Javascript 使用 Chai.js 测试失败
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/33756027/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Fail a test with Chai.js
提问by Sionnach733
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 实现相同目标的最佳方法是什么?
回答by Dmytro Shevchenko
There's assert.fail()
. You can use it like this:
有assert.fail()
。你可以这样使用它:
assert.fail(0, 1, 'Exception not thrown');
回答by hashchange
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()
@DmytroShevchenko 提到的那样——但通常,可以避免这些拐杖并以更好的方式表达测试的意图,如果测试失败,这将导致更有意义的消息.
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 docsfor more.
当然,你可以通过检查更具体的错误类型细化测试,预期的错误信息等。见.throw
的柴文档为多。
回答by Nigrimmist
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
回答by Frank Nocke
I also stumbled that here was no direct fail(msg)
.
For some time, I worked around with...
我也偶然发现这里没有直接的fail(msg)
。有一段时间,我与...
assert.isOk(false, 'timeOut must throw')
(Using this in places that should not be reachable, i.e. 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 本身本质上与 assert.isOK 相同……我最喜欢的是:
assert(false,'timeOut must throw')
…well, almost as short as assert.fail(…
.
……嗯,几乎和assert.fail(…
.
回答by Hemadri Dasari
I did this way
我是这样做的
const expect = require('chai').expect;
const exists = true;
expect(!exists).to.throw('Unknown request type');