如何使用 nock.js 通过 GET 请求添加参数

Nav*_*ngh 6 javascript testing api node.js nock

我正在尝试使用 nock.js 来测试我的 API 路由是否可以模拟 url 请求。

我的路由文件根据以下逻辑路由:

app.get('/api/study/load/:id', abc.loadStudy );
Run Code Online (Sandbox Code Playgroud)

'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);} ); 
Run Code Online (Sandbox Code Playgroud)

我的方法使用了与请求一起发送的“params”键,我无法模拟。在下面的代码中打印'req'只会给出'/api/test/load/1'。如何在 GET 请求中添加“参数”

loadStudy = function(req, res) {
    console.log(req);
    var id = req.params.id;
};
Run Code Online (Sandbox Code Playgroud)

Sun*_*ary 8

根据官方文档,您可以通过以下方式指定查询字符串

var api = nock("http://localhost:3002")
      .get("/api/test/load/1")
      .query({params: {id : 1}})
      .reply(200, abc.loadStudy);
Run Code Online (Sandbox Code Playgroud)

希望能帮助到你。
如有任何疑问,请返回。


小智 5

我刚刚遇到了类似的问题,并尝试了 Sunil 的答案。事实证明,您所要做的就是提供一个您想要匹配的查询对象,而不是具有 params 属性的对象。我使用的是 nock 版本 11.7.2

const scope = nock(urls.baseURL)
     .get(routes.someRoute)
     .query({ hello: 'world' })
     .reply(200);
Run Code Online (Sandbox Code Playgroud)