gpt4 book ai didi

node.js - Sinon 函数 stub : How to call "own" function inside module

转载 作者:太空宇宙 更新时间:2023-11-04 02:02:16 25 4
gpt4 key购买 nike

我正在为 node.js 代码编写一些单元测试,并使用 Sinon 来 stub 函数调用

var myFunction = sinon.stub(nodeModule, 'myFunction');
myFunction.returns('mock answer');

nodeModule 看起来像这样

module.exports = {
myFunction: myFunction,
anotherF: anotherF
}

function myFunction() {

}

function anotherF() {
myFunction();
}

模拟显然适用于像 nodeModule.myFunction() 这样的用例,但我想知道当使用 nodeModule.anotherF() 调用时如何模拟 anotherF() 内的 myFunction() 调用?

最佳答案

您可以稍微重构一下您的模块。像这样。

var service = {
myFunction: myFunction,
anotherFunction: anotherFunction
}

module.exports = service;

function myFunction(){};

function anotherFunction() {
service.myFunction(); //calls whatever there is right now
}

关于node.js - Sinon 函数 stub : How to call "own" function inside module,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45569111/

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