如何为chai Expect提供用于摩卡单元测试的自定义错误消息? [英] How to provide chai expect with custom error message for mocha unit test?

查看:94
本文介绍了如何为chai Expect提供用于摩卡单元测试的自定义错误消息?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我使用chai的期望进行了摩卡测试:

I have a mocha test using 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)期望失败,则错误输出a不是对开发人员友好的:

Now if one to.be.greaterThan(0) expectation fails, the error output on mocha is not dev-friendly:

 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)

我想用更人性化的东西代替它。有没有办法告诉chai使用自定义错误消息?

I would like to replace it with something more human-friendly. Is there a way to tell chai to use a customize error message?

我希望能够像下面的伪代码一样使用它:

I want to be able to use it like this pseudo-code:

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

然后出现失败的摩卡错误:

And then the failing mocha error should print:

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


推荐答案

每个期望方法都接受可选参数 message

Every expect method accepts an optional parameter message:

expect(1).to.be.above(2, 'nooo why fail??');
expect(1, 'nooo why fail??').to.be.above(2);

因此,在您的情况下,应为:

So, in your case it should be:

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

这篇关于如何为chai Expect提供用于摩卡单元测试的自定义错误消息?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆