Search code examples
nock

Nock - Get matched hostname


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?


Solution

  • 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)
        // ...
      })