XMLHttpRequest testing in Jest

The jest api has changed a bit. This is what I use. It doesn’t do anything but it’s enough to render my components.

const xhrMockClass = () => ({
  open            : jest.fn(),
  send            : jest.fn(),
  setRequestHeader: jest.fn()
})

window.XMLHttpRequest = jest.fn().mockImplementation(xhrMockClass)

and in the test file:

import '../../__mock__/xhr-mock.js'

Leave a Comment