1 year ago

#77067

test-img

karlosos

XMLHttpRequest mock - Jest mockImplementation doesn't create class with specified methods

I am trying to mock XMLHttpRequest but without success. Based on answers here I've managed to do following:

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

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

test("App works", async () => {
  const httpRequest = new XMLHttpRequest();
  httpRequest.open('GET', 'www.google.com');
});

However my httpRequest object doesn't have open, send or setRequestHeader methods. Why the mocked implementation doesn't work as intended?

Tests fails with following error:

TypeError: httpRequest.open is not a function

jestjs

react-testing-library

0 Answers

Your Answer

Accepted video resources