How to get the query parameters in nock callback

Viewed 1857

I want to access the query parameter in nock reply callback.

The request object that is exposed contains the path that has them as a string. But I would like to access them as a map so that I will not have to deal with parsing the string

const scope = nock('http://www.google.com')
  .get('/cat-poems')
  .reply(function(uri, requestBody) {
    console.log('path:', this.req.path)
    console.log('headers:', this.req.headers)
    // ...
  })

I would expect the query params to be a separate map that I can access Does anyone know of a way to achieve this?

1 Answers

The value of this.req inside a reply function is an instance of a ClientRequest that has been slightly modified.

Unfortunately for your use case, ClientRequest does not provide an easy way to access just the query params. But you do have access to the full path, from which you can parse the query params out.

const nock = require('nock')
const http = require('http')
const url = require('url')

const scope = nock('http://www.google.com')
  .get('/cat-poems')
  .query(true)
  .reply(function(uri, requestBody) {
    const parsed = new url.URL(this.req.path, 'http://example.com')
    console.log('query params:', parsed.searchParams)
    return [200, 'OK']
  })

const req = http.get('http://www.google.com/cat-poems?page=12')

// output >> query params: URLSearchParams { 'page' => '12' }

The object being logged is a URLSearchParams instance.

Using the URL constructor is the preferred method over url.parse now, so I've used that for the example. Keep in mind that URL won't parse relative paths alone, it requires an origin, but since you don't care about the host in the end it can be a dummy value (hence the use of "example.com").

Related