jest 单元测试中的 Funcs 如何覆盖
要覆盖 Jest 单元测试中的 Funcs,您可以使用 jest.mock() 函数来模拟或替换该函数的实现。这将允许您在测试中定义自己的函数实现,以便对其进行覆盖。
以下是一个示例:
// funcs.js
export const add = (a, b) => {
return a + b;
};
// test.js
import { add } from './funcs';
jest.mock('./funcs', () => ({
add: jest.fn(),
}));
describe('add', () => {
it('should return the sum of two numbers', () => {
add.mockReturnValue(5);
expect(add(2, 3)).toBe(5);
});
});
在这个例子中,我们使用 jest.mock() 函数来模拟 funcs.js 模块,并将 add 函数替换为一个 Jest mock 函数。然后,我们可以使用 add.mockReturnValue() 来定义 add 函数的返回值。
在这个测试中,我们期望 add(2, 3) 的结果为 5,因为我们在 add.mockReturnValue(5) 中定义了这样的返回值。
这样,我们就成功地覆盖了 Funcs 中的 add 函数,使其在单元测试中返回我们所期望的值
原文地址: https://www.cveoy.top/t/topic/iQGe 著作权归作者所有。请勿转载和采集!