Home > OS >  How mock then and catch in jest with mongoose
How mock then and catch in jest with mongoose

Time:01-25

I'm trying to run a jest spyOn on a mongoose method that contains a promise.

but it is returning me an error: Received message: "Cannot read properties of null (reading 'then')"

I have a repository with this function:

async getByEndpointId(endpointId: string) {
 return await this._requestModel.find({endpointId})
  .then((request) => request.filter((req) => !req.deleted))
  .catch((error) -> console.log("One Error"))
}

When I try to test with jest this way:

jest.spyOn(mockEndpointModel, 'find').mockReturnValue(value as any)

The runntime show me this error:

Received message: "Cannot read properties of null (reading 'then')"

if I remove the then and catch methods my test works

CodePudding user response:

Why are you mocking a promise rather than having Jest mock a resolve or reject which is a promise? jest.spyOn(mockEndpointModel, 'find').mockResolvedValue(value) or jest.spyOn(mockEndpointModel, 'find').mockRejectedValue(new Error('Something bad happened')

This repo has a bunch of Nest unit testing samples and might be useful to you

CodePudding user response:

I solved the problem by doing it this way:

jest.spyOn(mockEndpointModel, 'find').mockReturnValue({ then: jest.fn().mockResolvedValueOnce(value), } as any); 
  • Related