Jest:在测试套件中更改手动模拟的输出以用于不同的测试

时间:2017-06-01 13:55:29

标签: javascript unit-testing mocking jestjs

我们说我有以下两个文件:

// 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');
  });
});

如您所见,我的模拟函数返回IS_IOS: true。我希望它在第一次测试后返回IS_IOS: false。我该怎么做?

我还尝试了the solution here的改编,但我无法使其正常工作,因为mock会返回一个函数:

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

而我的mock应返回一个布尔值,该值不在我测试的文件中调用。 这就是我在这里所做的:

// 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');
  });
});

奇怪的是,当控制台记录时,即console.log(IS_IOS);我得到了预期值。然而,测试似乎使用原始值,即undefined

1 个答案:

答案 0 :(得分:1)

jest.resetModules()添加到该beforeEach()测试套件的describe()调用中:

describe('EventManager', () => {

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

此外,我还找到了一个关于如何用笑话here模拟模块的更完整的示例

相关问题