我正在尝试使用 nock.js 模拟 url 请求来测试我的 API 路由是否正常工作。
我的路由文件按照以下逻辑路由:
app.get('/api/study/load/:id', abc.loadStudy );
“abc.js”中的“loadStudy”方法用于处理以下特定的 GET 请求。因此,来自浏览器的任何 GET 请求都有一个带有“id”参数的“params”键,用于替换 URL 中的“:id”。但是,当我尝试使用 nock.js 模拟此 GET 请求时,我无法在请求中传递此“id”参数。
var abc = require('G:\\project\\abc.js');
var nock = require('nock');
var api = nock("http://localhost:3002")
.get("/api/test/load/1")
.reply(200, abc.loadStudy);
request({ url : 'http://localhost:3002/api/study/load/1', method: 'GET', params: {id : 1}}, function(error, response, body) { console.log(body);} );
我的方法使用随请求一起发送的“params”键,我无法模拟。在下面的代码中打印 'req' 只会给出 '/api/test/load/1' 。如何将'params' 添加到 GET 请求?
loadStudy = function(req, res) {
console.log(req);
var id = req.params.id;
};
最佳答案
根据 official docs ,您可以通过
指定查询字符串var api = nock("http://localhost:3002")
.get("/api/test/load/1")
.query({params: {id : 1}})
.reply(200, abc.loadStudy);
希望对您有所帮助。
如有任何疑问,请回复。
关于javascript - 如何使用 nock.js 通过 GET 请求添加参数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49341450/