Jim Moody
Jim Moody

Reputation: 808

How can I test a route with nock and request-promise when the url contains single quotes?

I am trying to test an API call using nock + request-promise and I am getting an error because the routes don't match. The issue appears to be that the API's url contains single quotes, and request-promise is url encoding the quotes but Nock isn't.

Codesandbox (just run yarn test from the terminal): https://codesandbox.io/s/immutable-water-6pw3d

Nock Matching Error

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

Sample code if you are not able to access the 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");
  });
});

Upvotes: 0

Views: 950

Answers (2)

antonku
antonku

Reputation: 7675

Internally request module uses Node.js native url.parse to parse url strings, see the source code.

So you can use the same module in the test:

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

Upvotes: 1

Matt R. Wilson
Matt R. Wilson

Reputation: 7575

You are correct about Request URL encoding the path while Nock is not.

You'll need to encode it yourself when setting up Nock like this:

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

Upvotes: 0

Related Questions