jest-community/jest-extended

New matchers: toHaveBeenCalledOnce and toHaveBeenCalledOnceWith

amercier opened this issue ยท 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.

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

if nothing else im happy to raise a pr for this

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

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

Sounds great! Feel free to send a PR with this, just drop a note here if you are working on it ๐Ÿ˜„

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 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

Sweet thank you @mattphillips, big help

toHaveBeenCalledOnce added via #274, still missing toHaveBeenCalledOnceWith if anyone is up for it ๐Ÿ™‚

@SimenB - I'll take a look at toHaveBeenCalledOnceWith ๐Ÿ˜Š