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

时间:2016-06-28 16:23:27

标签: javascript testing mocha fetch

我在我的应用程序中使用https://github.com/github/fetch,它工作正常,但我想用Mocha和babel测试我的代码,因为我正在编写ES2016。

这不是开箱即用的。我得到了:

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)

因为没有定义fetch。当我为浏览器构建时,webpack会公开fetch。

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

这个问题有解决方法吗?

2 个答案:

答案 0 :(得分:2)

所以,如果将来有人遇到这个问题:

  • 使用isomorphic-fetch
  • 使用网络包时,请确保您的目标设置为“网络”
  • index.js中的
  • import 'isomorphic-fetch'或其他根文件
  • import 'isomorphic-fetch'在任何测试文件中调用fetch(或根测试文件,如果有的话)
  • 您的测试现在将使用node-fetch,您的webpack现在将构建whatwg-fetch

答案 1 :(得分:0)

我能够使用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