【问题标题】:XMLHttpRequest is not defined when testing react-native app with jest用 jest 测试 react-native 应用程序时未定义 XMLHttpRequest
【发布时间】:2016-12-14 07:30:06
【问题描述】:

我正在尝试使用 jest(集成测试)在基于 react-native 的应用程序中测试 apiwrapper。 当我在 iOs 模拟器中运行它时,一切都运行良好,但是它无法正确运行我的笑话测试 - 我总是得到:

ReferenceError: XMLHttpRequest is not defined

当我尝试使用我的 api 包装器运行测试时,例如:

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

我在这里尝试测试的 api 类确实使用了 fetch api(不是 vanilla xhr)。我认为它与试图模拟某些东西的玩笑有关,但还没有找到使它起作用的方法。

提前致谢。

【问题讨论】:

  • XHR testing in Jest的可能重复
  • 我使用的是 fetch 而不是 XHR,所以提供的解决方案并不能真正解决问题。虽然我实际上想做集成测试。正确地模拟 fetch api 也是可以接受的......但是我发现没有办法正确指定模拟应该为哪些输入返回 fetch...

标签: react-native xmlhttprequest jestjs babel-jest


【解决方案1】:

在我的例子中,我没有测试搜索代码,而只是将它导入到我的代码路径中的某个位置,所以我决定在 setup.js 文件中的全局级别模拟它(在测试时使用 --require 加载跑步)。以下对我有用:

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

【讨论】:

    【解决方案2】:

    我在使用XMLHttpRequest 时遇到了与lokka 类似的问题。我为lokka 做了一个模拟,我的 api 包装类依赖于它。您可以尝试模拟您的 api 包装器。

    这就是我的lokka 模拟现在的样子。当我开始测试错误处理时,我会添加更多内容。

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

    你也许可以用类似的东西来模拟你的 api 包装器:

    export default class Api {      
      getInstance() {
        \\ However you implemented getInstance      
      }
    
      login(user, password) {
        return new Promise(resolve => {
          resolve('login_successful');
        });
      }
    }
    

    【讨论】:

      猜你喜欢
      • 2021-04-24
      • 2016-09-14
      • 2019-01-16
      • 2017-07-05
      • 1970-01-01
      • 2016-07-22
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多