我怎样才能使jest测试在任何抛出的错误上失败?
我试了一下,但还没有弄清楚语法。
test('getArcId => Error', async () => {
await expect(client.getArcId('skynet')).rejects.toThrow();
});
我收到错误消息
getArcId getArcId=&>;错误
expect(received).rejects.ToThrow()
接收的函数未引发
但是下面的测试通过了,所以我要测试的函数确实抛出了(至少在我对抛出含义的最好理解下是这样的):
test('getArcId => Error', async () => {
await client.getArcId('skynet').catch(e =>
expect(e.message).toBe('Command failure')
);
});
我无法使
it('throws on connection error', async () => {
expect.assertions(1);
await expect(nc.exec({ logger: true }))
.rejects.toEqual(Error('No command provided to proxy.'));
});
如果我拒绝的只是一个信息;
.rejects.toEqual('some message');
要使Jest异常处理按预期工作,请向其传递一个匿名函数,如:
test('getArcId => Error', async () => {
await expect(() => client.getArcId('skynet')).rejects.toThrow();
});
来自jest文档
test('throws on octopus', () => {
expect(() => {
drinkFlavor('octopus');
}).toThrow();
});
请注意匿名函数。是的,这让我有过几次:)
describe('getArcId()', () => {
it('should throw an error', async () => {
try {
await client.getArcId('skynet');
} catch (e) {
expect(e).toStrictEqual(Error('No command provided to proxy.'));
}
});
});