Reputation: 861
I have a chained mock function inside another mock function, I need to spy both of them but I don't know how to spy the second one.
This is an example:
res = {
status: jest.fn(() => {
return {
json: jest.fn()
}
})
}
expect(res.status).toBeCalled() // This works
expect(res.status.json).toBeCalled() // This does not
expect(res.status().json).toBeCalled() // This does neither
Upvotes: 0
Views: 750
Reputation: 1098
Now you can use https://jestjs.io/docs/en/mock-function-api#mockfnmockreturnthis
Like this:
const res = {
status: jest.fn().mockReturnThis(),
send: jest.fn()
};
// call function and pass res
expect(res.status).toHaveBeenCalledTimes(1);
expect(res.status).toHaveBeenCalledWith(200);
expect(res.send).toHaveBeenCalledTimes(1);
expect(res.send).toHaveBeenCalledWith("Something");
In app:
res.status(200).send("Something");
Upvotes: 2
Reputation: 861
I found the solution here: Spying on chained method calls with Jest not working
The trick is to separate definitions:
json = { json: jest.fn() }
res = {
status: jest.fn(() => json)
}
Upvotes: 2