Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I get the arguments called in jest mock function?

People also ask

How do you mock an argument in Jest?

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.

What does Jest fn () return?

Jest Mock Functions fn() . Returns a new, unused mock function.

How do you check if a function is called in Jest?

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.

How do you spy on functions in Jest?

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}...`);