【发布时间】:2016-02-18 18:29:06
【问题描述】:
在 JUnit 中,您可以通过以下方式使测试失败:
fail("Exception not thrown");
使用 Chai.js 实现相同目标的最佳方法是什么?
【问题讨论】:
标签: javascript node.js chai
在 JUnit 中,您可以通过以下方式使测试失败:
fail("Exception not thrown");
使用 Chai.js 实现相同目标的最佳方法是什么?
【问题讨论】:
标签: javascript node.js chai
试试吧
expect.fail("custom error message");
或
should.fail("custom error message");
如 chai 文档中所述:https://www.chaijs.com/api/bdd/#method_fail
【讨论】:
我是这样做的
const expect = require('chai').expect;
const exists = true;
expect(!exists).to.throw('Unknown request type');
【讨论】:
我还偶然发现这里没有直接的fail(msg)。
有一段时间,我和...一起工作过......
assert.isOk(false, 'timeOut must throw')
(在不应该到达的地方使用它,即在promise-testing中......)
Chai 与标准 ES6 错误兼容,因此可以:
throw new Error('timeOut must throw')
…或者,因为assert itself is essentially the same as assert.isOK…我最喜欢的是:
assert(false,'timeOut must throw')
……嗯,几乎和assert.fail(…一样短。
【讨论】:
有很多方法可以伪造失败——比如@DmytroShevchenko 提到的assert.fail()——但通常可以避免这些拐杖并以更好的方式表达测试的意图,这将导致更多如果测试失败,则发出有意义的消息。
例如,如果您希望抛出异常,为什么不直接说:
expect( function () {
// do stuff here which you expect to throw an exception
} ).to.throw( Error );
如您所见,在测试异常时,您必须将代码包装在匿名函数中。
当然,您可以通过检查更具体的错误类型、预期的错误消息等来优化测试。有关更多信息,请参阅Chai docs 中的.throw。
【讨论】:
有assert.fail()。你可以这样使用它:
assert.fail(0, 1, 'Exception not thrown');
【讨论】: