mon*_*ist 10 unit-testing stubs sinon proxyquire
我想对以下简化模块进行单元测试:
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
};
Run Code Online (Sandbox Code Playgroud)
我正在logplease
使用Proxyquire替换外部依赖,这非常有效.但是我需要存根,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();
});
Run Code Online (Sandbox Code Playgroud)
输出我得到:
fake logger: called real one()
fake logger: called real two()
call count 2: 0
Run Code Online (Sandbox Code Playgroud)
输出我期望:
fake logger: called real one()
called fake stub of two()
call count 2: 1
Run Code Online (Sandbox Code Playgroud)
为什么我的存根函数不运行?
简短回答:
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;
Run Code Online (Sandbox Code Playgroud)
说明:范围
您将一和二导出为:
module.exports = {
one: tester.one,
two: tester.two
};
Run Code Online (Sandbox Code Playgroud)
在这种情况下tester.one只知道这个函数:
two: () => {
logger.log('called real two()');
}
Run Code Online (Sandbox Code Playgroud)
并且不知道存根两个。所以你有两个版本的Two,只需尝试在 test 中调用tester.two()。
归档时间: |
|
查看次数: |
394 次 |
最近记录: |