Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Jest: Change output of manual mock for different tests within a test suite

Let's say I have the following two files:

// index.js
...
import { IS_IOS } from 'common/constants/platform';
...
export const myFunction = () => (IS_IOS ? 'foo' : 'bar');


// index.test.js
...
import { myFunction } from './index';

jest.mock('common/constants/platform', () => ({ IS_IOS: true }));

describe('My test', () => {
  it('tests behavior on IOS', () => {
    expect(myFunction()).toBe('foo');
  });

  // --> Here I want to change the value of IS_IOS to false

  it('tests behavior if NOT IOS', () => {
    expect(myFunction()).toBe('bar');
  });
});

As you see my mocking function returns IS_IOS: true. I want it to return IS_IOS: false after my first test. How would I do that?


I also tried an adaptation of the solution here but I couldn't get it work, because there the mock returns a function:

module.exports = {
    foo: jest.genMockFunction();
}

whereas my mock should return a boolean value which is not called inside the file I'm testing. That's what I did here:

// common/constants/__mock__/platform
export const setIsIos = jest.fn(val => (IS_IOS = val));
export let IS_IOS;

// index.test.js
...
import { IS_IOS, setIsIos } from 'common/constants/platform';
jest.mock('common/constants/platform');

describe('My test', () => {
  setIsIos('foo');

  it('tests behavior on IOS', () => {
    expect(myFunction()).toBe('foo');
  });

  setIsIos('bar');

  it('tests behavior if NOT IOS', () => {
    expect(myFunction()).toBe('bar');
  });
});

Oddly when console-logging, i.e. console.log(IS_IOS); I get the expected values. The test however seems to use the original value, i.e. undefined.

like image 497
Andru Avatar asked Jun 01 '17 13:06

Andru


1 Answers

Add jest.resetModules() to the beforeEach() call of that describe() test suite:

describe('EventManager', () => {

  beforeEach(() => {
    jest.resetModules();
  });
  ...

Additionally I found A more complete example on how to mock modules with jest here

like image 193
David Schumann Avatar answered Nov 01 '22 03:11

David Schumann