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

半腔热情 提交于 2020-01-07 06:25:53

问题


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


回答1:


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));


来源:https://stackoverflow.com/questions/47767279/how-to-test-for-a-propety-of-a-class-after-promise-resolution-with-mocha-and-cha

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!