How to ensure chai expect with a special error message for mocha unit test?

I have a mocha test using chai 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);
    }
}

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

 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)

I would like to replace it with something more convenient for people. Is there any way to tell chai to use a configuration error message?

I want to use it like this pseudocode:

 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 error of the unsuccessful mocha should print:

 AssertionError: It should parse at least one sail out of the flatfile, but result is empty
+4
source share
2 answers

Each method expectaccepts 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");
+3

should , , , . :

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

, . API, , .

0

Source: https://habr.com/ru/post/1683698/


All Articles