mocha.jschaichai-as-promised

How to test for a propety of a class after promise resolution with mocha and chai


I am trying out a bit of unit testing with Mocha + Chai as promised

'use strict';
var chai = require('chai').use(require('chai-as-promised'))
var should = chai.should();


describe('Testing how promises work', () => {
    it("should work right", function(){
        class SomeClass {
            constructor() {
                this.x = 0;
            }
            getSomething(inputVal) {
                let self = this;
                return new Promise((resolve, reject) => {
                    setTimeout(function(){
                        if(inputVal){
                            self.x = 1;
                            resolve();
                        }
                        else{
                            self.x = -1;
                            reject();
                        }

                    }, 10);
                });
            }
        }

        var z = new SomeClass();

        return z.getSomething(true).should.eventually.be.fulfilled
    });
});

Test does pass. But I would like to check if the value of z.x equals 1 after the promise has been resolved. How do I do that?

this is just a prototype. I would like to test more that one property in my real case


Solution

  • The assertions that chai-as-promised adds to Chai are themselves promises. So you can call .then on those assertions. So in your case, change your return to:

    return z.getSomething(true).should.eventually.be.fulfilled
        .then(() => z.should.have.property("x").equal(1));