Search code examples
javascripttestingchaichai-as-promised

Chai as promised not telling me where an error occured


When I define a test that fails using normal chai like so:

it("Should fail 1", async () => {
    expect(1).to.equal(2);
});

I get the following error:

         Should fail 1:

      AssertionError: expected 1 to equal 2
      + expected - actual

      -1
      +2
      
      at /home/myComputer/tests/myTest.ts:10:26
      at Generator.next (<anonymous>)
      at new Promise (<anonymous>)
      at __awaiter (tests/myTest.ts:27:12)
      at Context.<anonymous> (tests/myTest.ts:45:33)
      at processImmediate (node:internal/timers:478:21)

I.e. the first line tells me my AssertionError comes from line 10 in myTest.ts.

When I try to test promises though, such as

it("my test 2", async () => {
    await expect(Promise.reject("test")).to.be.fulfilled;
});

I only get

         my test 2:
     AssertionError: expected promise to be fulfilled but it was rejected with 'test'

This is very annoying, as this error doesn't tell me anything about where in my test the error actually occured. How do I make it tell me where the error actually occured?

The way I import chai and chai-as-promised is like so in case that matters:

import chai from "chai";
import chaiAsPromised from 'chai-as-promised';
chai.use(chaiAsPromised);
const expect = chai.expect;

Solution

  • You should be able to see the line in error if you use chai.config.includeStack. Additionally, you need to chain off of the eventually property of chai-as-promised.

    import chai from "chai";
    import chaiAsPromised from 'chai-as-promised';
    chai.use(chaiAsPromised);
    
    chai.config.includeStack = true; // <--- Add this
    
    const expect = chai.expect;
    
    it("my test 2", async () => {
        // Add .eventually
        await expect(Promise.reject("test")).to.eventually.be.fulfilled;
    });
    

    A run of this for me looks like this:

    user@comp $ ./node_modules/.bin/mocha spec.js
    
    
      1) my test 2
    
      0 passing (5ms)
      1 failing
    
      1) my test 2:
         AssertionError: expected promise to be fulfilled but it was rejected with 'test'
          at assertIfNotNegated (node_modules/chai-as-promised/lib/chai-as-promised.js:68:19)
          at /Users/user/project/node_modules/chai-as-promised/lib/chai-as-promised.js:101:17
          at async Context.<anonymous> (file:///Users/user/project/spec.js:11:5)
    
    

    My package.json uses "type": "module".

    • Node v20.12.2
    • mocha v10.4.0
    • chai v4.4.1
    • chai-as-promised v7.1.1