Home > OS >  How do you unit test unique method calls in Jasmine/Jest?
How do you unit test unique method calls in Jasmine/Jest?

Time:09-24

I have code in my application where a certain function is called n-times (lets call this function foo). The runtime expectation is that each invocation of foo is unique (called with a unique set of arguments). I had a recent bug manifest in my app due to foo being called with the same set of arguments more than once.

I want to write a test case where I can assert that foo was uniquely called once with a specific set of args but I'm at a loss at how to do so in Jasmine/Jest.

I know Jasmine has the toHaveBeenCalledOnceWith matcher but that asserts that foo was called "exactly once, and exactly with the particular arguments" which is not what I'm looking for in this scenario.

CodePudding user response:

You can combine toHaveBeenCalledWith() and toHaveBeenCalledTimes() to get your desired behaivor, you just need to have as many toHaveBeenCalledWith()s as the number of calls you were expecting:

for ex:

describe("test", () => {
  it("should call not more than unique", () => {
     spyOn(callsFoo, 'foo');
     callsFoo.somethingThatCallsFoo();
     expect(callsFoo.foo).toHaveBeenCalledTimes(2);
     expect(callsFoo.foo).toHaveBeenCalledWith({...someArgs});
     expect(callsFoo.foo).toHaveBeenCalledWith({...otherUnique});
  });
})

This would fail if there were repeated calls that weren't unique.

  • Related