gpt4 book ai didi

javascript - 有没有办法模拟请求对象的属性

转载 作者:行者123 更新时间:2023-11-30 19:19:56 24 4
gpt4 key购买 nike

我有一个使用 swagger 定义的 Javascript REST api 端点。在我的 Controller 中,我正在记录来自传入请求的 IP 地址。

这运行得很好,但现在我正在尝试添加 Jest 测试以覆盖,每次运行测试时都会抛出错误

module.exports.execute = async function execute (req, res) {
try {
log.info("Start processing request from client IP="+req.connection.remoteAddress);
... do some stuff
log.info("Finished processing request from client IP="+req.connection.remoteAddress);
} catch(err) {
log.error("Error caught in Address controller =>" + err.message);
utils.writeJson(res, err.message, 500);
}
};

当我执行测试时,我在 Controller 中遇到错误 =>无法读取未定义的属性“remoteAddress”

当我注释掉调用 req.connection.remoteAddress 的行时,一切都很好,我得到了覆盖,但不是那 2 行。

我猜问题是 req.connection.remoteAddress 是一个属性而不是一个函数。

有没有一种方法可以模拟此调用的响应以返回像 1.1.1.1 这样的统计字符串?

感谢任何帮助

最佳答案

在思考@Will Alexander 的第一条评论中的问题后,我添加了这个(第二行),现在一切都很好。谢谢你会

let mockReq = _.set({},'swagger.params.entity.value', JSON.stringify({            fail: false}));
mockReq.connection = _.set({},'remoteAddress', '1.1.1.1');

关于javascript - 有没有办法模拟请求对象的属性,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57581995/

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