When writing tests run by Karma for a application that's bundled with Webpack, it's easiest to integrate webpack and Karm A directly together. In this lesson we'll see if utilize the plugin and karma-webpack
reuse our existing webpack configuration to preprocess our TE St files with Webpack.
Karma.config.js:
Constwebpackenv = {test:true}ConstWebpackconfig = require ('./webpack.config') (webpackenv)ConstFileglob ='Src/js/**/*.test.js'Module.exports=function Setkarmaconfig (config) {config.Set({basepath:"', Frameworks: ['Mocha','Chai'], files: [Fileglob], preprocessors: {[Fileglob]: ['Webpack']}, Webpack:webpackconfig, Webpackmiddleware: {noinfo:true},//No Webpack outputReporters: ['Progress'], Port:9876, colors:true, Loglevel:config. Log_info, Autowatch:false, browsers: ['Chrome'], Singlerun:true, concurrency:infinity})}
Webpack.config.js:
Const{Resolve} = require ('Path') Module.exports= ENV = { return{entry:'./js/app.js', Output: {filename:'Bundle.js', Path:resolve (__dirname,'Dist'), PathInfo:!Env.prod,}, Context:resolve (__dirname,'src'), Devtool:env.prod?'Source-map':'Eval', Bail:env.prod, module: {loaders: [{test:/\.js$/, Loader:'Babel!eslint', Exclude:/node_modules/}, {test:/\.css$/, Loader:'Style!css'}, ], }, }}
Package.json:
{ "Private":true, "Dependencies": { "Todomvc-app-css":"2.0.4", "Todomvc-common":"1.0.2" }, "devdependencies": { "Babel":"6.5.2", "Babel-core":"6.8.0", "Babel-eslint":"6.0.4", "Babel-loader":"6.2.4", "Babel-preset-es2015-webpack":"6.4.1", "babel-preset-stage-2":"6.5.0", "Chai":"3.5.0", "cpy-cli":"1.0.0", "Css-loader":"0.23.1", "Eslint":"2.9.0", "Eslint-config-kentcdodds":"6.2.1", "Eslint-loader":"1.3.0", "Ghooks":"1.2.1", "Karma":"0.13.22", "Karma-chai":"0.1.0", "Karma-chrome-launcher":"1.0.1", "Karma-mocha":"1.0.1", "Karma-webpack":"1.7.0", "Mocha":"2.5.3", "Npm-run-all":"1.8.0", "opt-cli":"1.4.2", "Rimraf":"2.5.2", "Style-loader":"0.13.1", "Webpack":"2.1.0-beta.7", "Webpack-dev-server":"2.0.0-beta", "Webpack-validator":"2.1.0" }, "Config": { "Ghooks": { "Pre-commit":"opt--in pre-commit--exec \ "npm Run Validate\"" } }, "Scripts": { "Test":"Karma Start", "watch:test":"NPM test----Auto-watch--no-single-run", "Validate":"npm-run-all--parallel validate-webpack:* Lint", "Validate-webpack:dev":"webpack-validator webpack.config.js--env.dev", "Validate-webpack:prod":"webpack-validator webpack.config.js--env.prod", "clean-dist":"Rimraf Dist", "Copy-files":"cpy src/index.html Src/favicon.ico Dist", "clean-and-copy":"npm Run clean-dist && npm run Copy-files", "Prestart":"NPM Run Clean-and-copy", "Start":"webpack-dev-server--env.dev--content-base Dist", "Prebuild":"NPM Run Clean-and-copy", "Prebuild:prod":"NPM Run Clean-and-copy", "Build":"Webpack--env.dev", "Build:prod":"Webpack--env.prod-p", "Lint":"Eslint." }}
Test file:
from ' ./controller ' describe ('controller', () = { It ('exists ', () = { expect (Controller). To.exist })})
Github
[Webpack 2] Use Karma for Unit testing with Webpack