Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
85 views
in Technique[技术] by (71.8m points)

javascript - Karma, PhantomJS and es6 Promises

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.

How can I configure Karma to bring in the polyfill for promises?

question from:https://stackoverflow.com/questions/29391111/karma-phantomjs-and-es6-promises

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

You can pull in the Babel polyfill by simply installing Babel Polyfill:

npm install --save-dev babel-polyfill

and then include the polyfill file before your source and test files within the files section of your 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
],

Unless you know that all your target browsers support Promises, you probably want to apply this polyfill to your released build too.

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...