Search code examples
react-nativexmlhttprequestjestjsbabel-jest

XMLHttpRequest is not defined when testing react-native app with jest


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.


Solution

  • 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');
        });
      }
    }