Fail test if a network request is made (using Nock)

1.2k Views Asked by At

I have logic that conditionally makes a network request, how can I, using Nock, make a test that would fail if a network request is made? Basically asserting that 0 calls to an endpoint was made.

3

There are 3 best solutions below

0
On BEST ANSWER

I was able to solve this by listening to a "no match" event being emitted from nock.

nock.emitter.on('no match', (req: any) => {
  throw new Error(`Unexpected request was sent to ${req.path}`);
});
2
On

nock.disableNetConnect() will throw an error if a request is made that was not previously mocked.

Docs

0
On

So in your test there is now:

nock('foo').post('/bar').reply(200, ({ 'bar': 'foo' })

When you alter that in:

let times = 0
nock('foo').post('/bar').reply(200, ({ 'bar': 'foo' })
act(() => {
  scope.on('replied', () => {
    times += 1
  })
})

then inside your test you can now set the expectation:

await waitFor(() => expect(times).toBe(0), { timeout: 4000 })

and when you do expect it, that value will be 1