首页 > 解决方案 > Jest Matcher 错误:收到的值必须是承诺或返回承诺的函数

问题描述

我是一名 TDD 从业者,我正在尝试实现一个异常。

这是测试代码:

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

以下是相关代码:

  @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,
      }
  }

这是运行 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

我不确定我应该写什么才能让它通过。

标签: typescriptexceptionpromisejestjsnestjs

解决方案


您需要将 Promise 传递到expect. 目前,您正在传递一个不返回任何内容的函数。改变

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

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

推荐阅读