【问题标题】:How to clear spies from mock functions in Jest如何从 Jest 中的模拟函数中清除间谍
【发布时间】: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


【解决方案1】:

要从 Jest 中的模拟函数中清除间谍,我们可以使用 jest.clearAllMocks() 命令。

【讨论】:

  • 这不适用于我的用例,请查看我提供的代码。
猜你喜欢
  • 1970-01-01
  • 2020-08-13
  • 2019-04-20
  • 1970-01-01
  • 2020-05-26
  • 2018-09-14
  • 1970-01-01
  • 1970-01-01
  • 2021-02-27
相关资源
最近更新 更多