[removed] Mocking Constructor using Sinon

前端 未结 8 2107
迷失自我
迷失自我 2021-02-06 20:47

I am pulling my hair out trying to figure out how to mock a constructor using sinon. I have a function that will create multiple widgets by calling a constructor that accepts a

8条回答
  •  礼貌的吻别
    2021-02-06 21:38

    I needed a solution for this because my code was calling the new operator. I wanted to mock the object that the new call created.

    var MockExample = sinon.stub();
    MockExample.prototype.test = sinon.stub().returns("42");
    var example = new MockExample();
    console.log("example: " + example.test()); // outputs 42
    

    Then I used rewire to inject it into the code that I was testing

    rewiredModule = rewire('/path/to/module.js');
    rewiredModule.__set__("Example", example);
    

提交回复
热议问题