Внутренние вызовы заглушки на зависимость библиотеки с Sinon.js - PullRequest
1 голос
/ 26 июня 2019

Я пишу библиотеку, в которой есть файл ввода, который выглядит следующим образом:

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?

...