【问题标题】:Test if functions were called with arguments测试是否使用参数调用函数
【发布时间】:2018-07-24 19:14:54
【问题描述】:

所以...我只是想检查我的 sut 是否以这种方式使用依赖项,它是否会被调用至少 N 次并带有适当的参数。如果没有查找.mock.calls 条目并找到合适的条目的肮脏技巧,我无法找到一种方法。理想情况下,我希望代码看起来像这样:

it('...', () => {
  const dependency = jest.fn();
  const sut = createSut(dependency);

  sut();

  // that is of course wrong because of syntax but it shows what I want:
  expect(dependency).toBeCalledWith({ some: 'arguments' }).times(5);

  // this doesn't work - if at least one call was made it will always pass
  for (let i = 0; i < 5: ++i)
    expect(dependency).toBeCalledWith({ some: 'arguments' });

  // this doesn't work either, 'cause at least one proper call will make tests pass
  expect(dependency.mock.calls.length).toBeGreaterThanOrEqual(5);
  expect(dependency).toBeCalledWith({ some: 'arguments' });
});

是否可以在不使用其他库(如 chai)的情况下在 jest 中获取我想要的内容?

【问题讨论】:

    标签: javascript unit-testing jestjs


    【解决方案1】:

    您应该能够使用jests's matchers 编写测试。

    // Called just 5 times
    expect(dependency).toHaveBeenCalledTimes(5);
    
    // Called with same argument
    [1,2,3,4,5].forEach(time => {
      expect(dependency).toHaveBeenNthCalledWith(time, {
        some: 'arguments',
      });
    });
    
    // Called with different arguments
    const expectedArguments = [
      {some: 'arguments'},
      null,
      14,
      {some:'arguments'},
      {some:'arguments'},
    ];
    
    expectedArguments.forEach((argument, index) => {
      const callNumber = index + 1;
      expect(dependency).toHaveBeenNthCalledWith(callNumber, argument);
    });
    

    【讨论】:

    • 不,我不能。我不想绑定到实际的调用顺序。如果使用以下参数调用dependency 会怎样:{some: 'arguments'}, null, 14, then 4 time {some:'arguments'} - 我仍然希望这种行为通过测试。
    • 一旦你有了一个预期参数列表,Jest 就会随之而来。查看更新的示例。
    • 我想你不明白。我不想知道我的依赖项可能会以什么其他参数被调用,也不想知道以何种顺序调用,以免将自己锁定以应对 SUT 的未来重构。因此,我看到的唯一选择是过滤 .mock.calls 集合。我只是想知道是否有更好的选择。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-10-24
    • 1970-01-01
    • 2016-11-16
    • 2020-10-14
    • 1970-01-01
    相关资源
    最近更新 更多