How to check multiple arguments on multiple calls for jest spies?
Asked Answered
P

11

166

I have the following function in a React component:

onUploadStart(file, xhr, formData) {
  formData.append('filename', file.name);
  formData.append('mimeType', file.type);
}

This is my test that at least gets the spy to be called:

const formData = { append: jest.fn() };
const file = { name: 'someFileName', type: 'someMimeType' };
eventHandlers.onUploadStart(file, null, formData);

expect(formData.append).toHaveBeenCalledWith(
  ['mimeType', 'someMimeType'],
  ['fileName', 'someFileName']
);

However, the assertion is not working:

Expected mock function to have been called with:
 [["mimeType", "someMimeType"], ["fileName", "someFileName"]]
But it was called with:
  ["mimeType", "someMimeType"], ["filename", "someFileName"]

What is the right way to use toHaveBeenCalledWith?

Pareto answered 13/10, 2016 at 10:15 Comment(0)
M
275

I was able mock multiple calls and check the arguments this way:

expect(mockFn.mock.calls).toEqual([
  [arg1, arg2, ...], // First call
  [arg1, arg2, ...]  // Second call
]);

where mockFn is your mocked function name.

Monocle answered 3/1, 2018 at 13:57 Comment(5)
this should be the "best answer"Hull
Also, note that if you don't know exactly what the parameters should be, you can use things like expect.objectContaining.Supervisor
I had to use this syntax to make it work: expect(mockFn.mock.calls.allArgs()).toEqual([ ...]);. For reference, I am using Jasmine version 4.Sandra
I am aware of toHaveBeenNthCalledWith, as mentioned in other answers, but I feel that this solution is terser and easier to read.Gastroenteritis
What if I don't want to test the order of the calls? Just the containing parameters?Hospodar
D
166

Since jest 23.0 there is .toHaveBeenNthCalledWith(nthCall, arg1, arg2, ....) https://jestjs.io/docs/expect#tohavebeennthcalledwithnthcall-arg1-arg2-

Also under the alias: .nthCalledWith(nthCall, arg1, arg2, ...)

If you have a mock function, you can use .toHaveBeenNthCalledWith to test what arguments it was nth called with. For example, let's say you have a drinkEach(drink, Array<flavor>) function that applies f to a bunch of flavors, and you want to ensure that when you call it, the first flavor it operates on is 'lemon' and the second one is 'octopus'. You can write:

test('drinkEach drinks each drink', () => {
  const drink = jest.fn();
  drinkEach(drink, ['lemon', 'octopus']);
  expect(drink).toHaveBeenNthCalledWith(1, 'lemon');
  expect(drink).toHaveBeenNthCalledWith(2, 'octopus');
});

Note: the nth argument must be positive integer starting from 1.

Dalliance answered 30/5, 2018 at 9:16 Comment(2)
While this link may assist in your answer to the question, you can improve this answer by taking vital parts of the link and putting it into your answer, this makes sure your answer is still an answer if the link gets changed or removed :)Swingletree
Even if not provided an example in the answer, this point is really valid! up to yoU!Hysteroid
R
38

You can also test toHaveBeenCalledWith and test multiple times for each expected parameter combination.

One example is Google Analytics plugin api uses the same function call with different parameter combinations.

function requireGoogleAnalyticsPlugins() {
  ...
  ga('create', 'UA-XXXXX-Y', 'auto');
  ga('require', 'localHitSender', {path: '/log', debug: true});
  ga('send', 'pageview');
}

To test this the below example tests that ga has been called three times with the various parameter combinations.

describe("requireGoogleAnalyticsPlugins", () => {
  it("requires plugins", () => {
    requireGoogleAnalyticsPlugins();
    expect(GoogleAnalytics.ga.toHaveBeenCalledTimes(3);
    expect(GoogleAnalytics.ga).toHaveBeenCalledWith('create', 'UA-XXXXX-Y', 'auto');
    expect(GoogleAnalytics.ga).toHaveBeenCalledWith('require', 'localHitSender', {path: '/log', debug: true});
    expect(GoogleAnalytics.ga).toHaveBeenCalledWith('send', 'pageview');
  });
});

In OP case you could test this with

expect(formData.append).toHaveBeenCalledWith('mimeType', 'someMimeType');
expect(formData.append).toHaveBeenCalledWith('fileName', 'someFileName');
Rego answered 7/9, 2018 at 1:45 Comment(0)
L
25

The signature is .toHaveBeenCalledWith(arg1, arg2, ...), where arg1, arg2, ... means in a single call (see).

If you want to test multiple calls, just expect it multiple times.

Unfortunately, I have not yet found a method to test the order of multiple calls.

Lashonda answered 13/10, 2016 at 11:19 Comment(2)
I believe I've addressed how to use a single expect (see my answer below).Monocle
This method does not work/supported - unfortunately!Deictic
S
11

You can also create an array of the expected arguments per call and loop over it:

const expectedArgs = ['a', 'b', 'c', 'd']
expectedArgs.forEach((arg, index) => 
    expect(myFunc).toHaveBeenNthCalledWith(index + 1, arg))

This solution considers the order of the calls. If you do not care about the order, you can use toHaveBeenCalledWith without the index instead.

Slight answered 24/4, 2020 at 10:29 Comment(2)
This checks the order of the calls, not just that they have all happened (which may or may not be desired). But toHaveBeenNthCalledWith wants 1 if it is checking the first call, not 0, so the index is off by one.Misconception
@JacobRaihle Thanks for pointing that out. :) I have updated the answer according to your comment.Slight
L
9

Another solution based on Andi's one. Select the call you want and check the value of the arguments. In this example the first call is selected:

expect(mockFn.mock.calls[0][0]).toEqual('first argument');
expect(mockFn.mock.calls[0][1]).toEqual('second argument');

I recommend to check this Jest cheatsheet:

https://devhints.io/jest

Lipcombe answered 1/2, 2019 at 10:36 Comment(0)
A
3

To reset the count of the mocks, you can call jest.clearAllMocks.

This is most useful in a beforeEach between tests.

beforeEach(() => jest.clearAllMocks());
Adjure answered 3/11, 2021 at 15:56 Comment(0)
P
2

As a lot of sync calling happened, I encountered some calls the order would be different. Thanks for this post, so I got a way to validate this and ignore the orders.

expect(mockFn.mock.calls).toMatchObject(expect.arrayContaining(
  [
      objectContaining(oneOfYourObject)
  ],
  [
      objectContaining(oneOfYourObject)
  ],
  [
      objectContaining(oneOfYourObject)
  ]
));
Poyssick answered 26/10, 2022 at 21:45 Comment(0)
D
1

There is another solution for Jasmine:

expect($.fn.get.calls.allArgs()).toEqual([[], [1, 3], ['yo', 'ho']])

More details here: https://github.com/jasmine/jasmine/issues/228

Discontinuity answered 21/6, 2023 at 12:16 Comment(0)
P
0

This worked for me as well...initial page load does a default search...user interaction and click search does another search...needed to verify the search process augmented the search values correctly...

let model = {
        addressLine1: null,
        addressLine2: null,
        city: null,
        country: "US"};
let caModel = { ...model, country: "CA" };
const searchSpy = props.patientActions.searchPatient;
expect(searchSpy.mock.calls).toEqual([[{ ...model }], [{ ...caModel }]]);
Packaging answered 21/5, 2018 at 19:26 Comment(0)
F
0

You can use .calls on your spy that returns a Calls interface with amongst others the following method:

/** will return the arguments passed to call number index **/
argsFor(index: number): any[];

So then you can do the following:

const formData = { append: jest.fn() };
const file = { name: 'someFileName', type: 'someMimeType' };
eventHandlers.onUploadStart(file, null, formData);

expect(formData.append).toHaveBeenCalledTimes(2);
expect(formData.append.argsFor(0)).toEqual(
  ['fileName', 'someFileName']
);
expect(formData.append.argsFor(1)).toEqual(
  ['mimeType', 'someMimeType'],
);
Fatherly answered 3/12, 2021 at 7:50 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.