Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to test code that is using whatwg-fetch with mocha?

I'm using https://github.com/github/fetch in my app, which works fine but I would like to test my code with Mocha and babel since I'm writing ES2016.

This does not work out of the box. I'm getting:

1) testApi.js Test api error handling:
 ReferenceError: fetch is not defined
  at callApi (callApi.js:10:10)
  at Context.<anonymous> (testApi.js:8:40)

Because well, fetch is not defined. When I build for the browser fetch is exposed by webpack.

I've tried using https://github.com/bitinn/node-fetch but the api is slightly different and wants full url's instead of relative paths for example.

Is there a solution to this problem?

like image 564
Tieme Avatar asked Oct 30 '22 01:10

Tieme


1 Answers

So, if anyone has this problem in the future:

  • Use isomorphic-fetch
  • when using webpack make sure your target is set to 'web'
  • import 'isomorphic-fetch' in your index.js or otherwise root file
  • import 'isomorphic-fetch' in whatever test file calls fetch (or root test file if you have one)
  • your tests will now use node-fetch and your webpack will now build whatwg-fetch
like image 128
SparkyRobinson Avatar answered Nov 11 '22 04:11

SparkyRobinson