Search code examples
javascriptmocha.jssinon

TypeError: Attempted to wrap which is already wrapped


My codes:

  before(function _before() {
    this.myObject = new MyObject();
  });
  it('should', sinon.test(function() {
    const stubLog = sinon.stub(this.myObject.log, 'warn');
  }));
  it('should 2', sinon.test(function() {
    const stubLog = sinon.stub(this.myObject.log, 'warn');
  }));

sinon version: 1.17.6

Why I got the error TypeError: Attempted to wrap warn which is already wrapped in should 2 test? Should I restore stubLog manually? I think sinon.test() will do it for me. Maybe I did something wrong?

Any comments welcomed. Thanks


Solution

  • Have you tried using this.stub() instead of sinon.stub() inside the sandbox?

    const stubLog = this.stub(this.myObject.log, 'warn');
    

    From the official docs, an example:

    it('should do something', sinonTest(function(){
        var spy1 = this.spy(myFunc);
        var spy2 = this.spy(myOtherFunc);
        myFunc(1);
        myFunc(2);
        assert(spy1.calledWith(1));
        assert(spy1.calledWith(2));
    }));
    

    Once wrapped with sinon.test(), the function would access the this pointer inside itself and use it to stub/spy other functions.

    Using it like that should restore your stubs automatically for you.