Victor Queiroz

AngularJS: Creating Tests with Jasmine and Karma

Before anything else, it’s important that you read the article Jasmine: First Contact with Unit Testing, if you don’t already know what Jasmine is.

Dependencies

Writing tests

It’s pretty simple. You’ll want to use Jasmine’s beforeEach(), along with module and inject from angular-mocks, and Angular’s own $injector to load all the necessary dependencies.

Here’s a simple example where I load a service from within a module:

describe('app module', function () {
  var User;

  beforeEach(module('app'));

  beforeEach(inject(function ($injector) {
    User = $injector.get('User');
  }));

  it('should have a User service', function () {
    expect(typeof User.$get).toEqual('function');
  });
});

Notice that on line 4, we load the module. It’s important to remember that if this module uses services from another module, that other module will also need to be loaded — just add it below the beforeEach where we load the main module and your problem will be solved.

On line 6, we inject the $injector into the function using inject. The inject function can be used anywhere in your test. From there, you can import $compile if you want to compile directives into the DOM, or $rootScope if you want to create a $scope to compile directives with.

Running your tests with Karma Runner

Installing Karma

You should install Karma via npm globally:

npm install -g karma

And locally in your project (or it won’t work):

npm install --save-dev karma

Creating a Karma configuration file

It’s simply simple (?) and fast! Go to your project’s root folder and type:

karma init

Fill in all the questions and BOOM — you have a Karma configuration file.

Running the tests with Karma

Another one of Karma CLI’s wonders:

karma start --no-single-run --log-level debug

You can swap the --no-single-run parameter for --single-run, and it won’t keep watching your files for changes to restart the tests. It’s actually important to use --single-run as the default if you plan on using a Continuous Integration system — otherwise, it might report your tests as failing when it actually just stopped them to watch for file changes.

Final notes and tips

Keep in mind that you’ll need to configure your Karma configuration file (usually karma.conf.js, located in your project’s root) to load angular and angular-mocks, along with all other assets you load to make your modules work correctly.

Your test file should look similar to the example above. If you have any questions, you can read the angular-mocks documentation OR come here and leave a comment — I’ll be happy to answer.

Any questions, leave them in the comments or send me an email. Cheers and until next time!

Comments