fancy-test icon indicating copy to clipboard operation
fancy-test copied to clipboard

Pass `ctx` to nock callbacks

Open blake-mealey opened this issue 6 years ago • 1 comments

It would be quite useful to have access to the context object when setting up nock responses:

fancy
  .add('resource', () => ({ ok: true }))
  .nock('https://example.com', (api, ctx) => api
    .get('/api/resource')
    .reply(ctx.resource)

blake-mealey avatar Jan 24 '20 17:01 blake-mealey

Another use case for this - asserting on request properties in the test body:

fancy
  .nock('https://example.com', (api, ctx) => api
    .get('/api/resource')
    .reply(function (uri, requestBody) {
      ctx.req = this.req;
      return {};
    })
  .it('should include auth in the header', ctx => {
    expect(ctx.req.headers).to.have.property('authorization').that.matches(/Bearer/i)
  })

I know that I could write the same assertion using the nock's reqheaders property:

fancy
  .nock('https://example.com',
    { reqheaders: { 'authorization': /Bearer/i } },
    api => api.get('/api/resource').reply(200, {})
  )
  .it('should include auth in the header')

But that makes the assertion implicit - when the test has more code before the .it() line it's not immediately obvious that the request headers are the main thing this test is designed to verify.

vlukashov avatar Feb 22 '22 09:02 vlukashov