1

I've got a function I want to test. It returns a promise. Here'a fake version that just waits a bit and then resolves the promise.

function testee(){
    let myPromise = new Promise(
        (resolve, reject) => {
            setTimeout( () => {               
                resolve( 777 );
            }, 1000);
        }
     );
 
    return myPromise;
}

I'm using Mocha, Chai and ChaiAsPromised, and I try to test using eventually, thinking this will wait for the promise to resolve. I'm deliberately writing a test that should fail, and it passes. Why?

var chai = require('chai')  ;
var chaiAsPromised = require("chai-as-promised");
var expect = chai.expect;
chai.use(chaiAsPromised);

describe("Testing Promises", function() {
    it("should return a particular value ", function() {

     const testPromise = testee();

     // no matter what I specify in the equal it always passes the test
     expect(testPromise).to.eventually.equal(490);
});

I'm aware there are other ways to manage asynch processing under Mocha, or to avoid using Promises, but I want to understand why my tests don't fail as I would expect.

djna
  • 54,992
  • 14
  • 74
  • 117

1 Answers1

2

Since the assertion statement is asynchronous code, you should return the assertion statement so that mocha will know that it should wait for this function to be called to complete the test.

Please read the doc about chai-as-promised and asynchronous-code of mocha.

const { testee } = require('.');
var chai = require('chai');
var chaiAsPromised = require('chai-as-promised');
var expect = chai.expect;
chai.use(chaiAsPromised);

describe('Testing Promises', function () {
  it('should return a particular value ', function () {
    const testPromise = testee();
    return expect(testPromise).to.eventually.equal(777);
  });
});
djna
  • 54,992
  • 14
  • 74
  • 117
Lin Du
  • 88,126
  • 95
  • 281
  • 483
  • Thank you, I had somehow missed the very clearly documented need to return when using expect. – djna Jul 02 '21 at 05:37
  • alternatively if you are using async/await, you can just make the inner function async then `await expect(testPromise).to.eventually.equal(777)` – Andy Feb 16 '23 at 15:18