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
?
mockFn.mockClear() Often this is useful when you want to clean up a mocks usage data between two assertions.
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.
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.
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With