Enzyme: Cannot pull in Enzyme adapter when running tests using Webpack, PhantomJS, and Karma

Created on 28 Sep 2017  路  4Comments  路  Source: enzymejs/enzyme

When running Karma using PhantomJS with a Webpack config file and Enzyme 3, PhantomJS will report the error:

PhantomJS 2.1.1 (Windows 8 0.0.0) ERROR
  ReferenceError: Can't find variable: Set
  at webpack:///node_modules/react-dom/cjs/react-dom.development.js:7393:0 <- src/karma.js:62639

Take this section for instance:

const testFiles = require.context('./', true, /^\.\/.*\.test\.js$/)

testFiles
.keys()
.forEach(testFiles)

When running that Webpack entry-point from Karma using PhantomJS, it dynamically loads in all **/*.test.js files from the current directly and runs each one. This worked in Enzyme 2.

With Enzyme 3 I need to import or require the React 16 adapter and as soon as I do, PhantomJS will error.

This line in particular is the culprit:

import Adapter from 'enzyme-adapter-react-16'

Checking the line in question, it comes from new Set() which PhantomJS isn't compatible in the current release version. Webpack usually handles this using Babel, but when it's in a 3rd party library, that's not the case.

Without having to babel all my node_modules, what's the solution?

Most helpful comment

Yes, I ran into this too and Sawtaytoes fix works well, so...
npm install babel-polyfill --save-dev

This gave me "babel-polyfill": "6.26.0", and then in your karma.conf.js file:
files: [ 'node_modules/babel-polyfill/dist/polyfill.js', 'tests.webpack.js' ],

tests.webpack.js being karma-webpack's single test file bundle method for running tests found here (https://github.com/webpack-contrib/karma-webpack).

All 4 comments

Include airbnb-browser-shims in phantomjs before running all your tests.

This is erroring before any tests get run.

On the other hand, I just found this which points at Set and Map needing to be polyfilled via core-js or babel-polyfill:
https://gist.github.com/gaearon/9a4d54653ae9c50af6c54b4e0e56b583

In my Karma config, I was able to add babel-polyfill and correct the issue:

    files: [
        'node_modules/babel-polyfill/dist/polyfill.js',
    ]

Yes, I ran into this too and Sawtaytoes fix works well, so...
npm install babel-polyfill --save-dev

This gave me "babel-polyfill": "6.26.0", and then in your karma.conf.js file:
files: [ 'node_modules/babel-polyfill/dist/polyfill.js', 'tests.webpack.js' ],

tests.webpack.js being karma-webpack's single test file bundle method for running tests found here (https://github.com/webpack-contrib/karma-webpack).

Was this page helpful?
0 / 5 - 0 ratings