问题描述
我正在编写一个使用新es6承诺的JavaScript库。我可以在Firefox中测试库,因为已经定义了promises。但是,当我尝试使用Karma和PhantomJS测试我的代码时,我收到错误无法找到变量:Promise。
。我猜这是因为PhantomJS浏览器还不支持es6承诺。
I am writing a JavaScript library that uses the new es6 promises. I can test the library in Firefox because promises are defined. However, when I try to test my code with Karma and PhantomJS, I get the error Can't find variable: Promise.
. I am guessing this is because the PhantomJS browser doesn't support es6 promises yet.
我如何配置Karma为承诺引入polyfill?
How can I configure Karma to bring in the polyfill for promises?
推荐答案
只需安装:
npm install --save-dev babel-polyfill
然后在文件中的源文件和测试文件之前包含polyfill文件
你的部分karma.conf.js
:
files: [
'node_modules/babel-polyfill/dist/polyfill.js',
'index.js', //could be /src/**/*.js
'index.spec.js' //could be /test/**/*.spec.js
],
除非您知道所有目标浏览器都支持Promises,否则您可能也希望将此polyfill应用于已发布的版本。
Unless you know that all your target browsers support Promises, you probably want to apply this polyfill to your released build too.
如果您真的喜欢冒险,可以使用Browserify来提取文件以使您的测试更加模块化,然后使用Babelify将ES6转换为ES5。我创建了一个。
If you're feeling really adventurous you can use Browserify to pull files in to make your testing more modular, and then use Babelify to transpile ES6 to ES5. I've created a sample project with these and a working test involving a Promise (running on PhantomJS2) for reference.
这篇关于Karma,PhantomJS和es6 Promises的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!