【问题标题】:Sinon TypeError: Attempted to wrap <method> which is already wrapped when running multiple scriptsSinon TypeError: Attempted to wrap <method> 在运行多个脚本时已经被包装
【发布时间】:2017-06-23 12:20:00
【问题描述】:

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

即我有一个目录,里面有几个测试脚本。当我自己运行一个脚本时,测试通过了。当我运行目录中的所有脚本时,苔丝因错误而失败:

测试将失败

TypeError: Attempted to wrap getVariable which is already wrapped

而其他测试失败:

TypeError: Cannot read property 'restore' of undefined

两个测试脚本都以相同的代码开头:

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

我猜 mocha 正在同时运行这两个测试?测试相互干扰。我很困惑为什么测试的范围不是独立的......也许它使用global

谢谢

【问题讨论】:

    标签: javascript node.js mocha.js sinon


    【解决方案1】:

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

    所以,在你的情况下:

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

    【讨论】:

      【解决方案2】:

      我想我已经设法解决了这个问题。对我有用的解决方案是重新声明在 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();
      });
      

      不完全确定为什么会这样,但像这样构造代码似乎已经解决了问题

      【讨论】:

        【解决方案3】:

        如果你正在调用相同的函数,请检查你是否有任何忘记恢复到其他文件中的对象

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 2019-09-06
          • 2019-09-22
          • 2012-02-08
          • 1970-01-01
          • 2016-07-04
          • 1970-01-01
          • 2023-03-20
          • 2010-09-07
          相关资源
          最近更新 更多