typescript - 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
我不确定我应该写什么才能让它通过。
解决方案
您需要将 Promise 传递到expect
. 目前,您正在传递一个不返回任何内容的函数。改变
await expect(() => {
controller.addSkills(addSkillsDto)
}).rejects.toThrow()
到
await expect(controller.addSkills(addSkillsDto)).rejects.toThrow()
推荐阅读
- html - 是否可以将规则应用于标签嵌套中的特定标签?
- redux - 在 redux 中观察 redux-saga 动作
- google-bigquery - 使用源谷歌驱动器创建表模式并在 bigquery 表中加载数据
- service - 无法设置服务的优先级
- swift - 如何使用 SwiftUI 的 onDelete() 函数访问数组位置
- python - 用 OpenCV + Python 拼接四个图像
- swift - ScrollView 在关闭 ViewController 并调用 viewDidLoad 时不会重新加载
- python - 从网站抓取价格为零的问题
- python - 如何遍历 UnqLite 集合并提取数据
- flutter - 用于颤振的 Chopper 库时请求中的内容类型被覆盖