Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

React Jest test errors when using toHaveBeenNthCalledWith

I'm following Jest's documentation however I am not able to get around the following error. expect(dummyFunction).toHaveBeenNthCalledWith is not a function

Unless I'm missing something, I am pretty certain that I have my dummyFunction setup correctly as a jest.fn(). I even consoled the output of dummyFunction just before I use it in my tests and this is the output.

dummyFunction console.log output

    { [Function: mockConstructor]
      _isMockFunction: true,
      getMockImplementation: [Function],
      mock: [Getter/Setter],
      mockClear: [Function],
      mockReset: [Function],
      mockReturnValueOnce: [Function],
      mockReturnValue: [Function],
      mockImplementationOnce: [Function],
      mockImplementation: [Function],
      mockReturnThis: [Function],
      mockRestore: [Function] }

toHaveBeenCalledNthWith Test

const dummyFunction = jest.fn();

expect(dummyFunction).toHaveBeenCalledTimes(2); // pass

expect(dummyFunction).toHaveBeenNthCalledWith(1, { foo: 'bar' }); // error
expect(dummyFunction).toHaveBeenNthCalledWith(2, { please: 'work' });

Thanks in advance for the help.

like image 840
CWSites Avatar asked Sep 09 '26 02:09

CWSites


1 Answers

toHaveBeenNthCalledWith was released in Jest version 23.0.0 so you will see that error if you are using an earlier version of Jest.

Note that toHaveBeenNthCalledWith is just syntactic sugar for using spy.mock.calls[nth] so if you are using an earlier version of Jest you can just do the following:

const dummyFunction = jest.fn();

dummyFunction({ foo: 'bar' });
dummyFunction({ please: 'work' });

expect(dummyFunction).toHaveBeenCalledTimes(2); // pass

expect(dummyFunction.mock.calls[0]).toEqual([{ foo: 'bar' }]); // pass
expect(dummyFunction.mock.calls[1]).toEqual([{ please: 'work' }]); // pass
like image 173
Brian Adams Avatar answered Sep 11 '26 02:09

Brian Adams