May 20, 2015

How to get started with AngularJS testing using WebStorm

Today I've got a need to write tests for an independent angular directive. Very small package, no express, no grunt, no any pre-built and pre-configured stuff I used to. So, it was like a tiny challenge to get it worked conveniently with as low effort as it's possible.

So, tests. There are two main directions to have them run:

  • run them in browser manually (create html-page, include frameworks, include code to be tested, etc)
  • use test runner like Karma.
The second way looks more convenient and gives few extras that can be useful in future. Let's get it to work!

-1. Pre-requisites. You should have WebStorm and NodeJS installed (don't say "nodejs sucks use io.js" because they're going to merge back to a single code base). 

0. package.json. You should have it in your project directory. If you don't have it - run npm init and accept default values. It will be fast and you can change them later.

1. Install minimal set of dependencies:
npm install jasmine-core karma karma-jasmine angular angular-mocks

2. Set up Karma. In the project root create a file karma.conf.json with the following content:
module.exports = function (config) {

    basePath: './',

    files: [

    autoWatch: true,

    frameworks: ['jasmine']
3. Set up WebStorm. Here we need 3 steps:
3.1. Turn on Karma plugin:
3.2. Set up syntax highlight and autocomplete for Jasmine. 
  • Go to Settings -> Languages & Frameworks -> JavaScript -> Libraries;
  • Press "Download..." button;
  • In the select box choose "TypeScript community stubs";
  • In the list find and select "Jasmine", then click "Download and Install".

3.3. Create Karma Run configuration:

4. Add npm test command (optional). In case you'll run karma from command-line using npm add the following command to your package.json under "scripts" section:
  "test": "node node_modules/karma/bin/karma start karma.conf.js"

5. Write some tests: