簡體   English   中英

你可以在 Jasmine 中結合 toHaveBeenCalledWith 和 toHaveBeenCalledTimes 嗎?

[英]Can you combine toHaveBeenCalledWith and toHaveBeenCalledTimes in Jasmine?

我在 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 匹配器來做出我的斷言? 或者,是否有另一種方法可以獲得類似的可讀語法?

您可以使用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 文檔

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM