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

10,459

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

Share:
10,459
jackhelsi
Author by

jackhelsi

Updated on June 14, 2022

Comments

  • jackhelsi
    jackhelsi almost 2 years

    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);
      });
    })
    });
    
  • VLAZ
    VLAZ over 3 years
    Also viable async () => result or () => Promise.resolve(result)
  • jackhelsi
    jackhelsi over 3 years
    .then((result) => { console.log('',result); resolve(result); }).catch((err) => { console.log('',err); });); Is it right?