获取ReferenceError:在mocha中运行react native测试时未定义fetch

emm*_*mby 6 mocha.js fetch react-native

在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.
Run Code Online (Sandbox Code Playgroud)

emm*_*mby 14

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

具体来说,如果您还没有一个init文件,请将其添加到mocha命令行:

> mocha --require init.js …
Run Code Online (Sandbox Code Playgroud)

在init.js中,需要isomorphic-fetch:

require('isomorphic-fetch')
Run Code Online (Sandbox Code Playgroud)

然后重新运行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
Run Code Online (Sandbox Code Playgroud)

  • 或者`mocha --require isomorphic-fetch`.谢谢! (3认同)