我想对以下简化模块进行单元测试:
const Logger = require('logplease');
const logger = Logger.create('utils');
const tester = {
one: () => {
logger.log('called real one()');
tester.two();
},
two: () => {
logger.log('called real two()');
},
};
module.exports = {
one: tester.one,
two: tester.two
};
我正在使用Proxyquire替换外部依赖项logplease
,这非常有效。但是我需要存根two()
,因为我希望对one()
进行单元测试,同时消除在实际代码中运行时产生的副作用two()
。
it.only('stubbing functions on the "proxyquired" object under test', function(done) {
const loggerStub = {
create: () => {
return { log: (msg) => { console.log('fake logger: ', msg); } };
}
};
let tester = proxyquire('../tester', { 'logplease': loggerStub });
let stub2 = sinon.stub(
tester,
'two',
() => {
console.log('called fake stub of two()');
}
);
tester.one();
console.log('call count 2: ', stub2.callCount);
done();
});
输出我得到:
fake logger: called real one()
fake logger: called real two()
call count 2: 0
我希望输出:
fake logger: called real one()
called fake stub of two()
call count 2: 1
为什么我的存根功能没有运行?
答案 0 :(得分:1)
简短回答:
const Logger = require('logplease');
const logger = Logger.create('utils');
const tester = {
one: () => {
logger.log('called real one()');
tester.two();
},
two: () => {
logger.log('called real two()');
},
};
module.exports = tester;
说明:范围
您将一个和两个导出为:
module.exports = {
one: tester.one,
two: tester.two
};
在这种情况下, tester.one 只知道此功能:
two: () => {
logger.log('called real two()');
}
并且不知道存根两个。所以你有两个版本的两个,只是尝试在测试中调用 tester.two()。