【发布时间】:2022-01-26 21:38:15
【问题描述】:
这是我遇到的更复杂的场景之一。我有一个需要测试的函数,这个函数嵌套在一个复杂的函数拼图中。我需要存根这个函数,并在 variable 里面设置一个值。
由于我不允许在这里分享的原因,publishEvent() 方法中的变量在测试运行期间未定义,我需要在测试期间设置此变量的值以便我测试 if 块函数中的代码。
我总结了整个文件,因为由于保密协议,我无法在此处分享代码,如果问题不够详细,请见谅。也许使用 sinon 我可以直接在publishEvent 函数中设置这个变量的值。
function emitEvent() {
async function publishEvent() {
const variable = library.fetchData()
if (variable) {
// do something
}
}
return Promise.resolve(publishEvent())
.then(() => { })
.catch(() => null);
}
function requestSuscription() {
return getAllSubscriptions()
.then((results) => {
return Promise.map(results, () => emitEvent())
})
}
function getAllSubscriptions() {
return new Promise()
}
function requestOtherSubscription() {
console.log('other thing requested')
}
module.exports = { requestSuscription, requestOtherSubscription }
我知道我可以存根 requestSuscription、requestOtherSubscription 函数并且它可以工作,但我如何存根 publishEvent 并设置变量值?
【问题讨论】:
标签: node.js testing sinon stub sinon-chai