A M*_*eto 1 exception promise typescript jestjs nestjs
我是 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()
}
)
Run Code Online (Sandbox Code Playgroud)
下面是相关代码:
@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,
}
}
Run Code Online (Sandbox Code Playgroud)
这是运行 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
Run Code Online (Sandbox Code Playgroud)
我不确定我应该写什么来让它通过。
您需要将 Promise 传递到expect. 目前,您正在传入一个不返回任何内容的函数。改变
await expect(() => {
controller.addSkills(addSkillsDto)
}).rejects.toThrow()
Run Code Online (Sandbox Code Playgroud)
到
await expect(controller.addSkills(addSkillsDto)).rejects.toThrow()
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
2858 次 |
| 最近记录: |