如何在每个测试中更改 jest 模拟函数的返回值? [英] 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);
这篇关于如何在每个测试中更改 jest 模拟函数的返回值?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!