Skh*_*haz 2 javascript typescript jestjs
我正在编写一个应该可以捕获异常的测试
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)
})
})
Run Code Online (Sandbox Code Playgroud)
我很确定这client.request
会引发异常,但 Jest 说:
收到的函数没有抛出
const test = async () => {
...
}
Run Code Online (Sandbox Code Playgroud)
检查方法是否正确?
如果我改为
expect(t()).toThrow(Error)
Run Code Online (Sandbox Code Playgroud)
我有
expect(received).toThrow(expected)
Matcher error: received value must be a function
Received has type: object
Received has value: {}
Run Code Online (Sandbox Code Playgroud)
您可以使用拒绝
it('should return unauthorized response', async () => {
await expect(client.request('listUsers', {})).rejects.toThrow(/* error you are expecting*/);
})
Run Code Online (Sandbox Code Playgroud)
或者
您可以使用 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 */)
})
Run Code Online (Sandbox Code Playgroud)
您可以检查错误type of
和error message
归档时间: |
|
查看次数: |
480 次 |
最近记录: |