首页 > 解决方案 > 使用 Sinon.js 对库的依赖项进行 Stub 内部调用

问题描述

我正在编写一个库,它的入口文件如下所示:

function MyLibrary(options){

   this._options = {// defaults here};

   this.setupOptions(options);
   this._initInstance();
}

MyLibrary.prototype.randomMethod = function(){

}

MyLibrary.prototype._initInstance = function(){
   this._loadImage();
   this._internalInstance = new OtherThirdPartyDependency(this._options);
}

module.exports = MyLibrary;

在我的测试中,我想创建一个真实的实例MyLibrary,但我想创建一个OtherThirdPartyDependency.

到目前为止,这是我的测试文件。我怎样才能做到这一点?

describe('My Library Module', () => {

    let sandbox;
    let myLibInstance;

    beforeEach(() => {
        sandbox = sinon.createSandbox({});
        myLibInstance = new MyLibrary({option: 1, option: 2}); 
        // FAILS HERE because initializing MyLibrary make a call OtherThirdPartyDependency constructor. 
    });

    afterEach(() => {
        sandbox.restore();
    });

    it('should call setOptions and _loadImage on init', () => {

        expect(myLibInstance.setOptions).to.have.been.calledOnce;
        expect(myLibInstance._loadImage).to.have.been.calledOnce;
    })

});

sinon 中有一个方法createStubInstance,但我不确定如何在这里应用,因为OtherThirdPartyDependency它不是我可以直接存根的方法MyLibrary。我怎样才能存根OtherThirdPartyDependency

标签: javascriptunit-testingsinon

解决方案


推荐阅读