oclif / fancy-test

extends mocha with helpful, chainable extensions

Home Page:https://npmjs.com/package/fancy-test

Geek Repo:Geek Repo

Github PK Tool:Github PK Tool

Pass `ctx` to nock callbacks

blake-mealey opened this issue · 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)

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.