Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Getting ReferenceError: fetch is not defined when running react native tests in mocha

When running react-native tests in mocha, I'm getting the following error:

> 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.
like image 851
emmby Avatar asked Jul 20 '16 16:07

emmby


1 Answers

The problem was that fetch isn't available in a node environment like mocha. I'm not sure why react-native-mock (which I'm also using) doesn't have a mock for it, but the solution was to require isomorphic-fetch when initializing my mocha tests.

Specifically, add an init file to your mocha command-line if you don't have one already:

> mocha --require init.js …

and in init.js, require isomorphic-fetch:

require('isomorphic-fetch')

Then re-run 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
like image 93
emmby Avatar answered Oct 27 '22 11:10

emmby