use*_*776 4 error-handling unit-testing typescript jestjs
如何在抛出任何错误时使玩笑测试失败?
我已经尝试了一些,但还没有掌握语法。
test('getArcId => Error', async () => {
await expect(client.getArcId('skynet')).rejects.toThrow();
});
Run Code Online (Sandbox Code Playgroud)
我收到错误消息
getArcId › getArcId => 错误
期望(收到)。拒绝。toThrow()
收到的函数没有抛出
但是,以下测试通过了,因此我打算测试的函数确实抛出了(至少就我对 throw 含义的理解而言):
test('getArcId => Error', async () => {
await client.getArcId('skynet').catch(e =>
expect(e.message).toBe('Command failure')
);
});
Run Code Online (Sandbox Code Playgroud)
为了使 Jest 异常处理按预期工作,请向其传递一个匿名函数,例如:
test('getArcId => Error', async () => {
await expect(() => client.getArcId('skynet')).rejects.toThrow();
});
Run Code Online (Sandbox Code Playgroud)
来自笑话文档
test('throws on octopus', () => {
expect(() => {
drinkFlavor('octopus');
}).toThrow();
});
Run Code Online (Sandbox Code Playgroud)
请注意匿名函数。是的,这让我好几次了:)
小智 7
我无法开始toThrow()工作,但像这样进行测试确实有效;
it('throws on connection error', async () => {
expect.assertions(1);
await expect(nc.exec({ logger: true }))
.rejects.toEqual(Error('No command provided to proxy.'));
});
Run Code Online (Sandbox Code Playgroud)
如果我只拒绝一条消息;
.rejects.toEqual('some message');
Run Code Online (Sandbox Code Playgroud)
describe('getArcId()', () => {
it('should throw an error', async () => {
try {
await client.getArcId('skynet');
} catch (e) {
expect(e).toStrictEqual(Error('No command provided to proxy.'));
}
});
});
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
6606 次 |
| 最近记录: |