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.
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.
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