在用摩卡和柴解决承诺后如何测试班级的戒备 [英] How to test for a propety of a class after promise resolution with mocha and chai

查看:84
本文介绍了在用摩卡和柴解决承诺后如何测试班级的戒备的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在按承诺对Mocha + 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
    });
});

测试通过.但我想检查诺言是否已解决后的z.x equals 1值.我该怎么办?

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

推荐答案

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

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

这篇关于在用摩卡和柴解决承诺后如何测试班级的戒备的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆