Li Wang
Li Wang

Reputation: 111

How do I mock chained function in jest?

I use jest to test my node.js code. I need to connect to mongodb using mongoose. But I don't know how to mock the chained function.

the function I need to mock(Vessels is a module):

return await Vessels.find({}).exec();

the way I tried to mock, but it fails:

 Vessels.find.exec = jest.fn(() => [mockVesselResponse]);

I want to mock chained function Vessels.find({}).exec(), anyone here can helps me, thanks.

Upvotes: 3

Views: 2619

Answers (2)

Marco Martins
Marco Martins

Reputation: 127

You can mock the function in the return of the value.

jest.fn().mockReturnValue({ exec: () => vesselMockObject })

Upvotes: 0

skyboyer
skyboyer

Reputation: 23705

Naïve way is to mock method find that would return object with method exec(check Jest docs on ways to mock modules for details):

import Vessels from '/path/to/vessels';

jest.mock('/path/to/vessels'); 
Vessels.prototype.find.mockReturnThis();
Vessels.prototype.exclude.mockReturnThis();
Vessels.prototype.anyOtherChainingCallMethod.mockReturnThis();

it('your test', () => {
   Vessels.prototype.exec.mockResolvedValueOnce([youdata]);
   // your code here
});

but it seems to me quite long way with a lot of manual work on mocking every single internal method.

Instead I propose you mocking one level deeper. Say with mocking mongoose models with mockingoose.

Have never worked with mongoose so cannot provide sample for this approach.

Upvotes: 2

Related Questions