Digged the types a bit more: the right way in TypeScript is jest. fn((args) => "foobar") : explicitely defining args will results in a better typings, and mock. calls[0][0] will be accepted by TypeScript. This is because if you use 2 args in your mock, mock.
Jest Mock Functions fn() . Returns a new, unused mock function.
To check if a component's method is called, we can use the jest. spyOn method to check if it's called. We check if the onclick method is called if we get the p element and call it.
To spy on an exported function in jest, you need to import all named exports and provide that object to the jest. spyOn function. That would look like this: import * as moduleApi from '@module/api'; // Somewhere in your test case or test suite jest.
Just use mockObject.calls. In my case I used:
const call = mockUpload.mock.calls[0][0]
Here's the documentation about the mock
property
Here is a simple way to assert the parameter passed.
expect(mockedFunction).toHaveBeenCalledWith("param1","param2");
I prefer lastCalledWith()
over toHaveBeenCalledWith()
. They are both the same but the former is shorter and help me reduce the cognitive load when reading code.
expect(mockedFn).lastCalledWith('arg1', 'arg2')
You can use toHaveBeenCalledWith()
together with expect.stringContaining
or expect.arrayContaining()
or expect.objectContaining()
...
const { host } = new URL(url);
expect(mockedFunction).toHaveBeenCalledWith("param1", expect.stringContaining(`http://${host}...`);
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