9
votes

i am trying to test a apiwrapper in a react-native based app using jest (integration testing). When i run it in the iOs simulator everything runs fine however it wont run my jest tests correctly - i always get:

ReferenceError: XMLHttpRequest is not defined

when i try to run tests using my api wrapper, eg.:

it('Login successful with correct data', () => {
  let api = Api.getInstance();
  return api.login("test", "testpass")
         .then(result => expect(result).toEqual('login_successful'));
});

the api class i am trying to test here does use the fetch api (not vanilla xhr). I assume its something related to jest trying to mock something but have not found a way to make it work yet.

Thanks in advance.

2
Possible duplicate of XHR testing in Jestthe_bluescreen
I am using fetch not XHR so the solution provided does not really solve the problem. Although i actually want to do integration testing. Correctly mocking the fetch api would also be acceptable... however i've found no way to correctly specify what the mock should return for which inputs for fetch...dburgmann

2 Answers

3
votes

In my case, I'm not testing the search code but only importing it somewhere in my code path, so I decided to just mock it at the global level in a setup.js file (loaded using --require at test run). The following works for me:

// needed in react-instantsearch
class XMLHttpRequest {}
global.XMLHttpRequest = XMLHttpRequest;
2
votes

I had a similar problem with lokka using XMLHttpRequest. I made a mock for lokka, which my api wrapper class depends on. You could try mocking your api wrapper.

This is what my lokka mock looks like for now. I'll add more to it when I start testing error handling.

export default class {
  query() {
    return new Promise(resolve => {
      resolve(200);
    });
  }
}

You might be able to mock your api wrapper with something similar:

export default class Api {      
  getInstance() {
    \\ However you implemented getInstance      
  }

  login(user, password) {
    return new Promise(resolve => {
      resolve('login_successful');
    });
  }
}