Javascript Jest expect异常不使用异步
我正在编写一个测试,应该可以捕获一个异常Javascript Jest expect异常不使用异步,javascript,typescript,jestjs,Javascript,Typescript,Jestjs,我正在编写一个测试,应该可以捕获一个异常 description('unauthorized',()=>{ const client=jayson.client.http({ 主机:“localhost”, 港口:港口,, 路径:'/bots/uuid', }) 它('应返回未经授权的响应',异步()=>{ const t=async()=>{ 等待client.request('listUsers',{}) } expect(t()).toThrow(错误) }) }) 我很确定,clien
description('unauthorized',()=>{
const client=jayson.client.http({
主机:“localhost”,
港口:港口,,
路径:'/bots/uuid',
})
它('应返回未经授权的响应',异步()=>{
const t=async()=>{
等待client.request('listUsers',{})
}
expect(t()).toThrow(错误)
})
})
我很确定,client.request
正在引发异常,但Jest说:
收到的函数没有抛出
const test=async()=>{
...
}
正确的检查方法是什么
更新
如果我换成
expect(t()).toThrow(错误)
我得到
expect(已收到)。toThrow(预期)
匹配器错误:收到的值必须是函数
接收到的类型为:对象
接收到的值:{}
您可以使用
或
您可以使用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 */)
})
您可以检查的错误
类型和错误消息
您可能需要等待测试
函数,因为此时它只是一个未解析的异步函数,因此它没有抛出。异步函数返回承诺,可能会拒绝,但不会抛出错误。您还可以使用ToStriteQual代替toBe,并添加作为参数抛出的异常<代码>预期(错误).toStrictEqual(异常)代码>
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 */)
})