【问题标题】:How to test for a propety of a class after promise resolution with mocha and chai如何在使用 mocha 和 chai 解决承诺后测试类的属性
【发布时间】:2018-05-25 19:45:31
【问题描述】:

我正在按照承诺尝试使用 Mocha + Chai 进行一些单元测试

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

测试确实通过了。但是我想检查一下承诺后z.x equals 1 的值是否已经解决。我该怎么做?

这只是一个原型。我想在我的真实案例中测试更多的属性

【问题讨论】:

    标签: mocha.js chai chai-as-promised


    【解决方案1】:

    chai-as-promised 添加到 Chai 的断言本身就是承诺。所以你可以在这些断言上调用.then。因此,在您的情况下,请将您的 return 更改为:

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2016-09-22
      • 1970-01-01
      • 2015-10-28
      • 2017-07-22
      • 2017-12-29
      • 2019-08-21
      • 2021-10-03
      • 2016-06-19
      相关资源
      最近更新 更多