【发布时间】:2021-11-20 18:26:33
【问题描述】:
如何从 Jest 中的模拟函数中清除间谍?如果原始函数不是jest.fn(),jest.restoreAllMocks() 工作得非常好。如何正确清除来自jest.fn() 的所有间谍?这个问题可能与How to change mock implementation on a per single test basis [Jestjs] 重复,尽管我的问题描述了一个不涉及多个模块的更简单的场景。
describe('Mock', () => {
const mock = {
method1: jest.fn().mockReturnValue(false),
};
afterEach(() => {
// none of these clear the spy
jest.clearAllMocks();
jest.resetAllMocks();
jest.restoreAllMocks();
});
it('returns false by default', () => {
expect(mock.method1()).toEqual(false);
});
it('changes return value after applying spy implementation', () => {
jest.spyOn(mock, 'method1').mockReturnValue(true);
expect(mock.method1()).toEqual(true);
});
// this test fails
it('resets to original value after each test', () => {
expect(mock.method1()).toEqual(false);
});
});
【问题讨论】:
-
为什么在你监视已经是模拟的东西?
-
@jonrsharpe 我想更改每个测试中特定模拟函数的返回值,以测试不同的场景。我想在每个测试中更改 mockReturnValue 很好,但是我猜 method1 从一开始就不应该是 jest.fn() 吗?我使用了 jest.fn() 以便我可以调用 method1 并检查调用参数,而无需创建额外的间谍来检查。
标签: javascript unit-testing jestjs mocking