Nock - Get matched hostname

159 Views Asked by At

I want to mock an internal host naming scheme, like this.

nock(/some-internal.(ds1|ds2|ds3).hostname/)
  .get("/info")
  .reply(200, (???, requestBody) => {
    if(??? === "d1") {
      // return mock for d1
    } else if (??? === "d2") {
      // return mock for d2
    }
    // ... 
}) 

The first parameter of the callback is the path without the base url, so is this even possible?

1

There are 1 best solutions below

1
On BEST ANSWER

You can access the ClientRequest instance from inside the callback using the context. Docs for accessing the original request and headers.

const scope = nock(/some-internal.(ds1|ds2|ds3).hostname/)
  .get('/info')
  .reply(function (uri, requestBody) {
    console.log('host:', this.req.options.host)
    // ...
  })