Node.js sinon在并行执行中桩存函数导致失败的testing
我有两个testing用例testing相同的function只是采取两个不同的执行path,所以说明:
MyClass.prototype.functionBeingTested = function() { if (this.check1()) { this.isCheck1Called = true; } else if (this.check2()) { this.isCheck1Called = false; } else { ... } };
我的2个testing用例如下:
it('should take check1() execution path', function() { var myClass= new MyClass({}, {}, {}); var check1Stub sinon.stub(MyClass.prototype, 'check1'); check1Stub.returns(true); myClass.functionBeingTested(); myClass.isCheck1Called.should.equal(true); }); it('should take check2() execution path', function() { var myClass= new MyClass({}, {}, {}); var check2Stub sinon.stub(MyClass.prototype, 'check2'); check2Stub.returns(true); myClass.functionBeingTested(); myClass.isCheck1Called.should.equal(false); });
现在默认情况下, check1()
返回false,所以我不把它存储在第二个testing用例中,但是在第二个case运行的时候, check1()
函数存根仍然是活动的并且导致第二个case进入执行第一种情况的path很好,第二种情况下testing失败。
我知道这是一个并行testing的问题,第一个testing用例仍然使用第一个sinon存根,反正我可以解决这个问题吗?
在第一次testing结束时,您应该恢复原来的方法(这总是一件好事,以防止testing受到以前testing的影响):
check1Stub.restore()
或者,也可以使用Sinon 沙箱来运行每个testing:
describe('MyClass', function() { beforeEach(function() { this.sinon = sinon.sandbox.create(); }); afterEach(function() { this.sinon.restore(); }); it('should take check1() execution path', function() { var myClass = new MyClass({}, {}, {}); // `this.sinon` is the sandbox var check1Stub = this.sinon.stub(MyClass.prototype, 'check1'); check1Stub.returns(true); myClass.functionBeingTested(); myClass.isCheck1Called.should.equal(true); }); it('should take check2() execution path', function() { var myClass = new MyClass({}, {}, {}); var check2Stub = this.sinon.stub(MyClass.prototype, 'check2'); check2Stub.returns(true); myClass.functionBeingTested(); myClass.isCheck1Called.should.equal(false); }); });
(见mocha-sinon
,这完全一样)