reactjs - 如何在每个测试中更改 Jest 模拟函数的返回值?

标签 reactjs react-native jestjs enzyme

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

  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 组件一次,所以我的模拟模块不会再次重新导入。所以它不会改变。我该如何解决这个问题?

最佳答案

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

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);

关于reactjs - 如何在每个测试中更改 Jest 模拟函数的返回值?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45758366/

相关文章:

javascript - 引用错误: document is not defined Jest React Testing Library

javascript - react native 相机在导航时变成空白

javascript - 防止 parent 被点击,同时允许 child 捕捉触摸

javascript - React Redux 测试失败,因为它无法通过操作获取数据

ecmascript-6 - "SyntaxError: Unexpected token export"将 Jest 与 babel 7+ 结合使用

javascript - 使用 React 和 Express 阻止跨域请求

javascript - 如果 JSON 字段不存在,则 JSX 跳过

javascript - React router Link标签在目标="_blank"上呈现不同的路由

javascript - 使用 React-navigation 的 React Native 中的模态窗口

rxjs - 无法从 'rxjs/testing' 找到模块 'jasmine-marbles.umd.js'