Getting ReferenceError: fetch is not defined when running react native tests in mocha
Getting ReferenceError: fetch is not defined when running react native tests in mocha
当 运行 在 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(我也在使用)没有模拟,但解决方案是在初始化我的 mocha 测试时需要 isomorphic-fetch
。
具体来说,如果您还没有 init 文件,请将其添加到您的 mocha 命令行:
> mocha --require init.js …
并且在 init.js 中,需要同构获取:
require('isomorphic-fetch')
然后重新运行摩卡:
> 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
当 运行 在 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(我也在使用)没有模拟,但解决方案是在初始化我的 mocha 测试时需要 isomorphic-fetch
。
具体来说,如果您还没有 init 文件,请将其添加到您的 mocha 命令行:
> mocha --require init.js …
并且在 init.js 中,需要同构获取:
require('isomorphic-fetch')
然后重新运行摩卡:
> 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