Search code examples
javascriptnode.jsrequest-promisenock

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

Solution

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