jest-extended icon indicating copy to clipboard operation
jest-extended copied to clipboard

New matchers: toHaveBeenCalledOnce and toHaveBeenCalledOnceWith

Open amercier opened this issue 7 years ago • 9 comments

I think it would be nice to add the following matchers for Mock:

toHaveBeenCalledOnce

const mock = jest.fn();
// ...
expect(mock).toHaveBeenCalledOnce();

that would be equivalent to:

const mock = jest.fn();
// ...
expect(mock).toHaveBeenCalledTimes(1);

toHaveBeenCalledOnceWith

const mock = jest.fn();
// ...
expect(mock).toHaveBeenCalledOnceWith('foo', 'bar');

that would be equivalent to:

const mock = jest.fn();
// ...
expect(mock).toHaveBeenCalledTimes(1);
expect(mock).toHaveBeenLastCalledWith('foo', 'bar');

Rationale

I find myself regularly writing tests with only one call per mock. Especially while writing unit tests, where I prefer writing many small, atomic tests, rather than one large test for all cases.

amercier avatar Jun 21 '18 07:06 amercier

This sounds like a really good matcher and i would find it helpful myself :)

benjaminkay93 avatar Jun 30 '18 09:06 benjaminkay93

if nothing else im happy to raise a pr for this

benjaminkay93 avatar Jun 30 '18 18:06 benjaminkay93

That would be a nice addition! There is something similar but not as semantic :

const mock = jest.fn();
expect(mock).toHaveBeenNthCalledWith(1, 'foo');

julianjurai avatar Jul 10 '18 13:07 julianjurai

Sounds great! Feel free to send a PR with this, just drop a note here if you are working on it :smile:

mattphillips avatar Jul 30 '18 14:07 mattphillips

Ive got a branch locally with a toHaveBeenCalledOnce matcher, it was queit straightforward, however the toHaveBeenCalledOnceWith is causing my brain issues, should we use === equality on objects or == equality on them?

benjaminkay93 avatar Jul 30 '18 21:07 benjaminkay93

@benjaminkay93 I think we probably want to do deep equality on them you can use the equals util to compare two objects deeply or the contains util to deeply check if an array contains an object

mattphillips avatar Jul 31 '18 09:07 mattphillips

Sweet thank you @mattphillips, big help

benjaminkay93 avatar Jul 31 '18 09:07 benjaminkay93

toHaveBeenCalledOnce added via #274, still missing toHaveBeenCalledOnceWith if anyone is up for it 🙂

SimenB avatar Oct 11 '21 08:10 SimenB

@SimenB - I'll take a look at toHaveBeenCalledOnceWith 😊

theryansmee avatar Mar 16 '22 19:03 theryansmee