sinonjs/sinon

sandbox.restore() does not work on static members of a function or class

Open

#2,384 opened on Jun 16, 2021

View on GitHub
 (18 comments) (2 reactions) (0 assignees)JavaScript (764 forks)batch import
BugDifficulty: MediumHelp wantedwontfix

Repository metrics

Stars
 (9,548 stars)
PR merge metrics
 (Avg merge 6d 16h) (15 merged PRs in 30d)

Description

Describe the bug The documentation says, that we can stub all methods of a object by using sinon.stub(obj) https://sinonjs.org/releases/latest/stubs/#var-stub--sinonstubobj

This works great for objects and also for classes.

It also works for sandbox.stub(obj)

What doesn't work, is to restore the methods of a class by using sandbox.restore()

To Reproduce

This block works:

const sinon = require('sinon');
const sandbox = sinon.createSandbox();

console.log('stub(obj)')
let i = 1;

const myTest = {
  test: (value) => {
    return value;
  }
}

console.log(myTest.test(i++));
sandbox.stub(myTest);
console.log(myTest.test(i++));
sandbox.restore();
console.log(myTest.test(i++));
sandbox.stub(myTest);
console.log(myTest.test(i++));
sandbox.restore();
console.log(myTest.test(i++));

The output is:

stub(obj)
1
undefined
3
undefined
5

This one doesn't:

const sinon = require('sinon');
const sandbox = sinon.createSandbox();

console.log('stub(class)')
let i = 1;

class MyTest {
  static test(value) {
    return value;
  }
}

console.log(MyTest.test(i++));
sandbox.stub(MyTest);
console.log(MyTest.test(i++));
sandbox.restore();
console.log(MyTest.test(i++));
sandbox.stub(MyTest);
console.log(MyTest.test(i++));
sandbox.restore();
console.log(MyTest.test(i++));

The output is:

stub(class)
1
undefined
undefined
./node_modules/sinon/lib/sinon/util/core/wrap-method.js:82
            throw error;
            ^

TypeError: Attempted to wrap test which is already wrapped
...

Expected behavior It would be great if sandbox.restore() would also restore all methods of a class and not only of a object.

Context (please complete the following information):

  • Library version: 11.1.1
  • Environment: Linux - node v14.16.0

Contributor guide