Karma Coverage and Babel+Browserify Preprocessing

假装没事ソ 提交于 2019-12-12 12:08:51

问题


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.


回答1:


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!




回答2:


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).



来源:https://stackoverflow.com/questions/30751385/karma-coverage-and-babelbrowserify-preprocessing

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!