我试着用笑话把我的大脑围绕在以下几点上:resetAllMocks
,resetModules
,resetModuleRegistry
和restoreAllMocks
我发现这很难。
我读了jest文档,但它不太清楚。我将不胜感激,如果有人能为我提供一个例子,如何上述工作,他们是不同的。
发布于 2021-02-25 09:32:56
感谢@sepehr的回答。
我认为通过示例来理解会更容易一些。
快速提示:
clear
在使用之前reset
restore
。import {Calculator} from './calculator';
describe('calculator add', function () {
let calculator = new Calculator();
const mockAdd = jest.spyOn(calculator, 'add');
it('mock the add method', function () {
calculator.add = mockAdd.mockReturnValue(5);
expect(calculator.add(1, 2)).toBe(5);
});
it('because we didnt clear mock, the call times is 2', function () {
expect(calculator.add(1, 2)).toBe(5);
expect(mockAdd).toHaveBeenCalledTimes(2);
});
it('After clear, now call times should be 1', function () {
jest.clearAllMocks();
expect(calculator.add(1, 2)).toBe(5);
expect(mockAdd).toHaveBeenCalledTimes(1);
});
it('we reset mock, it means the mock has no return. The value would be undefined', function () {
jest.resetAllMocks();
expect(calculator.add(1, 2)).toBe(undefined);
});
it('we restore the mock to original method, so it should work as normal add.', function () {
jest.restoreAllMocks();
expect(calculator.add(1, 2)).toBe(3);
});
});
https://stackoverflow.com/questions/58151010
复制相似问题