Just how blazingly easy it is to use the Karma test-runner

My big talk/soapbox for the year is testing in JavaScript – maybe if you already thoroughly test, you’re under the impression that everyone else does, but that’s definitely not the case.

There are three basic, basic, components to running unit tests:

  • Testing harness/base for testing
  • Write a test*
  • Make it pass*

* the order of these is debatable.

As for the first order of business, there are so many choices for how you configure your testing environment that it can be overwhelming where to start. What I generally tell people nowadays is “Karma and Jasmine,” that is, use Karma for your test runner, use Jasmine as the taxonomy for writing your test (describe foo, it bars, expect bazzing).

So how do you set up your basic base for testing? Let’s see how simple it is to do it with the Karma test runner.

Step 0: Create a package.json file

This makes the rest easier. Your package.json can be as little as:

{
  "name": "my-package-name-no-spaces-plz"
}

Tada, valid JSON to build your dependencies on, for maximum laziness.

Step 1: Install karma and karma-jasmine

npm install karma karma-jasmine --save-dev

The save-dev saves it in your package.json for you. See why we did step 0?

Other good stuff includes karma-coverage for generating coverage reports (another post on that), or karma-chrome-launcher if you want to run your tests in Chrome rather than Phantom.

Step 3: Walk through the handy “what do you want” tool

./node_modules/karma/bin/karma init

What this does is generate your karma.conf.js file for you, which is just a config file, much like a Gruntfile. Easy enough to tweak on your own once you have the base set up.

And really, that’s it. It’s fantastically simple to get started. You can start running the test server (runs in a watch environment unless you set singleRun to true) with:

./node_modules/karma/bin/karma start

And should you not want to type that all the time, install karma globally with:

npm install -g karma-cli

That’s it. Now you can go to town writing tests in your test folder (describe, it, expect) and start your project off on the right track.

Be Sociable, Share!

Tags: , ,

No comments yet.

Leave a Reply