Unit testing JavaScript ES6 code with Karma

This posting is referenced to this post.

Unit Testing ES6 codes

To run unit tests against ES6 codes, we need a way to transpile the codes before the unit test runner(karma) processes them.

Here we use webpack to transpile ES6 codes with babel loader using babel es2015 preset.

But the original posting is outdated since babel is now split in serveral modules. We need few of them to get transpiling working.

The complete code is on a github repository.
Karma for es6 respository

Prerequisites

Install Node.js

The best way to install Node.js is with nvm.

cURL:

$ curl https://raw.github.com/creationix/nvm/master/install.sh | sh

Wget:

$ wget -qO- https://raw.github.com/creationix/nvm/master/install.sh | sh

Once nvm is installed, restart the terminal and run the following command to install Node.js.

$ nvm install 4

Alternatively, download and run the installer.

Create project directory

Create a directory.

1
$ mkdir karma-testing; cd karma-testing

Install related modules

Install node modules.

1
2
3
$ npm init --y
$ npm i -D karma karma-phantomjs-launcher phantomjs-prebuilt karma-jasmine jasmine-core babel-core babel-polyfill babel-loader babel-preset-es2015 webpack karma-webpack
$ npm i -g karma-cli

Add or change npm script attribute to package.json

1
2
3
"scripts": {
"tests": "karma start"
},

Generate karma config file

karma.conf.js

1
$ vi karma.conf.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
module.exports = function(config) {
config.set({
browsers: ['PhantomJS'],
files: [
{ pattern: 'test-context.js', watched: false }
],
frameworks: ['jasmine'],
preprocessors: {
'test-context.js': ['webpack']
},
webpack: {
module: {
loaders: [
{ test: /\.js$/, exclude: /node_modules/, loader: 'babel?presets[]=es2015' }

]
},
watch: true
},
webpackServer: {
noInfo: true
}
});
};

Provide context including testing files

test-context.js

1
$ vi test-context.js
1
2
3
4
require("babel-polyfill");

var context = require.context('./source', true, /-spec\.js$/);
context.keys().forEach(context);

source/calculator.js

1
$ vi source/calculator.js
1
2
3
4
5
6
7
8
export class Calculator{
add(op1,op2){
return op1 + op2;
}
subtract(op1,op2){
return op1 - op2;
}
}

source/calculator-spec.js

1
$ vi source/calculator-spec.js
1
2
3
4
5
6
7
8
9
10
11
12
13
import {Calculator} from './calculator';
describe('Calculator', () => {
it('should add two numbers', () => {
let calculator = new Calculator();
let sum = calculator.add(1,4);
expect(sum).toBe(5);
});
it('should subtract two numbers', () => {
let calculator = new Calculator();
let sum = calculator.subtract(4,1);
expect(sum).toBe(3);
});
});

Kicking off unit testing

1
$ npm run tests

Enjoy testing ES6 codes!

The complete code is on a github repository.
Karma for es6 respository

.

Share