Angular 2 vs 1

Unit Testing in AngularJS

The modern way of development is to build and deliver web apps that include automated unit test suites. These automated tests exercise your web app to make sure that it works and doesn’t have any bugs. Tests give you the confident to say to your client or project manager or customer, yes we have the right features and yes they all work.

“Test-driven development is a set of techniques that any software engineer can follow, which encourages simple design and test suites that inspire confidence…following these two simple rules can lead us to work much more closely to our potential.

  • Write a failing automated test before you write any code.
  • Remove duplication.”

Kent Beck, Test Driven Development

Unit Tests

Unit testing is essential and of course, AngularJS lets you do some unit testing. In fact, it was built from the ground-up to co-operate with unit testing by using dependency injection.

One of the better tutorials on fully testing your AngularJS app is Full-Spectrum Testing With AngularJS and Karma.

To begin unit testing AngularJS, you need the following:

  • Karma test runner
  • Jasmine or Mocha/Chai test frameworks
  • Sinon for mocking/spies/stubs

The Karma test runner will run whatever tests you have. The Jasmine test framework lets you define tests and has assertions (such as Personally, I prefer the Mocha framework since it only defines tests, and lets you use whatever assertion library you want to use such as Chai, it also has lots of nice features.

A classic on unit testing is Test Driven Development: By Example, it’s by Kent Beck who was one of the founders of the Extreme Programming movement.

Mocking Dependencies for Integration and Unit Testing AngularJS

Sometimes when you’re writing a test, you want to make sure that your service or provider is making the right calls to another service. The way to do this is with mocks. Mocks are fake objects that keep track of which methods were called on them.

Mocks are not essential for writing tests, but there are cases where they do help. When you’re writing a controller that connects to your web app’s REST API, you want to make sure that it calls methodX and methodY. By creating a mock service and registering it with AngularJS, you can write a unit test that makes sure those two methods have been called. When using external 3rd party REST APIs, you may want to mock the $httpBackend to make sure the right calls are being made and the correct responses are returned.

Sinon is valuable for defining mocks. It lets you create method stubs and it lets you spy on method calls.


Find more modules on


AngularJS Meetups