nock/nock

Add statusMessage to response

Open

#1,979 opened on 2020年4月22日

GitHub で見る
 (12 comments) (5 reactions) (0 assignees)JavaScript (12,294 stars) (787 forks)batch import
good first issue

説明

Context

This isn't really a feature request, as what I need is possible with nock as-is. But I spent several hours searching, reading old issues and searching through the source code to find the solution, so I thought this might help others.

I am testing code that accesses a service that sets the statusMessage of the response, as well as the statusCode. I am using nock to mock the server/service in tests of the client code. Because the service does and the client responds to it, I want to set the statusMessage of the responses provided by nock, as well as the statusCode.

Alternatives

It is possible to set the statusMessage of the response with nock 12.0.3 (and possibly older, but I have only done it with 12.0.3), without any change required. To set the statusMessage of the response, one can use a callback to provide the body of the reply and set the statusMessage via this.req.response. For example:

const scope = nock('http://www.google.com')
  .post('/echo')
  .reply(200, function (uri, requestBody) {
    this.req.response.statusMessage = 'This is the custom status message'
    return {
      status: 200,
      message: 'This is the reply body',
      ...
    }
  })

I have only tried this one form of callback, but I expect the other forms would work as well. As noted in the docs, a function, rather than an arrow function, is necessary to get the correct 'this'.

Has the feature been requested before?

This has been discussed before in #469, #558 and #587 but these are all closed now.

If the feature request is accepted, would you be willing to submit a PR?

No need, as noted above.

Thanks all for a very nice tool!

コントリビューターガイド