Bea*_*ith 17
复制/面试失败:
it('This test will fail', done => {
done.fail(new Error('This is the error'))
})
Run Code Online (Sandbox Code Playgroud)
Cri*_*san 15
你可以通过抛出错误来做到这一点.例如:
test('Obi-Wan Kenobi', () => {
throw new Error('I have failed you, Anakin')
})
Run Code Online (Sandbox Code Playgroud)
Ras*_*ash 11
以下是某些答案不起作用的某些情况。在 的世界中async-await,像这样的 try-catch 逻辑是很常见的。
try {
await someOperation();
} catch (error) {
expect(error.message).toBe('something');
}
Run Code Online (Sandbox Code Playgroud)
现在想象一下,如果someOperation()以某种方式通过了,但您预计它会失败,那么该测试仍然会通过,因为它从未进入 catch 块。所以我们想要的是确保如果 someOperation 没有抛出错误,测试就会失败。
现在让我们看看哪些解决方案有效,哪些无效。
接受的答案在这里不起作用,因为投掷会再次被抓住。
try {
await someOperation();
throw new Error('I have failed you, Anakin');
} catch (error) {
console.log('It came here, and so will pass!');
}
Run Code Online (Sandbox Code Playgroud)
true === false 的答案也不起作用,因为断言也会抛出类似上面的错误,该错误将被捕获。
try {
await someOperation();
expect(true).toBe(false); // This throws an error which will be catched.
} catch (error) {
console.log('It came here, and so will pass!');
}
Run Code Online (Sandbox Code Playgroud)
对于这种情况,一种有效的解决方案(如@WhatWouldBeCool 的回答所示)如下。现在它明确地未通过测试。
try {
await someOperation();
fail('It should not have come here!')
} catch (error) {
console.log('It never came here!');
}
Run Code Online (Sandbox Code Playgroud)
Wha*_*ool 10
Jest实际上使用Jasmine,因此您可以fail像以前一样使用。
样品通话:
fail('it should not reach here');
Run Code Online (Sandbox Code Playgroud)
这是Jest的TypeScript声明文件中的定义:
declare function fail(error?: any): never;
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
14834 次 |
| 最近记录: |