[removed] Mocking Constructor using Sinon

前端 未结 8 2090
迷失自我
迷失自我 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:18

    Using Sinon 4.4.2, I was able to mock an instance method like this:

    const testObj = { /* any object */ }
    sinon.stub(MyClass.prototype, "myMethod").resolves(testObj)
    let myVar = await new MyClass(token).myMethod(arg1, arg2)
    // myVar === testObj
    

    A similar solution provided here: Stubbing a class method with Sinon.js

    0 讨论(0)
  • 2021-02-06 21:21

    I was able to get StubModule to work after a few tweaks, most notably passing in async:false as part of the config when requiring in the stubbed module.

    Kudos to Mr. Davis for putting that together

    0 讨论(0)
  • 2021-02-06 21:23

    I ran into this error by mistakenly typing sinon.stub.throws(expectedErr) rather than sinon.stub().throws(expectedErr). I've made similar mistakes before and not encountered this particular message before, so it threw me.

    0 讨论(0)
  • 2021-02-06 21:27

    Use sinon.createStubInstance(MyES6ClassName), then when MyES6ClassName is called with a new keyword, a stub of MyES6ClassName instance will returned.

    0 讨论(0)
  • 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);
    
    0 讨论(0)
  • 2021-02-06 21:42

    Just found this in the documentation.

    If you want to create a stub object of MyConstructor, but don’t want the constructor to be invoked, use this utility function.

    var stub = sinon.createStubInstance(MyConstructor)

    0 讨论(0)
提交回复
热议问题