简体   繁体   English

如何使用mocha测试使用whatwg-fetch的代码?

[英]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. 我在我的应用程序中使用https://github.com/github/fetch ,它工作正常,但我想用Mocha和babel测试我的代码,因为我正在编写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. 因为没有定义fetch。 When I build for the browser fetch is exposed by webpack. 当我为浏览器构建时,webpack会公开fetch。

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. 我尝试过使用https://github.com/bitinn/node-fetch,但是api略有不同,例如需要完整的url而不是相对路径。

Is there a solution to this problem? 有这个问题的解决方案吗?

So, if anyone has this problem in the future: 所以,如果将来有人遇到这个问题:

  • Use isomorphic-fetch 使用isomorphic-fetch
  • when using webpack make sure your target is set to 'web' 使用webpack时,请确保将目标设置为“web”
  • import 'isomorphic-fetch' in your index.js or otherwise root file 在index.js或其他根文件中import 'isomorphic-fetch'
  • import 'isomorphic-fetch' in whatever test file calls fetch (or root test file if you have one) 在任何测试文件调用fetch中import 'isomorphic-fetch' (如果你有一个测试文件,则输入root测试文件)
  • your tests will now use node-fetch and your webpack will now build whatwg-fetch 你的测试现在将使用node-fetch,你的webpack现在将构建whatwg-fetch

I was able to get Mocha tests working with a ternary using node-fetch module: 我能够使用node-fetch模块让Mocha测试使用三元组:

// Support server-side fetch for tests.
let fetch = (typeof window === 'undefined')
  ? require('node-fetch')
  : window.fetch
;

https://github.com/bitinn/node-fetch https://github.com/bitinn/node-fetch

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM