3

I have an error when testing with sinon.js (and mocha). The error occurs when I run the all test scripts via npm, but not when I run an individual script through the IDE. Running the test script individually works ok, and the test passes.

I.e. I have a directory with several test scripts in it. When I run one script on its own the tests pass. When I run all scripts in the directory the tess fail with the errors:

Test will fail with

TypeError: Attempted to wrap getVariable which is already wrapped

While the other tests fail with:

TypeError: Cannot read property 'restore' of undefined

Both test scripts start with the same code:

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

I guess that mocha is running both test simultaneously? And the tests are interfering with one another. I'm confused why the scope of the tests is not independent though... perhaps its the use of global?

thanks

robjwilkins
  • 5,462
  • 5
  • 43
  • 59

3 Answers3

4

According to the Sinon JS documentation, if you have var stub = sinon.stub(object, "method");
you have to restore with object.method.restore();

So, in your case:

afterEach(function () {
    context.getVariable.restore()
});
Srdjan Dejanovic
  • 118
  • 1
  • 11
1

I think I have managed to sole the problem. The solution which is working for me is to redeclare the objects being stubbed in the beforeEach method.

for example:

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

Not entirely sure why this works, but structuring the code like this seems to have resolved the problem

robjwilkins
  • 5,462
  • 5
  • 43
  • 59
1

Check whether you have any object which you forgot to restore in other file, if you are calling same function

pride
  • 85
  • 1
  • 11