part of the difficulty of using something like webpack is that the source code that you edit is not the final code that is used in your project. so when it comes to unit testing your code, you have to figure out how to instrument what webpack is bundling.
suppose that you are using karma as your test runner with mocha, chai, and sinon. you can add istanbul to the mix to add code coverage, but you need istanbul to understand how webpack bundles files.
luckily, there’s istanbul-instrumenter-loader. you can add this as a loader which will add the instrumentation of the code in your project as part of the webpack process.
a sample karma.conf.js file:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 |
var Webpack = require('webpack'), path = require('path'); module.exports = function(config) { config.set({ frameworks: [ 'mocha', 'chai', 'sinon' ], files: [ 'tests/*_test.js', 'tests/**/*_test.js' ], autoWatch: true, browsers: [ 'PhantomJS' ], preprocessors: { 'tests/*_test.js': ['webpack'] }, reporters: [ 'progress', 'coverage' ], coverageReporter: { dir: 'build/reports/coverage', reporters: [ { type: 'html', subdir: 'report-html' }, { type: 'lcov', subdir: 'report-lcov' }, { type: 'cobertura', subdir: '.', file: 'cobertura.txt' } ] }, webpack: { module: { postLoaders: [ { test: /\.js$/, exclude: /(node_modules|resources\/js\/vendor)/, loader: 'istanbul-instrumenter' } ] } }, webpackMiddleware: { noInfo: true }, plugins: [ 'karma-webpack', 'karma-mocha', 'karma-chai', 'karma-sinon', 'karma-phantomjs-launcher', 'karma-coverage' ] }); }; |