4
const chaiAsPromised = require('chai-as-promised');
const chai = require('chai');
const expect = chai.expect;
chai.use(chaiAsPromised);

describe('[sample unit]', function() {
  it('should pass functionToTest with true input', function() {   
    expect(Promise.resolve({ foo: "bar" })).to.eventually.have.property("meh");
  });
});

This test passes??? I am using "chai": "3.5.0", "chai-as-promised": "5.2.0",

laiboonh
  • 1,377
  • 1
  • 9
  • 19

1 Answers1

7

expect(...) returns a promise itself, which will either be resolved or rejected, depending on the test.

For Mocha to test the outcome of that promise, you need to explicitly return it from the test case (this works because Mocha has built-in promise support):

describe('[sample unit]', function() {
  it('should pass functionToTest with true input', function() {   
    return expect(Promise.resolve({ foo: "bar" })).to.eventually.have.property("meh");
  });
});

Alternatively, you can use Mocha's "regular" callback-style async setup and chai-as-promised's .notify():

describe('[sample unit]', function() {
  it('should pass functionToTest with true input', function(done) {   
    expect(Promise.resolve({ foo: "bar" })).to.eventually.have.property("meh").notify(done);
  });
});
robertklep
  • 198,204
  • 35
  • 394
  • 381
  • .notify(done) is important piece when you have UnhandledPromise exception. otherwise your test will pass in mocha, with this unhandled exception trace – PKV Aug 01 '18 at 14:05
  • @PrashantSinha I would recommend using the first example, returning the promise instead of using the callback. Makes more sense in a promise-based workflow. – robertklep Aug 01 '18 at 14:46