提问人:Rodrigo 提问时间:2/2/2021 最后编辑:Rodrigo 更新时间:2/2/2021 访问量:7673
开玩笑期望异常不适用于异步 [重复]
Jest expect exception not working with async [duplicate]
问:
我正在编写一个测试,据说应该捕获异常
describe('unauthorized', () => {
const client = jayson.Client.http({
host: 'localhost',
port: PORT,
path: '/bots/uuid',
})
it('should return unauthorized response', async () => {
const t = async () => {
await client.request('listUsers', {})
}
expect(t()).toThrow(Error)
})
})
我很确定这引发了一个异常,但 Jest 说:client.request
接收函数未抛出
const test = async () => {
...
}
检查方法是否正确?
更新
如果我更改为
expect(t()).toThrow(Error)
我得到了
expect(received).toThrow(expected)
Matcher error: received value must be a function
Received has type: object
Received has value: {}
答:
22赞
lissettdm
2/2/2021
#1
您可以使用拒绝
it('should return unauthorized response', async () => {
await expect(client.request('listUsers', {})).rejects.toThrow(/* error you are expecting*/);
})
或
你可以使用try/catch
it('should return unauthorized response', async () => {
const err= null;
try {
await client.request('listUsers', {});
} catch(error) {
err= error; //--> if async fn fails the line will be executed
}
expect(err).toBe(/* data you are expecting */)
})
您可以检查错误和type of
error message
评论
1赞
Anurag Phadnis
4/20/2021
您还可以使用 toStrictEqual 代替 toBe,并将抛出的异常添加为参数。expect(err).toStrictEqual(Exception);
评论
test