Is it possible to reuse a nock object?

181 views Asked by At

I am using nock for testing HTTP Endpoints and I don't want to define the headers and baseURL multiple times. Is it problematic to do something like this?

const serviceNock = nock('https://my-service.local')
  .matchHeader('Api-Key', 'my-api-key')
  .matchHeader('Content-Type', 'application/json')

Use serviceNock in test1

const serviceNock1 = serviceNock
      .patch('/resources')
      .reply(200)

Use serviceNock in test2

const serviceNock2 = serviceNock
      .patch('/resources')
      .reply(500)

1

There are 1 answers

1
Vasiliy vvscode Vanchuk On BEST ANSWER

No idea about the nock (never used it and don't know if chaining creates new object or just modify the existing one), but why not to do something like next:

const getBaseNockService = () => nock('https://my-service.local')
  .matchHeader('Api-Key', 'my-api-key')
  .matchHeader('Content-Type', 'application/json')

const serviceNock1 = getBaseNockService()
      .patch('/resources')
      .reply(200)

const serviceNock2 = getBaseNockService()
      .patch('/resources')
      .reply(500)

Here we define factory function getBaseNockService and get full functionality you requested