Stubbing method in same file using Sinon

后端 未结 3 1588
爱一瞬间的悲伤
爱一瞬间的悲伤 2021-01-04 09:04

I\'m trying to unit test a function in a file while stubbing another function in the SAME file, but the mock is not being applied and the real method is being called. Here\

3条回答
  •  孤城傲影
    2021-01-04 09:51

    Some restructuring can make this work.

    I've used commonJS syntax. Should work in the same way in ES6 as well.

    foo.js

    const factory = {
      a,
      b,
    }
    function a() {
      return 2;
    }
    
    function b() {
      return factory.a();
    }
    
    module.exports = factory;
    

    test.js

    const ser = require('./foo');
    const sinon = require('sinon');
    
    const aStub = sinon.stub(ser, 'a').returns('mocked return');
    console.log(ser.b());
    console.log(aStub.callCount);
    

    Output

    mocked return

    1

提交回复
热议问题