[英]Sinon Stub the whole class
我在A.js
文件中有以下 class ,
class A {
constructor(name) {
this.name = name;
}
getResult() {
return this.name;
}
}
module.exports = A
在另一個名為controller.js
的文件中,我正在使用這樣的文件,
const A = require('./A');
module.exports = {
doProcess: () => {
const a = new A('John');
console.log(a.getResult());
}
}
所以我的要求是,我想在為 controller.js 編寫單元測試時對controller.js
A 及其方法進行存根。 如何使用 sinon 實現這一目標?
就像是,
const getResultStub = sinon.stub();
getResultStub().returns('success');
如果是默認導出,我不相信你可以直接存根它。
如果您在 nodejs 環境中工作,您可以使用proxyquire ,或者執行以下操作:
// A.js
class A {
constructor(name) {
this.name = name;
}
getResult() {
return this.name;
}
}
module.exports = A
// controller.spec.js
const sinon = require('sinon')
class DummyA {
constructor(){}
getResult(){
return 'success'
}
}
require.cache[require.resolve('./A')] = DummyA
const controller = require('./controller.js')
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.