我有两个测试,看起来像:
import someThing from '../someThing';
jest.mock('../someThing');
describe('group', () => {
it('test #1', async () => {
someThing.someFunction.mockImplementation(() => 123);
});
it('test #2', async () => {
someThing.someFunction.mockImplementation(() => 456);
});
});
我看到一个问题,似乎在第二个测试中调用了第一个测试中的 mockImplementation。如果我禁用 test #1 test# 2 会按预期工作。 (我的实际代码比这更复杂)。我需要一个单独的模拟的原因是一个应该返回失败结果,一个应该返回一个成功的给定相同的输入。
据我所知,JEST 并行运行所有测试,所以我假设发生的事情是模拟实现正在被两个测试同时修改,因为它是相同的导入。
最佳答案
几乎从不希望测试相互影响。
根据经验,Jest spies 需要在两次测试之间恢复到原始状态:
beforeEach(() => {
jest.restoreAllMocks();
jest.clearAllMocks();
});
或者最好使用 Jest restoreMocks
无条件地应用于所有测试和 clearMocks
配置选项。不这样做会导致测试交叉污染。
解决方法是使用
*Once
方法,正如另一个答案所描述的那样。与 *restore*
一起使用时,它们仅用于单个测试中的顺序模拟。From what I understand, JEST runs all test in parallel
Jest 并行运行测试文件。至于单项测试,情况并非如此,除非
concurrent
测试正在使用中。
关于javascript - JEST 模拟是否可能被彼此覆盖?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/67260803/