Karma Coverage and Babel+Browserify Preprocessing

1.5k views Asked by At

I'm using Karma to test my ES6 code. When I add karma-coverage to the mix, I need to add all the source files for the coverage tool to make a useful report, but when I do that, Karma gives me this error in all browsers:

PhantomJS 1.9.8 (Mac OS X 0.0.0) ERROR

Error: Invariant Violation: _registerComponent(...): Target container is not a DOM element.

at /var/folders/55/9_128mq95kz1q_2_vwy7qllw0000gn/T/41cf272955d73fbba8ad1df941172139.browserify:46444:0 <- ../../node_modules/react/lib/invariant.js:49:0

My Karma config file is:

basePath: '',
browserNoActivityTimeout: 100000,
frameworks: ['phantomjs-shim', 'mocha', 'chai', 'browserify'],
files: [
  './client/**/*.js',
  './client/**/*.spec.js'
],
exclude: [
  './client/dist/*.js',
],
preprocessors: {
  './client/**/*.js': ['browserify', 'sourcemap', 'coverage']
},
browserify: {
  debug: true,
  transform: [
    ['babelify', {
        optional: ["runtime"],
        plugins: ["rewire"]
    }],
  ]
},
coverageReporter: {
  instrumenters: { isparta : require('isparta') },
  instrumenter: {
    '**/*.js': 'isparta'
  },
  type : 'html',
  dir : './coverage/'
},
reporters: ['mocha', 'coverage'],
port: 9876,
colors: true,
logLevel: config.LOG_INFO,
autoWatch: false,
browsers: ['Chrome', 'Firefox', 'Safari', 'PhantomJS'],
singleRun: true

If I remove './client/**/*.js', from the files array, the tests work, but then the coverage only show me the tests code. I use Karma from gulp with gulp-karma, but I suppose that this doesn't have anything to do with the problem.

2

There are 2 answers

0
fxlemire On

I had that same problem, which in my case occurred because React couldn't find the element in which it needed to render the html.

I found a quick fix by adding the following if statement into my main js file:

if ($('#container').length <= 0) {
  $('body').prepend('<div id="container"></div>');
}

ReactDom.render(
  <App />,
  document.getElementById('container')
);

I'm aware this must not be the best way of fixing it, but at least it works for now. If anyone knows of a better way, please let us know!

0
And1 On

Code you are covering is trying to render component into DOM node. Your code relys that it already exists (somewhere in index.html or whatever). But PhantomJS cannot find that DOM node. You should create it before calling ReactDOM.render or search how to change template of html page used by phantom to run tests (there are plugins doung this).