Testing with Karma: Initializing Karma

In notebook:
FrontEndMasters Webpack Deep Dive
Created at:
Webpack libraries React JavaScript

Q&A: Hot module replacement with Angular 1 apps?

The problem with Angular 1 is that the state lives everywhere, across several modules. So if you change one file, all the other files need to be replaced as well, so in the end, the whole app will refresh.

Testing with Webpack

He usually aims for 70% code coverage. 

FEM/02.0-init-karma branch


      "karma": "1.1.2",
    "karma-chrome-launcher": "1.0.1",
    // will give you the Mocha globals
    "karma-mocha": "1.1.1",
    // and also mocha
    "mocha": "3.0.1",

npm scripts

    // run the tests
    "test": "karma start",
    // watch mode
    // you also need to add --no-single-run
    "watch:test": "npm test -- --auto-watch --no-single-run",
    "validate": "npm-run-all --parallel lint build test",

About Karma

As opposed to Mocha or Jasmine, Karma makes it easy to run your tests in a browser. It has watch mode and can refresh one, or multiple browsers. You can use any desktop browser. 
So Karma's responsibility is to launch and run tests in the browser. 
Q&A: What about Eva
Eva a testing framework that runs on NodeJS not in the browser. Kent likes it a lot. If you need to access the DOM, you need a dom implementation like jsdom. He really likes the api. 
Eva promises performance, it will use all available cores. But he found that orchestrating all the threads has a lot of overhead, so finally not that fast. He's currently migrating to Mocha even though the API is great. 
Q&A: What about headless Chrome
A headless browser doesn't have a window or UI. The problem with headless Chrome is that it only supports ES3!
Not even ES5. Probably the 2.0 version has ES5 support. 

Test files organisation

The common way is to have a test/ directory that mirrors the source directory. This doesn't scale very well. 
So he puts his test files next to the source files. My note: I just saw Brian Holt do the same in the React workshop. And I can endorse this, based on my own experience.

Karma config

Won't explain too much in detail...
  // ****   karma.conf.js   ****

module.exports = config => {
    basePath: '',
    frameworks: ['mocha'],
    // the most important part
    // for the workshop
    files: [
    reporters: ['progress'],
    port: 9876,
    colors: true,
    logLevel: config.LOG_INFO,
    autoWatch: false,
    browsers: ['Chrome'],
    singleRun: true,
    concurrency: Infinity,
Running the test
  // ****   controller.test.js  ****
// (just a random test file)
// using the Mocha API

describe('test', () => {
  it('works', () => {
    // test stuff
  it('works again', () => {
    // other stuff

Add the assertion library

branch 02.1-add-assertions
  // add these libs
    "chai": "3.5.0",
    "karma-chai": "0.1.0",
So now you can do expectations
  describe('test', () => {
  it('works', () => {
    // note: expect
  it('works again', () => {