在Jest中,模拟(mocking)模块是一种常见的做法,用于隔离测试并确保测试的独立性。你可以在同一测试文件的不同测试中以不同的方式模拟同一个模块。以下是一些基础概念和相关方法:
假设我们有一个模块 mathUtils.js
,其中包含两个函数 add
和 subtract
:
// mathUtils.js
export const add = (a, b) => a + b;
export const subtract = (a, b) => a - b;
我们希望在不同的测试中以不同的方式模拟这个模块。
// __tests__/mathUtils.test.js
import * as mathUtils from '../mathUtils';
jest.mock('../mathUtils', () => {
return {
add: jest.fn(() => 10),
subtract: jest.fn(() => 5)
};
});
describe('mathUtils', () => {
beforeEach(() => {
jest.clearAllMocks();
});
it('should mock add function', () => {
expect(mathUtils.add(2, 3)).toBe(10);
expect(mathUtils.add).toHaveBeenCalledWith(2, 3);
});
it('should mock subtract function differently', () => {
mathUtils.subtract.mockImplementation((a, b) => a * b);
expect(mathUtils.subtract(2, 3)).toBe(6);
expect(mathUtils.subtract).toHaveBeenCalledWith(2, 3);
});
});
// __tests__/mathUtils.test.js
import * as mathUtils from '../mathUtils';
jest.mock('../mathUtils');
describe('mathUtils', () => {
beforeEach(() => {
jest.clearAllMocks();
});
it('should auto mock add function', () => {
mathUtils.add.mockReturnValue(10);
expect(mathUtils.add(2, 3)).toBe(10);
expect(mathUtils.add).toHaveBeenCalledWith(2, 3);
});
it('should auto mock subtract function differently', () => {
mathUtils.subtract.mockImplementation((a, b) => a * b);
expect(mathUtils.subtract(2, 3)).toBe(6);
expect(mathUtils.subtract).toHaveBeenCalledWith(2, 3);
});
});
jest.clearAllMocks()
)。jest.mock()
和 mockImplementation
。jest.spyOn()
来部分模拟特定函数。通过上述方法,你可以在同一测试文件的不同测试中灵活地模拟模块,确保每个测试的独立性和准确性。
领取专属 10元无门槛券
手把手带您无忧上云