我正在编写一个库,其中包含一个如下所示的入口文件:
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
不是我可以直接在{{1}上存根的方法}。如何存根MyLibrary
?