我在 __mocks__
中有一个手动模拟文件夹,名为 client.ts
.现在在我的单元测试中,我调用 jest.mock('./client')
.这工作正常,并开 Jest 导入了模拟文件夹。现在我有一个需要覆盖此行为的场景(测试)。我用了mockImplementationOnce
在单元测试中。
import mockClient from './client';
(mockClient.getObject as jest.Mock).mockImplementationOnce(() => {
console.log('calling the mock of the mock');
return Promise.resolve('abcde');
});
现在当我运行这个测试时,Jest 似乎仍然在
__mocks__
中加载手动模拟。文件夹而不是为此特定测试加载此模拟。我在这里错过了什么吗?
最佳答案
这应该有效:
import mockClient from './client';
test('getObject', async () => {
mockClient.getObject.mockImplementationOnce(() => {
console.log('calling the mock of the mock');
return Promise.resolve('abcde');
});
await mockClient.getObject();
})
我认为使用
mockImplementationOnce
是一个好习惯就在调用之前,以避免在 beforeEach
中的任何覆盖或任何其他冲突。
关于typescript - Jest mockImplementationOnce 不覆盖手动模拟,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58129020/