Search code examples
webpackphantomjskarma-runnerbabeljswebpack-2

Getting failed tests (TypeError) only when running PhantomJS


tl;dr How to remove this error in PhantomJS?

Repo

Reference Repo: https://github.com/Sawtaytoes/Tabletop-Helper/tree/d123927b8f65fc97234fd2543bf9103ac0db58ab

Run yarn test.

Issue

When running these same tests from Chrome vs PhantomJS, I'm seeing errors show up related to the Webpack bundle, or so I thought.

Error

TypeError: undefined is not a constructor (evaluating '__WEBPACK_IMPORTED_MODULE_3_content_smash_up_decks__["a" /* sets */].find(function (set) { return title === set.title; })')

Code

sets
.find(set => title === set.title)
.decks
.reduce((combined, { title }) => ({ ...combined, [title]: setState }), {})

Confusion

The line in particular that's breaking is sets.find(). If I leave that out and make it sets[0], it works. In logging out the values of sets.find(), it always returned a matching array because the tests are written to pass in a valid set title.

The other two tests that have a similar error are also referencing sets.find(). What it is about this function that that PhantomJS doesn't like?


Solution

  • After narrowing this down, I was able to get it to show only

    TypeError: undefined is not a constructor (evaluating 'Array.prototype.find')
    

    PhantomJS 2.1 and older do not support Array.prototype.find. The solution is installing a PhantomJS plugin through npm and setting it up in the Karma config:

    ptim/phantomjs-polyfill-find
    

    Once installed, the Karma config needs to be modified. The first array parameter of the files property can be modified like so:

    files: [
        `node_modules/phantomjs-polyfill-find/find-polyfill.js`,
        ...
    ],
    

    NOTE: It has to reference node_modules/ in the path.