【问题标题】:Can you combine toHaveBeenCalledWith and toHaveBeenCalledTimes in Jasmine?你能在 Jasmine 中结合 toHaveBeenCalledWith 和 toHaveBeenCalledTimes 吗?
【发布时间】:2020-01-18 05:20:28
【问题描述】:

我在 Jasmine 单元测试中使用这两个单独的断言。

expect(spyFunction).toHaveBeenCalledWith(expectedArgument);
expect(spyFunction).toHaveBeenCalledTimes(expectedCount);

如果我理解正确,这些将确认以下内容。

  • 该函数至少使用expectedArgument 调用一次,并且
  • 该函数总共被调用了expectedCount 次。

我想要做的是确认该函数是用expectedArgument 准确地expectedCount 次调用的。换句话说,我只想计算参数匹配的调用次数。

我意识到我可以用假货自己数数......

var callCount = 0;
spyOn(myInstance, 'myFunction').and.callFake(arg => {
  if (arg === expectedArgument) {
    callCount++;
  }
});

...

expect(callCount).toEqual(expectedCount);

...但这不具备以前语法的可读性,感觉就像在重新发明轮子。我没有用过 Jasmine,所以我想知道我是否遗漏了什么。

有没有办法使用内置的 Jasmine 匹配器进行断言?或者,有没有其他方法可以获得类似可读的语法?

【问题讨论】:

    标签: javascript jasmine


    【解决方案1】:

    您可以使用calls 从间谍那里获得更多详细信息。您可以像这样查看每个调用及其参数:

    expect(spyFunction.calls.count()).toBe(2)
    expect(spyFunction.calls.argsFor(0)).toEqual(/* args for 1st call */)
    expect(spyFunction.calls.argsFor(1)).toEqual(/* args for 2nd call */)
    

    详情请见Jasmine docs

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2014-02-01
      • 1970-01-01
      • 1970-01-01
      • 2023-04-06
      • 2012-11-15
      • 1970-01-01
      • 2017-09-21
      相关资源
      最近更新 更多