react-native - 获取 ReferenceError : fetch is not defined when running react native tests in mocha

标签 react-native mocha.js fetch

在 mocha 中运行 react-native 测试时,出现以下错误:

> mocha --require test/init.js --compilers js:test/compiler.js 'src/**/*.spec.js'

Initializing tap mocha reporter...
1..7
ok 1 test1
…
not ok 7 test7
  ReferenceError: fetch is not defined
      at foo (src/foo.js:59:8)
      at Context.<anonymous> (src/__specs__/foo.spec.js:9:30)
# tests 7
# pass 6
# fail 1
npm ERR! Test failed.  See above for more details.

最佳答案

问题是 fetch 在像 mocha 这样的节点环境中不可用。我不确定为什么 react-native-mock(我也在使用)没有模拟它,但解决方案是需要 isomorphic-fetch初始化我的 Mocha 测试时。

具体来说,如果你还没有一个 init 文件到你的 mocha 命令行:

> mocha --require init.js …

在 init.js 中,需要 isomorphic-fetch:
require('isomorphic-fetch')

然后重新运行 mocha:
> mocha --require test/init.js --compilers js:test/compiler.js 'src/**/*.spec.js' && standard

Initializing tap mocha reporter...
1..7
ok 1 test1
…
ok 7 test7
# tests 7
# pass 7
# fail 0

关于react-native - 获取 ReferenceError : fetch is not defined when running react native tests in mocha,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38485826/

相关文章:

javascript - 使用 React Native 和 Mobx 创建主题全局类?

ios - Pod 安装在 React-native mac os catalina 10.15 中不起作用

javascript - 如何使用 mocha、chai 和 sinon 模拟和测试闭包

android - React Native获取在Android上提供TypeError

react-native - React Native codePush 重启后回滚

javascript - 当值为 true 时显示选取器项目 React Native

javascript - 使用 sinon spy restore 或 reset 的正确方法是什么?

express - 在 mocha 中的每个测试文件之前运行一组操作

javascript - 如果 URL 不正确,fetch API 不会在 catch 中显示确切的错误

javascript - Parse.com fetch collection 上限为 1000