Javascript 如何为chai expect提供用于mocha单元测试的自定义错误消息?

Javascript 如何为chai expect提供用于mocha单元测试的自定义错误消息?,javascript,node.js,typescript,chai,Javascript,Node.js,Typescript,Chai,我用chai's expect进行了摩卡咖啡测试: it("should parse sails out of cache file", async () => { const sailExtractor = new Extractor(); const result = await sailExtractor.extract("test.xml"); try { expect(result.length).to.be.greaterThan(0)

我用chai's expect进行了摩卡咖啡测试:

it("should parse sails out of cache file", async () => {
    const sailExtractor = new Extractor();
    const result = await sailExtractor.extract("test.xml");

    try {
        expect(result.length).to.be.greaterThan(0);
        const withMandatoryFlight = result.filter((cruises) => {
            return cruises.hasMandatoryFlight === true;
        });
        expect(withMandatoryFlight.length).to.be.greaterThan(0);
        const cruiseOnly = result.filter((cruises) => {
            return cruises.hasMandatoryFlight === false;
        });

        expect(cruiseOnly.length).to.be.greaterThan(0);

        return Promise.resolve();
    } catch (e) {
        return Promise.reject(e);
    }
}
现在,如果一个
to.be.greaterThan(0)
预期失败,那么mocha上的错误输出对开发人员不友好:

 AssertionError: expected 0 to be above 0
      at Assertion.assertAbove (node_modules/chai/lib/chai/core/assertions.js:571:12)
      at Assertion.ctx.(anonymous function) [as greaterThan] (node_modules/chai/lib/chai/utils/addMethod.js:41:25)
      at _callee2$ (tests/unit/operator/croisiEurope/CroisXmlExtractorTest.js:409:61)
      at tryCatch (node_modules/regenerator-runtime/runtime.js:65:40)
      at Generator.invoke [as _invoke] (node_modules/regenerator-runtime/runtime.js:303:22)
      at Generator.prototype.(anonymous function) [as next] (node_modules/regenerator-runtime/runtime.js:117:21)
      at fulfilled (node_modules/tslib/tslib.js:93:62)
      at <anonymous>
      at process._tickDomainCallback (internal/process/next_tick.js:228:7)
然后失败的mocha错误应打印:

 AssertionError: It should parse at least one sail out of the flatfile, but result is empty

如果对断言使用
should
,则可以向测试函数传递一个字符串,如果条件失败,该字符串将被写出。例如:

result.length.should.be.above(0, "It should parse at least one sail out of the flatfile, but result is empty");

我不确定这在expect中是否可行。API似乎没有提到它。

每个
expect
方法都接受一个可选参数
消息

expect(1).to.be.above(2, 'nooo why fail??');
expect(1, 'nooo why fail??').to.be.above(2);
因此,在您的情况下,应该是:

expect(result.length)
  .to.be.greaterThan(0, "It should parse at least one sail out of the flatfile, but result is empty");

OP正在使用
chai
,但您的答案似乎也适用于该库。或者,您可以使用
expect(result.length,'It should parse…).to.be.greaterThan(0)
Sidenote:由于我使用的是typescript,我可以通过跳入
greaterThan
方法找到它,因为它的类型声明为,并且显示了可选的消息参数。这对我不起作用,但是自定义消息是。我意识到这已经很旧了,但只是为了确认这在语法
myCollection.should.have.length(1,“oopsy”)中确实适用。奇怪的是@liminal18却没有。谢谢你的回答!
expect(result.length)
  .to.be.greaterThan(0, "It should parse at least one sail out of the flatfile, but result is empty");