Search code examples
unit-testingpromisejestjses6-promisenestjs

NestJS Jest test expecting then catch finally


I am new to NestJS and have written a basic unit test for my service/controller using an example from a couple of sites including the official NestJS website and even before I try to run this code,

it('should be defined', async () => {

    const result:MyEntity[] = [{"test1":"value1"},{"test1":"value2"}];
    jest.spyOn(service, 'findAll').mockImplementation(() => result);

    expect(await controller.findAll()).toBe(result);
  });

I see the following error.

Type 'MyEntity[]' is missing the following properties from type 'Promise<MyEntity[]>': then, catch, [Symbol.toStringTag], finallyts(2739)
index.d.ts(1163, 33): The expected type comes from the return type of this signature.

I am returning a Promise from my controller but somehow the compiler is expecting a try catch finally somewhere but I don't know where this should go.


Solution

  • If service.findAll normally returns a promise, you should make the mock return a promise as well. You can do this with jest.spyOn(service, 'findAll').mockResolvedValue(result). Now in your test you can do expect(controller.findAll()).resovles.toEqual(result) to make the method resolve properly and test the result.