我想放弃使用jest.resetModules
,因为我想重置两个模块,但是在所有运行中都保留一个。
我的原始代码无法正常工作,就像这样:
beforeEach(() => {
jest.resetModules();
require('hooks/useMyProvider');
const useMyProvider = require('#/');
api = useMyProvider(); // scoped above
})
然后在每个测试中,我会做这样的事情:
// Mock hook since we can't spy on a function
jest.doMock('#/hooks/useActive', () => {
return () => {
return [true]
}
});
// re-require the component that requires useActive so it pulls latest mock
let MyComponent = require('#/components/MyComponent')
const { container } = render(<MyComponent />);
我尝试重构为在文件顶部定义一次useMyProvider
,然后从jest.resetModules
中删除beforeEach
;
然后我这样做了:
let MyComponent;
jest.isolateModules(() => {
jest.doMock('#/hooks/useActive', () => {
return () => {
return [true]
}
});
MyComponent = require('#/components/MyComponent')
});
const { container } = render(<MyComponent />);
当我在两次测试中执行此操作,然后将true
换成false
时,无论哪个测试先到都会坚持下去。自从隔离模块以来,我希望每次都会更改它。