Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 435
Li Wang Avatar asked Dec 15 '25 14:12

Li Wang


1 Answers

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.

like image 102
skyboyer Avatar answered Dec 17 '25 03:12

skyboyer



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!