摩卡测试共享状态,因为范围不好

Mocha tests sharing state because of bad scoping?

本文关键字:范围 因为 测试 共享 状态 摩卡      更新时间:2023-09-26

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

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

和一个看起来像这样的摩卡测试文件:

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

我的第三个测试失败了:断言错误:1 == 0,所以感觉第二个测试中的 obj 与第三个测试中的 obj 相同。我预计它会是一个新的。

我是否编写了类似单例的东西?为什么在第三次测试中计数==1?我做错了什么?

我想

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

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

以及我设置测试的方式(每个测试之前只有一次)

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