Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Chai-As-Promised passes even when it is wrong

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",

like image 260
laiboonh Avatar asked Mar 12 '23 10:03

laiboonh


1 Answers

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);
  });
});
like image 194
robertklep Avatar answered Mar 22 '23 23:03

robertklep