我有一组从utils.js文件导出的函数,并在其余api路由函数之一中使用,我试图通过模拟返回值来测试该函数,但我无法做到这一点
// utils.js
exports.callSeparate = function() {
return new Promise(function (resolve, reject) {
try {
return {x:10, y:10}
}
}
exports.callSeparate = function() {
return new Promise(function (resolve, reject) {
try {
return {x:11, y:12}
}
}
// index.js
const {callSeparate} = import("../utils.js")
router.post(firstfunction,secondfunction,thridfunction);
async function secondfunction(req, res, next) {
result = await callSeparate()
return result;
}
//test.js
let callAPistub = sinon.stub(utils,'callSeparate');
callAPistub.returns(
{x:13, y:14}
);
如果我导入了整个utils库,然后在其余的API中使用了该函数,我就可以模拟该函数。
// index.js
const utils = import("../utils.js")
router.post(firstfunction,secondfunction,thridfunction);
async function secondfunction(req, res, next) {
result = await utils.callSeparate()
return result;
}
当函数按第一个代码块中的说明编写时,该如何模拟该函数,这不是我的代码,我正在尝试对其进行测试,因此我的双手几乎没有束缚。我已经阅读了有关rewire和proxyquire的内容,但是它们非常混乱,我无法达到我想要的结果。
答案 0 :(得分:0)
首先,您的意义不大。 callAPistub.returns( returns {x:13, y:14} )
实际上不是一个函数,因此它不应返回任何内容。您只是在设置返回值,所以现在调用该函数时,它将返回{x:13,y:14}。
我使它起作用:
//test.js
const utils = require("./utils.js")
var sinon = require('sinon');
let callAPistub = sinon.stub(utils,'callSeparate1');
callAPistub.returns( {x:13, y:14} );
console.log(callAPistub())
终端:
node test.js
{ x: 13, y: 14 }
关于我将callAPistub.returns
更改为此的通知:
callAPistub.returns({x:13, y:14});