小编典典

在每次测试中如何更改笑话模拟函数的返回值?

reactjs

我的组件测试文件中有一个像这样的模拟模块

  jest.mock('../../../magic/index', () => ({
    navigationEnabled: () => true,
    guidanceEnabled: () => true
  }));

这些函数将在我的组件的渲染函数中调用以隐藏和显示某些特定功能。

我想对这些模拟函数的返回值的不同组合进行快照。

假设我有一个这样的测试用例

 it('RowListItem should not render navigation and guidance options', () => {
    const wrapper = shallow(
      <RowListItem type="regularList" {...props} />
    );
    expect(enzymeToJson(wrapper)).toMatchSnapshot();
  });

要运行此测试用例,我想更改模拟模块函数的返回值以使其false动态变化

jest.mock('../../../magic/index', () => ({
    navigationEnabled: () => false,
    guidanceEnabled: () => false
  }));

因为我RowListItem已经一次导入了组件,所以我的模拟模块不会再次重新导入。所以它不会改变。我该如何解决?


阅读 260

收藏
2020-07-22

共1个答案

小编典典

您可以模拟该模块,以便它返回间谍并将其导入您的测试中:

import {navigationEnabled, guidanceEnabled} from '../../../magic/index'

jest.mock('../../../magic/index', () => ({
    navigationEnabled: jest.fn(),
    guidanceEnabled: jest.fn()
}));

然后,您可以使用 mockImplementation

navigationEnabled.mockImplementation(()=> true)
//or
navigationEnabled.mockReturnValueOnce(true);

并在下一个测试中

navigationEnabled.mockImplementation(()=> false)
//or
navigationEnabled.mockReturnValueOnce(false);
2020-07-22