Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Nock - Get number of calls performed to fetch

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?

like image 846
Unapedra Avatar asked Oct 25 '25 14:10

Unapedra


1 Answers

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

like image 106
Thomas Champion Avatar answered Oct 27 '25 09:10

Thomas Champion