javascript - 使用 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
?
解决方案
推荐阅读
- vim - 为什么我可以在 vimrc 中组合 `Plug` 和 `set`,但不能 `nnoremap`?
- javascript - 正在寻找一种方法使 div 顶部的这个三角形像这张图片一样圆润?
- java - 在 JavaFX 中创建两个按钮表
- .net - 尽管配置了防火墙,但 Google Cloud Linux VM 不允许 HTTP 访问事件
- java - ServiceLoader 找不到从路径加载的服务
- python - 使用 Selenium chromedriver (Python) 上传文件时出错 - “选择的文件扩展名无效”
- r - R:来自 seq() 函数的“length.out”参数无法正常工作
- maven - 构建dss库最新版本
- visual-studio-code - VS Code 侧边栏前景色变暗(使用 FireFly Pro Midnight)
- firebase - firebase fetchSignInMethodsForEmail 返回什么?