gpt4 book ai didi

javascript - 如何在每次测试前重置 Jest 模拟函数调用计数

转载 作者:IT王子 更新时间:2023-10-29 03:06:19 25 4
gpt4 key购买 nike

我是 Jest 的新手,我正在尝试使用它来测试函数是否被调用。我注意到 mock.calls.length 并没有为每个测试重置,而是在累积。如何在每次测试前将其设为 0?我不希望我的下一次测试取决于上一次的结果。

我知道 Jest 中有 beforeEach - 我应该使用它吗?重置 mock.calls.length 的最佳方法是什么?谢谢你。

代码示例:

求和.js:

import local from 'api/local';

export default {
addNumbers(a, b) {
if (a + b <= 10) {
local.getData();
}
return a + b;
},
};

求和.test.js

import sum from 'api/sum';
import local from 'api/local';
jest.mock('api/local');

// For current implementation, there is a difference
// if I put test 1 before test 2. I want it to be no difference

// test 1
test('should not to call local if sum is more than 10', () => {
expect(sum.addNumbers(5, 10)).toBe(15);
expect(local.getData.mock.calls.length).toBe(0);
});

// test 2
test('should call local if sum <= 10', () => {
expect(sum.addNumbers(1, 4)).toBe(5);
expect(local.getData.mock.calls.length).toBe(1);
});

最佳答案

我找到的一种处理方法:在每次测试后清除模拟函数:

添加到 Sum.test.js:

afterEach(() => {
local.getData.mockClear();
});

如果您想在每次测试后清除所有模拟函数,请使用 clearAllMocks

afterEach(() => {
jest.clearAllMocks();
});

关于javascript - 如何在每次测试前重置 Jest 模拟函数调用计数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47812801/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com