2

I've got a React custom hook that tries to avoid repeated calls to a URL. This is done by storing in state the isLoading prop, which is set to true whenever the fetch method is called, and is set to false once it receives the response from the server.

To test it, I need to be able to count how many times 'fetch' has been called, but I cannot seem to find any option or property or method inside nock library that gets me that.

There is a isDone method to know if all mocks have been fulfilled. There is a pendingMocks to know how many mocks haven't been fulfilled. But I can't find a way to count how many times fetch has been called, without caring about anything else (just the URL match).

They may be 100 times or just 2, just want to check how many times fetch has been called, just like toHaveFetchedTimes in fetch-mock-jest. Is there any way to do so in nock?

Unapedra
  • 2,043
  • 4
  • 25
  • 42
  • Did you find a way ? – Thomas Champion Feb 17 '23 at 16:14
  • @ThomasChampion nope, actually had to switch back to `fetch-mock-jest` because of this. It's less intuitive and sometimes things are hard to configure, but it has some functionalities that I need and `nock` hasn't. – Unapedra Feb 19 '23 at 00:01

1 Answers1

2

I find a way that works even it's not very clean.

In fact reply can take a callback function in second parameter that is called for every request that matches criteria.

  let called = 0
  nock
    .post('/my/path')
    .reply(200, () => {
      called++
      return { foo: 'bar' }
    })

  expect(called).toBe(1)

See: https://github.com/nock/nock#specifying-replies

Thomas Champion
  • 328
  • 3
  • 7