Search code examples
node.jsreactjswebpackkarma-runnernwb

Configure phantomjs to work with webpack and karma nwb


I am using nwb to configure a react app, I would use like to chai and enzyme to set up my testing environment. I have made the following changes to accomplish this, I created a tests.webpack.js file:

import chai from 'chai';
import chaiEnzyme from 'chai-enzyme';
import chaiAsPromised from 'chai-as-promised';
import sinonChai from 'sinon-chai';

chai.use(chaiEnzyme());
chai.use(chaiAsPromised);
chai.use(sinonChai);

const context = require.context('./src', true, /\.spec\.js/);
context.keys.forEach(context);

I also modified the karma config in nwb.config.js:

const karmaChaiPlugins = require('karma-chai-plugins');

module.exports = {
  type: 'react-component',
  npm: {
    esModules: true,
    umd: {
      global: 'ReactMg',
      externals: {
        react: 'React',
      },
    },
  },
  karma: {
    testContext: 'tests.webpack.js',
    plugins: [
      karmaChaiPlugins,
    ],
    frameworks: ['mocha', 'chai', 'chai-as-promised'],
  },
  webpack: {
    compat: {
      enzyme: true,
      sinon: true,
    },
  },
};

I get an error when running nwb test after defining index.spec.js in src:

PhantomJS 2.1.1 (Linux 0.0.0) ERROR
  TypeError: undefined is not a function (evaluating 'context.keys.forEach(context)')
  at tests.webpack.js:73
PhantomJS 2.1.1 (Linux 0.0.0): Executed 0 of 0 ERROR (0.375 secs / 0 secs)
Karma exit code was 1

Solution

  • To fix error TypeError: undefined is not a function

    You should change context.keys.forEach(context); on context.keys().forEach(context); because keys is function[1]

    [1] - https://developer.mozilla.org/en/docs/Web/JavaScript/Reference/Global_Objects/Object/keys