Search code examples
javascriptnode.jsunit-testingintegration-testingnock

how to make nock.js reply posted data?


Given this function:

createTrip: function(trip, userId) {
  trip.userId = userId
  trip.id = uuid()
  return axios
    .post(`${url}/trips`, trip)
    .then(res => res.data)
    .catch(error => error)
}

And this test:

tripToCreate = {
    "name": "Iceland 2017",
    "start": "2017-04-07",
    "end": "2017-04-29",
    "parts": []
}

describe('#createTrip', function() {
  it('should post the trips to the REST API', async function() {
    nock(baseUrl)
     .post('/trips')
     .reply(201)

    data = await tripDao.createTrip(tripToCreate, 'u1')
    console.log(data)
    expect(data.id).to.match(/^[0-9a-f]{8}-[0-9a-f]{4}-4[0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/)
    expect(data.userId).to.equal(tripToCreate.userId)
    expect(data.name).to.equal(tripToCreate.name)
    expect(data.start).to.equal(tripToCreate.start)
    expect(data.end).to.equal(tripToCreate.end)
  })
})

I would like nock to reply with the posted data (therefore mocking the behavior of json-server). Since the data is posted by the createTrip() function after adding 2 fields, I can't simply return hardcoded data. Is it possible using nock (or another "mocking" tool)?

Bonus question: does it actually make sense to make this test? Or a true integration test with a dedicated json-server for integration tests would be better?

Thanks in advance for your help!


Solution

  • Yes, this is supported by nock. See this section of the documentation: https://github.com/nock/nock#specifying-replies

    The example given there does exactly what you're asking for:

    const scope = nock('http://www.google.com')
      .post('/echo')
      .reply(201, (uri, requestBody) => requestBody)
    

    Though as for what test makes sense to write, it's important to consider what behavior you're trying to test. nock makes the most sense for testing the client (without needing to set up a real server), whereas other mocking libraries like node-mocks-http are better suited for testing server endpoints (without needing to set up a real client).