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



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

代码沙箱(只需从终端运行纱线测试(: https://codesandbox.io/s/immutable-water-6pw3d

诺克匹配错误

matching https://test.com:443/%27health1%27 to GET https://test.com:443/'health2': false

无法访问代码沙箱时的示例代码:

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");
});
});

内部request模块使用 Node.js native url.parse 来解析 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");
});
});

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

在像这样设置 Nock 时,您需要自己对其进行编码:

nock("https://test.com")
.get(escape("/'health1'"))
.reply(200, { status: "up" })

最新更新