我有一個 class modules/handler.js,它看起來像這樣:
const {getCompany} = require('./helper');
module.exports = class Handler {
constructor () {...}
async init(){
await getCompany(){
...
}
}
它getCompany從檔案中匯入函式modules/helper.js:
exports.getCompany = async () => {
// async calls
}
現在在集成測驗中,我想存根該getCompany方法,它應該只回傳一個模擬公司。但是,proxyquire 不會存根方法getCompany,而是呼叫真正的方法。考試:
const sinon = require('sinon');
const proxyquire = require("proxyquire");
const Handler = require('../modules/handler');
describe('...', () => {
const getCompanyStub = sinon.stub();
getCompanyStub.resolves({...});
const test = proxyquire('../modules/handler.js'), {
getCompany: getCompanyStub
});
it('...', async () => {
const handler = new Handler();
await handler.init(); // <- calls real method
...
});
});
我也試過了,沒有sinon.stubwhere proxyquire 回傳一個直接回傳一個物件的函式,但是,這也不起作用。
我會非常感謝每一個指標。謝謝。
uj5u.com熱心網友回復:
Handler您正在使用的類是require函式所必需的,而不是proxyquire.
handler.js:
const { getCompany } = require('./helper');
module.exports = class Handler {
async init() {
await getCompany();
}
};
helper.js:
exports.getCompany = async () => {
// async calls
};
handler.test.js:
const sinon = require('sinon');
const proxyquire = require('proxyquire');
describe('69759888', () => {
it('should pass', async () => {
const getCompanyStub = sinon.stub().resolves({});
const Handler = proxyquire('./handler', {
'./helper': {
getCompany: getCompanyStub,
},
});
const handler = new Handler();
await handler.init();
});
});
測驗結果:
69759888
? should pass (2478ms)
1 passing (2s)
------------|---------|----------|---------|---------|-------------------
File | % Stmts | % Branch | % Funcs | % Lines | Uncovered Line #s
------------|---------|----------|---------|---------|-------------------
All files | 100 | 100 | 100 | 100 |
handler.js | 100 | 100 | 100 | 100 |
helper.js | 100 | 100 | 100 | 100 |
------------|---------|----------|---------|---------|-------------------
轉載請註明出處,本文鏈接:https://www.uj5u.com/houduan/341618.html
