[]' is missing the following properties from type 'Promise<Cats[]>': then, catch, [Symbol.toStringTag], finally ts(2739)

Viewed 17249

I am new in typescript and nestjs and I am trying to learn nest js, But when I am trying to Unit test my code then result variable gives me an error shown in the title? Anyone helps me to try to find what I am doing wrong here.

describe('cats', () => {
  let controller: CatsController;
  let service: CatsService;
  beforeEach(async () => {
    const module: TestingModule = await Test.createTestingModule({
      controllers: [DeliveryController],
    }).compile();

    controller = module.get<CatsController>(CatsController);
  });
describe('', () => {
  it('should return an array of cats', async () => {
    const result = [
{
id: "1",
name: "Cat",
type: "hybrid"
}
          ];
    jest.spyOn(service, 'getCats').mockImplementation(() => result); //'result' in this line shows error

    expect(await controller.getAllCats()).toBe(result);
  });
})
});
1 Answers

You're returning an array, but your function is async, meaning it should return a Promise of the array. There's two ways you can go about this.

  1. use mockResolvedValue() instead of mockImplementation(). This will make Jest return a promise of what you tell it to.
  2. use mockImplementation(() => new Promise((resolve, reject) => resolve(result))) to return a promise instead of the result.^

Both of these do the same thing, so the choice is yours, but the first is definitely easier to read.

^ as noted by VLAZ, this can be anything that returns a promise, including using mockImplementation(async () => result) or mockImplementation(() => Promise.resolve(result))

Related