sinonjs/sinon

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

Open

#2384 aperta il 16 giu 2021

Vedi su GitHub
 (18 commenti) (2 reazioni) (0 assegnatari)JavaScript (764 fork)batch import
BugDifficulty: MediumHelp wantedwontfix

Metriche repository

Star
 (9548 star)
Metriche merge PR
 (Merge medio 6g 16h) (15 PR mergiate in 30 g)

Descrizione

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

Guida contributor