Avoid making network requests in unit tests


function logEvent(event, payload) {
  fetch('', {
    method: 'POST',
    body: JSON.stringify({ event }),

function rollDice() {
  const result = Math.floor(Math.random() * 6) + 1;

  return result;



function rollDice(_logEvent = logEvent) {
  const result = Math.floor(Math.random() * 6) + 1;

  return result;


Check out for more ways to mock out functions in Jest.


Unit tests should not make network requests - even by some deeply nested function. The network should be mocked out, or replaced by a stub if you need to check calls to it.

Making network requests implies a server needs to be running, in order to successfully fulfill the request. This is usually the domain of End to End (E2E) tests, Integration Tests or Acceptance Tests.

Even if we don't care about the response from the server, we may have to deal with slow requests due to timeouts, the test process not shutting down gracefully because it's awaiting a network response etc.

Further reading