Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to check multiple arguments on multiple calls for jest spies?

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?

like image 509
Andreas Köberle Avatar asked Oct 13 '16 10:10

Andreas Köberle


People also ask

Which method is useful to clean up a mock's usage data between two assertions?

mockFn.mockClear() ​ Often this is useful when you want to clean up a mocks usage data between two assertions.

What does jest fn () do?

The Jest library provides the jest. fn() function for creating a “mock” function. An optional implementation function may be passed to jest. fn() to define the mock function's behavior and return value.

What is jest spyOn?

Jest's spyOn method is used to spy on a method call on an object. It is also very beneficial in cases where the Jest mock module or mock function might not be the best tool for the job on hand. While writing unit tests you only test one particular unit of code, generally a function.

What is mocking in jest?

Mock functions allow you to test the links between code by erasing the actual implementation of a function, capturing calls to the function (and the parameters passed in those calls), capturing instances of constructor functions when instantiated with new , and allowing test-time configuration of return values.


1 Answers

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.

like image 160
Andi Avatar answered Sep 30 '22 11:09

Andi