How to use `toHaveBeenCalledOnce` in testing frameworks?

I want to verify that a specific function or mock was called exactly once in my test. While I’m aware of general toHaveBeenCalled or toHaveBeenCalledTimes methods in frameworks like Jest, I’d like to know the correct usage of toHaveBeenCalledOnce and how it differs from other similar assertions. How can I implement it effectively to ensure my function is invoked only once during test execution?

In Jest, there’s no built-in toHaveBeenCalledOnce matcher. Instead, you use toHaveBeenCalledTimes(1) to achieve the same effect:

const myFn = jest.fn();

myFn(); // call the function

expect(myFn).toHaveBeenCalledTimes(1);

This is exactly equivalent to “called once,” and it’s the standard approach in Jest. So whenever you see toHaveBeenCalledOnce in examples, it’s usually an alias from a custom matcher or another testing library.

If you really like the readability of toHaveBeenCalledOnce, you can add a custom matcher:

expect.extend({
  toHaveBeenCalledOnce(received) {
    const pass = received.mock.calls.length === 1;
    if (pass) {
      return { message: () => `Expected not to be called once`, pass: true };
    } else {
      return { message: () => `Expected to be called once, but was called ${received.mock.calls.length} times`, pass: false };
    }
  },
});

// Usage
const myFn = jest.fn();
myFn();
expect(myFn).toHaveBeenCalledOnce();

This can make your tests more expressive, especially for teams that prefer toHaveBeenCalledOnce over toHaveBeenCalledTimes(1).

In frameworks like Sinon, you have a similar helper:

const myFn = sinon.spy();
myFn();

sinon.assert.calledOnce(myFn); // verifies the function was called exactly once

Or in Jasmine, you can use:

spyOn(obj, 'method');
obj.method();

expect(obj.method).toHaveBeenCalledTimes(1);

So the key takeaway is: “called once” is universally handled via toHaveBeenCalledTimes(1) or framework-specific calledOnce methods. toHaveBeenCalledOnce is often just a more readable alias.