nock library - 如何匹配任何url

hen*_*ald 19 node.js

嗨,我正在尝试nock库,但我正在努力匹配查询字符串上的随机模式.我认为下面的代码应该可以工作,但我无法得到任何工作.

  var nock, request;

  request = require('request');

  nock = require('nock');

  nock("http://www.google.com").filteringPath(/.*/g).get("/").reply(200, "this should work?");

  request("http://www.google.com?value=bob", function(err, res, body) {
    return console.log(body);
  });
Run Code Online (Sandbox Code Playgroud)

tht*_*gma 20

我之前没有使用过这个,但是从阅读文档中可能会有所帮助.

这样的事情怎么样:

var nock = require('nock');
var request = require ('request');

nock("http://www.google.com")
    .filteringPath(function(path){
        return '/';
    })
    .get("/")
    .reply(200, "this should work?");

request("http://www.google.com?value=bob", function(err, res, body) {
    return console.log(body);
});
Run Code Online (Sandbox Code Playgroud)


mar*_*nes 5

只是为了完成thtsigma的答案:

如果要匹配任何范围(协议,域和端口),也可以添加范围过滤

var nock = require('nock');
var request = require ('request');

nock("http://www.whatever-here.com", {
    filteringScope: function(scope) {
      return true;
    }
  })
  .filteringPath(function(path){
      return "/";
  })
  .get("/")
  .reply(200, "this should work?");

request("http://www.google.com?value=bob", function(err, res, body) {
  return console.log(body);
});
Run Code Online (Sandbox Code Playgroud)

这样,任何网址都会被匹配。


Kev*_*Law 5

我们也可以使用正则表达式

nock("http://www.google.com")
   .get(/.*/)
Run Code Online (Sandbox Code Playgroud)