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

Tie*_*eme 5 javascript testing mocha.js fetch

我使用https://github.com/github/fetch在我的应用程序,它工作正常,但我想测试我的代码以摩卡和巴贝尔,因为我在写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)
Run Code Online (Sandbox Code Playgroud)

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

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

有这个问题的解决方案吗?

小智 0

我能够使用三元模块进行 Mocha 测试node-fetch:

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

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