Search code examples
jestjsnock

Unable to mock POST request with nock


I'm using the fetch API and nock to mock a post request. The test looks like so:

it('should handle the triple bracket replacements ', async () => {
  nock('https://jives.dev')
    .post('/', {
      bestCat: 'cat'
    })
    .reply(200, {
      data: '12345'
    })

  const data = await retrieveData({
    endpoint: 'https://jives.dev/',
    configuration: JSON.stringify({
      method: 'POST',
      body: {
        bestCat: 'cat'
      }
    }),
    auth: {cat: 'cat'}
  })

  expect(data).toEqual({data: '12345'})
})

The retrieveData function runs fetch, and simply maps the endpoint and configuration args into a request as following:

fetch('https://jives.dev/', {
  method: 'POST',
  body: {
    bestCat: 'cat'
  }
})

I end up getting an error as if nock is not mocking the request. I can get it to work for get requests but I'm unsure why this isn't working in this example. The error message looks like it's trying to actually make the post request instead of returning data from nock.

- Expected  - 3
+ Received  + 1

- Object {
-   "data": "12345",
- }
+ [Error]

Solution

  • This was caused by me not cleaning all of the mocks in the jest suite. The following resolved this.

    afterEach(nock.cleanAll)
    afterAll(nock.restore)