gpt4 book ai didi

unit-testing - 在 proxyquired 对象中 stub 函数

转载 作者:行者123 更新时间:2023-12-04 03:16:30 27 4
gpt4 key购买 nike

我想对以下简化模块进行单元测试:

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
};

我正在替换外部依赖 logplease使用 Proxyquire ,效果很好。但是我需要 stub 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

为什么我的 stub 函数不运行?

最佳答案

简短的回答:

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()');
}

并且不知道 stub 两个 .所以你有两个版本的 两个 ,只需尝试调用 tester.two() 内测。

关于unit-testing - 在 proxyquired 对象中 stub 函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42169052/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com