【发布时间】:2021-05-27 16:52:07
【问题描述】:
我有一个程序按此顺序发出三个post 请求
- http://myservice/login
- http://myservice/upload
- http://myservice/logout
代码看起来像这样
async main() {
try {
await this.login()
await this.upload()
} catch (e) {
throw e
} finally {
await this.logout()
}
}
每个方法在失败时都会抛出自己的错误。
我正在使用 Jest 来监视底层请求库(超级代理)。对于一项特定的测试,我想测试如果上传函数抛出错误,则正在发出注销post 请求。
我通过抛出异常来模拟 post 请求。
const superagentStub = {
post: () => superagentStub
}
const postSpy = jest.spyOn(superagent, 'post')
.mockImplementationOnce(() => superagentStub)
.mockImplementationOnce(() => { throw new Error() })
.mockImplementationOnce(() => superagentStub)
const instance = new ExampleProgram();
expect(async () => await instance.main()).rejects.toThrow(); // This is fine
expect(postSpy).toHaveBeenNthCalledWith(3, 'http://myservice/logout')
如果我不模拟第三个实现,测试将失败,因为logout() 将抛出自己的error,因为第三个post 请求将作为实时调用失败。
本案例中的间谍报告仅对底层库的 post 方法进行了 1 次调用。
- http://myservice/login
我觉得这很奇怪,因为我期待 3 次呼叫间谍
- http://myservice/login
- http://myservice/upload -> 但它会引发错误
- http://myservice/logout
【问题讨论】:
标签: javascript unit-testing jestjs