【问题标题】:Getting ReferenceError: fetch is not defined获取 ReferenceError:未定义提取
【发布时间】:2018-10-26 12:38:38
【问题描述】:

在我的 React Native 应用程序的 Saga 测试中(确实可以正常工作),我添加了以下测试,该测试调用了一个执行 POST http 调用 (doScan) 的函数。

describe('Scan the product and register the scanning action', () => {
  const it = sagaHelper(scanProductSaga(scanProductAction(item)));

  it('logscan via ASL', (result) => {
    expect(result).toEqual(cps(ASLogger.logScan, xxx));
    return logScanResult;
  });

  it('should register the product', (result) => {
    expect(result).toEqual(call(doScan, logScanResult));
  });
});

单独的文件:

const doScan = scanObj =>
  toJSON(fetch('https://xxxx.xxxxxx.com/logger/scans', {
    method: 'POST',
    headers: new Headers(CONTENT_TYPE_HEADERS),
    body: JSON.stringify(scanObj),
  }));

注意:fetch 函数来自 react-native 库中的“react-native-interfaces.js”。测试失败,错误是由以下异常引起的:

ReferenceError: fetch is not defined
      at doScan (/Users/andy/WebstormProjects/ASAP/api/index.js:81:11)....

什么会导致这样的问题?解决方案可能是什么?

【问题讨论】:

    标签: javascript reactjs jestjs redux-saga universal


    【解决方案1】:

    在某些情况下,在客户端和服务器的通用应用程序中,维护人员必须在其Node 项目中使用isomorphic-fetch 模块,因为Node 尚不包含Fetch API。更多信息请阅读this question and answer

    但是在这种特殊情况下,因此React Native有些不同,因为在移动设备领域,没有V8SpiderMonkeyNode。有JavaScriptCore。所以,对于这种新情况应该使用react-native-fetch

    有点不一样,用下面的代码安装:

    npm install react-native-fetch
    

    然后,像 JSX 组件一样使用它:

    import Fetch from 'react-native-fetch'
    ...
      <Fetch
          url="https://jsonplaceholder.typicode.com/posts/1"
          retries={3}
          timeout={3000}
          onResponse={async (res) => {
            const json = await res.json()
            console.log(json)
          }}
          onError={console.error}
      />
    

    它很新,但很可爱。

    【讨论】:

      【解决方案2】:

      react-native 默认有fetch,但是node.js 上的测试环境没有fetch

      您可以像下面的测试代码顶部一样导入fetch

      const fetch = require('node-fetch')
      

      文件react-native-interface.js只声明了fetch的类型。

      declare var fetch: any;
      

      【讨论】:

        猜你喜欢
        • 2018-07-04
        • 1970-01-01
        • 2021-08-07
        • 2020-01-25
        • 1970-01-01
        • 2020-06-21
        • 2023-03-05
        • 2016-06-20
        相关资源
        最近更新 更多