mocha.jschaichai-as-promised

chai-as-promised should.eventually.equal not passing


I am trying to write a minimum working example of chai-as-promised in order to understand how it is working when testing functions that return a promise.

I have the following function:

simple.test = async (input) => {
    return input;
};

and the following test function:

chai.use(sinonChai);
chai.use(chaiAsPromised);
const { expect } = chai;
const should = chai.should();

describe('#Test', () => {
    it('test', () => {
        expect(simple.test(1)).should.eventually.equal(1);
    });
});

However, testing this results in the test not passing, but in a very long error, which is pasted here: https://pastebin.com/fppecStx

Question: Is there something wrong about the code, or what seems to be the problem here?


Solution

  • First: Your mixing expect and should. If you want to use should for assertion, you don't need expect.

    Second: To tell mocha that a test is async you have to either call done, return a Promise or use async/await.

    const chai = require('chai');
    const chaiAsPromised = require('chai-as-promised');
    const sinonChai = require('sinon-chai');
    
    const should = chai.should();
    chai.use(sinonChai);
    chai.use(chaiAsPromised);
    
    // Function to test
    const simple = {
      test: async (input) => {
        return input;
      }
    }
    
    // Test
    describe('#Test', () => {
      it('test', () => {
        return simple.test(1).should.eventually.equal(1);
      });
    });