Lugo Labs

Testing JavaScript with Karma

I really like karma, it's an amazingly fast JavaScript test runner. It works for Mac and Windows, even though the latter can be a pain at times.

Karma is a node.js module, so node must be installed first. Then I ran on my shell:

sh
npm install -g karma

That's it. To use it, I needed to create your config file. On the shell again, I navigated to my project, where I wanted to place the config file, and ran:

sh
karma init

(In the past I had tried to copy the config file from the github repo, but it proved a bit confusing.) This created a karma.config file, which I updated to include the source and test JavaScript files, as well as any testing framework. My favourite framework is jasmine, and luckily karma comes with a jasmine adapter.

One of the issues I had with the config is the list of browsers needed for testing. I had to make sure that the executable path of the browsers was in the PATH variable, otherwise karma would not be able to start them. Sometimes I started the browsers manually.

Now, time to start karma:

sh
karma start

Or if the config file is on another folder (in my case: vendor):

sh
karma start vendor/karma.config

Karma starts a CLI server, and fires any browser it can find in the browsers list specified in the config file. You can also start any browser manually, and navigate to the URL of the karma's server (at the moment http://localhost:9876).

All the tests are executed on the browser and the results appear on the shell. And the best part is that karma watches the source/testing files specified in the config: anytime the files are changed, the related tests will run.