Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 537
dburgmann Avatar asked Aug 08 '16 13:08

dburgmann


2 Answers

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;
like image 130
mvdb Avatar answered Nov 11 '22 19:11

mvdb


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');
    });
  }
}
like image 2
Jason Turner Avatar answered Nov 11 '22 20:11

Jason Turner