【问题标题】:Mocha tests sharing state because of bad scoping?由于范围界定不当,摩卡测试共享状态?
【发布时间】:2014-11-23 06:07:30
【问题描述】:

我有一个文件“mochatest.js”,看起来像这样:

(function(){
    var MyObject = function(){
        var myCount= 0;
        return{
            count: myCount
        };
    }();
    module.exports = MyObject 
})();

还有一个看起来像这样的 mocha 测试文件:

(function(){
 var assert = require("assert");

    describe("actual test", function(){

        it("should start with count of zero", function(){
            var obj = require("../mochatest.js");   
            assert.equal(obj.count, 0);
        }); 
        it("should be able to increment counter", function(){
            var obj = require("../mochatest.js");   
            obj.count=1;
            assert.equal(obj.count, 1);
        }); 
        it("should start with count of zero", function(){
            var obj = require("../mochatest.js");   
            assert.equal(obj.count, 0);
        }); 
    });
})();

我的第三个测试失败了:AssertionError: 1 == 0 所以感觉第二个测试中的 obj 与第三个测试中的 obj 相同。我希望它是一个新的。

我是否编写过类似单例的代码?为什么 count==1 在第三次测试中?我做错了什么?

【问题讨论】:

    标签: javascript mocha.js


    【解决方案1】:

    我想,我想通了。我改变了两者并得到了我预期的行为。

    (function(){
        var MyObj = function(){
            var myCount= 0;
            return{
                count: myCount
            };
        }  // <= note no more ();
        module.exports =MyObj; 
    })();
    

    以及我设置测试的方式(在 beforeEach 中仅一次)

    (function(){
     var assert = require("assert");
    
        describe("actual test", function(){
            var obj;
            beforeEach(function(done){
                var MyObject = require("../mochatest.js");  
                obj = new MyObject();
                done();
            });
            it("should start with count of zero", function(){
                assert.equal(obj.count, 0);
            }); 
            it("should be able to increment counter", function(){
                obj.count=1;
                assert.equal(obj.count, 1);
            }); 
            it("should start with count of zero", function(){
                assert.equal(obj.count, 0);
            }); 
        });
    })();
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2012-04-29
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2016-10-02
      • 2019-06-13
      • 1970-01-01
      相关资源
      最近更新 更多