[英]Fail a test with Chai.js
In JUnit you can fail a test by doing: 在JUnit中,您可以通过执行以下操作来使测试失败:
fail("Exception not thrown");
What's the best way to achieve the same using Chai.js? 使用Chai.js实现相同目标的最佳方法是什么?
There's assert.fail()
. 有assert.fail()
。 You can use it like this: 你可以像这样使用它:
assert.fail(0, 1, 'Exception not thrown');
There are many ways to fake a failure – like the assert.fail()
mentioned by @DmytroShevchenko –, but usually, it is possible to avoid these crutches and express the intent of the test in a better way, which will lead to more meaningful messages if the tests fail. 伪造失败的方法有很多 - 比如assert.fail()
提到的assert.fail()
,但通常可以避免这些拐杖并以更好的方式表达测试的意图,这将导致更有意义的测试失败时的消息。
For instance, if you expect a exception to be thrown, why not say so directly: 例如,如果您希望抛出异常,为什么不直接这样说:
expect( function () {
// do stuff here which you expect to throw an exception
} ).to.throw( Error );
As you can see, when testing exceptions, you have to wrap your code in an anonymous function. 如您所见,在测试异常时,您必须将代码包装在匿名函数中。
Of course, you can refine the test by checking for a more specific error type, expected error message etc. See .throw
in the Chai docs for more. 当然,您可以通过检查更具体的错误类型,预期的错误消息等来优化测试。请参阅Chai文档中的 .throw
以获取更多信息。
I also stumbled that here was no direct fail(msg)
. 我也发现这里没有直接fail(msg)
。 For some time, I worked around with... 一段时间以来,我一直在努力......
assert.isOk(false, 'timeOut must throw')
(Using this in places that should not be reachable, ie in promise-testing…) (在无法访问的地方使用此功能,即在承诺测试中......)
Chai is compatible with standard ES6 errors, so this works: Chai与标准的ES6错误兼容,因此这有效:
throw new Error('timeOut must throw')
…or, since assert itself is essentially the same as assert.isOK … my favourite is: ...或者,因为断言本身与assert.isOK基本相同 ......我最喜欢的是:
assert(false,'timeOut must throw')
…well, almost as short as assert.fail(…
. ......好吧,几乎和assert.fail(…
一样短assert.fail(…
Just try 试一试
expect.fail("custom error message");
or 要么
should.fail("custom error message");
as decribed in chai docs : https://www.chaijs.com/api/bdd/#method_fail 如chai docs所述: https : //www.chaijs.com/api/bdd/#method_fail
I did this way 我这样做了
const expect = require('chai').expect;
const exists = true;
expect(!exists).to.throw('Unknown request type');
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.