How to check multiple arguments on multiple calls for jest spies?
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 adrinkEach(drink, Array<flavor>)
function that appliesf
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.
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.
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');