【问题标题】:How to test multiple console outputs with Jest in JavaScript?如何在 JavaScript 中使用 Jest 测试多个控制台输出?
【发布时间】:2022-01-25 21:10:06
【问题描述】:

我需要这个解决方案来进行教育项目。此单元测试应检查函数的预期控制台输出:

it('should log into the console "Victoria lifting anchor up" and "Victoria is moving"', () => {

  const consoleSpy = jest.spyOn(console, 'log');

  victoria.move();

  expect(consoleSpy).toHaveBeenCalledWith(?);

});

问题是函数 victoria.move() 运行两个控制台日志,我想在一个单元测试中检查它们。该测试完美地适用于一个输出,但我不知道测试两个输出应该使用什么符号。我在网上苦苦寻找语法。

【问题讨论】:

    标签: javascript unit-testing junit jestjs babel-jest


    【解决方案1】:

    您可以使用consoleSpy.calls 属性。官方文档"using a mock function"中有一个例子。在您的情况下,可以这样做

    expect(mockCallback.mock.calls[0][0]).toBe('your value'); // first call, first argument
    expect(mockCallback.mock.calls[1][0]).toBe('your value');  // second call, first argument
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2015-04-25
      • 1970-01-01
      • 1970-01-01
      • 2017-12-07
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多