Nomura Nori
Nomura Nori

Reputation: 5187

How to mock mongoose query like findOne()?

I am going to mock mongooose function find(). This is what I have tried.

1)

jest.mock("./user.model")
UserModel.findOne.mockResolvedValue(await UserModel.findOne({email: "[email protected]"}))

2)

const findOne = jest.fn();
findOne.mockResolvedValue(await UserModel.findOne({email: "[email protected]"}))

But both not working, What is solution? I would like to make findOne of UserModel to return specific record always.

Thanks

Upvotes: 1

Views: 6504

Answers (1)

Enrique Saez
Enrique Saez

Reputation: 2700

assuming that UserModel is a mongoose model instance, you can probably do something along the lines of:

jest.spyOn(UserModel, 'findOne').mockReturnValue(Promise.resolve({ email: "[email protected]" }))

Some jest references:

Upvotes: 6

Related Questions