Javascript 当url包含单引号时,如何使用nock和请求承诺测试路由?

Javascript 当url包含单引号时,如何使用nock和请求承诺测试路由?,javascript,node.js,request-promise,nock,Javascript,Node.js,Request Promise,Nock,我正在尝试使用nock+请求承诺测试API调用,但由于路由不匹配,我遇到了一个错误。问题似乎是API的url包含单引号,请求承诺是url编码引号,而Nock不是 Codesandbox刚从终端运行纱线测试: Nock匹配错误 匹配https://test.com:443/%27health1%27 得到https://test.com:443/“health2”:错误 如果无法访问codesandbox,则示例代码: const nock = require("nock"); const rp

我正在尝试使用nock+请求承诺测试API调用,但由于路由不匹配,我遇到了一个错误。问题似乎是API的url包含单引号,请求承诺是url编码引号,而Nock不是

Codesandbox刚从终端运行纱线测试:

Nock匹配错误

匹配https://test.com:443/%27health1%27 得到https://test.com:443/“health2”:错误

如果无法访问codesandbox,则示例代码:

const nock = require("nock");
const rp = require("request-promise");

describe("#getHealth", () => {
  it("should return the health", async () => {
    const getHealth = async () => {
      const response = await rp.get(`https://test.com/'health1'`);
      return JSON.parse(response);
    };

    nock("https://test.com")
      .get(`/'health2'`)
      .reply(200, { status: "up" })
      .log(console.log);

    const health = await getHealth();

    expect(health.status).equal("up");
  });
});

关于请求URL编码路径,您是正确的,而Nock不是

设置Nock时,您需要自己对其进行编码,如下所示:

nock("https://test.com")
  .get(escape("/'health1'"))
  .reply(200, { status: "up" })
内部请求模块使用Node.js native解析url字符串,请参阅

因此,您可以在测试中使用相同的模块:

const nock = require("nock");
const rp = require("request-promise");
const url = require("url");


describe("#getHealth", () => {
  it("should return the health", async () => {
    const getHealth = async () => {
      const response = await rp.get(`https://example.com/'health1'`);
      return JSON.parse(response);
    };

    const { pathname } = url.parse("https://example.com/'health1'");
    nock("https://example.com")
      .get(pathname)
      .reply(200, { status: "up" })
      .log(console.log);

    const health = await getHealth();
    expect(health.status).equal("up");
  });
});