Chai.js 测试失败
Fail a test with Chai.js
在 JUnit 中,您可以通过以下方式使测试失败:
fail("Exception not thrown");
使用 Chai.js 实现相同目标的最佳方法是什么?
有assert.fail()
。你可以这样使用它:
assert.fail(0, 1, 'Exception not thrown');
有很多方法可以伪造失败——就像@DmytroShevchenko 提到的 assert.fail()
——但通常,可以避免这些拐杖并以更好的方式表达测试的意图,这如果测试失败,将导致更有意义的消息。
例如,如果您希望抛出异常,为什么不直接说:
expect( function () {
// do stuff here which you expect to throw an exception
} ).to.throw( Error );
如您所见,在测试异常时,您必须将代码包装在匿名函数中。
当然,您可以通过检查更具体的错误类型、预期的错误消息等来优化测试。有关更多信息,请参阅 Chai docs 中的 .throw
。
我也无意中发现这里没有直接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(…
一样短。
我是这样做的
const expect = require('chai').expect;
const exists = true;
expect(!exists).to.throw('Unknown request type');
试试
expect.fail("custom error message");
或
should.fail("custom error message");
如 chai 文档中所述:https://www.chaijs.com/api/bdd/#method_fail
在 JUnit 中,您可以通过以下方式使测试失败:
fail("Exception not thrown");
使用 Chai.js 实现相同目标的最佳方法是什么?
有assert.fail()
。你可以这样使用它:
assert.fail(0, 1, 'Exception not thrown');
有很多方法可以伪造失败——就像@DmytroShevchenko 提到的 assert.fail()
——但通常,可以避免这些拐杖并以更好的方式表达测试的意图,这如果测试失败,将导致更有意义的消息。
例如,如果您希望抛出异常,为什么不直接说:
expect( function () {
// do stuff here which you expect to throw an exception
} ).to.throw( Error );
如您所见,在测试异常时,您必须将代码包装在匿名函数中。
当然,您可以通过检查更具体的错误类型、预期的错误消息等来优化测试。有关更多信息,请参阅 Chai docs 中的 .throw
。
我也无意中发现这里没有直接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(…
一样短。
我是这样做的
const expect = require('chai').expect;
const exists = true;
expect(!exists).to.throw('Unknown request type');
试试
expect.fail("custom error message");
或
should.fail("custom error message");
如 chai 文档中所述:https://www.chaijs.com/api/bdd/#method_fail