1. Prerequisites

Ensure that Node is installed and run the following from the directory of the Javascript project:

Install PhantomJS

PhantomJS is a headless browser for the tests to interact with.

$ npm install -g phantomjs

Install Karma and RequireJS

$ npm install karma requirejs --save-dev

2. Setup the Config file

In the Javascript directory that you’ve installed Karma (should have an autogenerated ‘node_modules’ directory in it), run:

./node_modules/karma/bin/karma init

..and when prompted, select:

  • Testing Framework: Jasmine
  • Require.js: yes
  • Browser: PhantomJS
  • Pattern of source files *:
    • <directory-you-store-js-app-files>/**/*.js (eg app/**/*.js)
    • <directory-you-store-js-lib-files>/**/*.js (eg libs/**/*.js)
    • <your-test-requirejs-main-file>.js (eg test-main.js)
  • Patterns to exclude:
    • <your-requirejs-main-file>.js (eg app/main.js)

..then skip through the rest

* this is how Karma finds the JS files to load for testing

This will then have generated a configuration file called ‘karma.conf.js’ with the necessary settings to run Karma - if anything you selected was wrong, you can always edit this file to correct it.

3. Create test-main.js

Create a ‘test-main.js’ (or whatever you named this file) with the following:

// This creates an array of all the files that Karma finds with a suffix of
// Test.js (eg utilsTest.js) to be added to the Require JS config below
var tests = [],
for (file in window.__karma__.files) {
if (window.__karma__.files.hasOwnProperty(file)) {
if(/Test\.js$/.test(file)) {
baseUrl: '/base' // Karma serves files from /base/<your-base-path>
paths: {
//.. the paths you have set in your Require Js main.js file
// eg jquery: "libs/jquery.min"
deps: tests // add tests array to load our tests

callback: window.__karma__.start // start tests once Require.js is done

4. Write Unit Tests

Write your Unit tests according to the pattern that you set Karma to search for the files in karma.config.js and the pattern to load test files you set at the top of test-main.js.

I write a test file for each JS file by using the original JS filename with a suffix of ‘Test.js’ and store them in a ‘tests’ directory, for example:

- app/
- utils.js
- tests/
- utilsTest.js

Within these test files you can require the modules that you wish to test and use the Testing Framework that you selected to make assertions. The default for Karma is Jasmine - you can learn the syntax for this at: pivotal.github.io/jasmine/

5. Run Karma

Run the following to start Karma:

$ ./node_modules/karma/bin/karma start

If you left autoWatch: true, in the ‘karma.conf.js’ file, Karma with continue to listen for changes to your files and return the outcomes as soon as you save a file, otherwise you will have to either manually run karma start for every change you make or use a task runner like Grunt to watch for changes.