Sinon TypeError:尝试包装运行多个脚本时已包装的<method>

在使用sinon.js(和mocha)进行testing时出现错误。 当我通过npm运行所有的testing脚本时发生错误,但是当我通过IDE运行单个脚本时不会发生错误。 单独运行testing脚本工作正常,testing通过。

即我有一个目录中有几个testing脚本。 当我自己运行一个脚本时,testing通过。 当我在目录中运行所有的脚本时,tess失败,出现错误:

testing将失败

TypeError: Attempted to wrap getVariable which is already wrapped 

而其他testing失败:

 TypeError: Cannot read property 'restore' of undefined 

两个testing脚本都以相同的代码开始:

 const assert = require('assert'), sinon = require('sinon'); global.context = { getVariable: function(s) {} }; var contextGetVariableMethod; beforeEach(function () { contextGetVariableMethod = sinon.stub(context, 'getVariable'); }); afterEach(function () { contextGetVariableMethod.restore(); }); 

我猜摩卡同时运行两个testing? testing正在互相干扰。 我很困惑为什么testing的范围不是独立的,但也许是它的global使用?

谢谢

根据Sinon JS文档,如果你有var stub = sinon.stub(object, "method");
你必须用object.method.restore();来恢复object.method.restore();

所以,在你的情况下:

 afterEach(function () { context.getVariable.restore() }); 

我想我已经设法解决这个问题。 正在为我工​​作的解决scheme是重新声明在beforeEach方法中被桩入的对象。

例如:

 const assert = require('assert'), sinon = require('sinon'); var contextGetVariableMethod; beforeEach(function () { global.context = { getVariable: function(s) {} }; contextGetVariableMethod = sinon.stub(context, 'getVariable'); }); afterEach(function () { contextGetVariableMethod.restore(); }); 

不完全确定这是为什么这样工作,但像这样构build代码似乎已经解决了这个问题