Jest Matcher error: received value must be a promise or a function returning a promise

Viewed 8408

I am a TDD practitioner and I am trying to implement an Exception.

Here is the test code:

  it.each([[{ id: '', token: '', skills: [''] }, 'Unknown resource']])(
    'should return an Exception when incorrect dto data',
    async (addSkillsDto: AddSkillsDto) => {
      await expect(() => {
        controller.addSkills(addSkillsDto)
      }).rejects.toThrow()
    }
  )

Here is the related code:

  @Post('candidate/add-skills')
  async addSkills(
    @Body() skills: AddSkillsDto,
  ): Promise<StandardResponseObject<[]>> {
    const data = await this.candidateService.addSkills(skills)
    console.log(data, !data)
    if (!data) throw new HttpException('Unknown resource', HttpStatus.NOT_FOUND)
    else
      return {
        success: true,
        data,
        meta: null,
        message: ResponseMessage.SKILLS_ADDED,
      }
  }

Here is the console output when running Jest:

● Candidate Controller › should return an Exception when incorrect dto data

    expect(received).rejects.toThrow()

    Matcher error: received value must be a promise or a function returning a promise

    Received has type:  function
    Received has value: [Function anonymous]

      88 |       await expect(() => {
      89 |         controller.addSkills(addSkillsDto)
    > 90 |       }).rejects.toThrow()
         |                  ^
      91 |     }
      92 |   )
      93 |

      at Object.toThrow (../node_modules/expect/build/index.js:226:11)
      at candidate/candidate.controller.spec.ts:90:18

  console.log
    null true

      at CandidateController.addSkills (candidate/candidate.controller.ts:75:13)

Test Suites: 1 failed, 1 total

I am not sure what I am suppose to write to make it pass.

1 Answers

You need to pass a Promise into expect. Currently, you're passing in a function which doesn't return anything. Change

await expect(() => {
  controller.addSkills(addSkillsDto)
}).rejects.toThrow()

to

await expect(controller.addSkills(addSkillsDto)).rejects.toThrow()
Related