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.
Since the assertion statement is asynchronous code, you should return the assertion statement so that
mochawill know that it should wait for this function to be called to complete the test.Please read the doc about
chai-as-promisedand asynchronous-code ofmocha.