我正在编写一个使用新的 es6 promise 的 JavaScript 库。我可以在 Firefox 中测试该库,因为已定义 promise 。但是,当我尝试使用 Karma 和 PhantomJS 测试我的代码时,出现错误 Can't find variable: Promise.
。我猜这是因为 PhantomJS 浏览器还不支持 es6 promises。
我如何配置 Karma 以引入 promise 的 polyfill?
最佳答案
您只需安装 Babel Polyfill 即可引入 Babel polyfill :
npm install --save-dev babel-polyfill
然后在 karma.conf.js
的 files
部分中的源文件和测试文件之前包含 polyfill 文件:
files: [
'node_modules/babel-polyfill/dist/polyfill.js',
'index.js', //could be /src/**/*.js
'index.spec.js' //could be /test/**/*.spec.js
],
除非您知道所有目标浏览器都支持 Promises,否则您可能也想将此 polyfill 应用到您发布的构建中。
如果您真的很喜欢冒险,可以使用 Browserify 拉入文件以使您的测试更加模块化,然后使用 Babelify 将 ES6 转换为 ES5。我创建了一个 sample project with these and a working test involving a Promise (running on PhantomJS2) for reference .
关于javascript - Karma、PhantomJS 和 es6 Promises,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29391111/