如何在每次测试中更改笑话模拟函数的返回值? [英] how to change jest mock function return value in each test?
问题描述
我的组件测试文件中有一个类似这样的模拟模块
I have a mock module like this in my component test file
jest.mock('../../../magic/index', () => ({
navigationEnabled: () => true,
guidanceEnabled: () => true
}));
这些函数将在我的组件的渲染函数中调用,以隐藏和显示某些特定功能.
these functions will be called in render function of my component to hide and show some specific feature.
我想对这些模拟函数的返回值的不同组合进行快照.
I want to take a snapshot on different combinations of the return value of those mock functions.
假设我有一个这样的测试用例
for suppose I have a test case like this
it('RowListItem should not render navigation and guidance options', () => {
const wrapper = shallow(
<RowListItem type="regularList" {...props} />
);
expect(enzymeToJson(wrapper)).toMatchSnapshot();
});
要运行此测试用例,我想动态地将模拟模块函数的返回值更改为false
to run this test case I want to change the mock module functions return values to false
like this dynamically
jest.mock('../../../magic/index', () => ({
navigationEnabled: () => false,
guidanceEnabled: () => false
}));
因为我已经一次导入了RowListItem
组件,所以我的模拟模块不会再次重新导入.所以它不会改变.我该如何解决?
because i am importing RowListItem
component already once so my mock module wont re import again. so it wont change. how can i solve this ?
推荐答案
您可以模拟该模块,以便它返回间谍并将其导入到您的测试中:
You can mock the module so it returns spies and import it into your test:
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);
这篇关于如何在每次测试中更改笑话模拟函数的返回值?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!