Unit testing for AngularJS

Thirumal S

1 min read

I recently wrote unit testing for an AngularJS application. We know AngularJS is one of the most popular front end framework used by developers. AngularJS is developed by google and it comes with an excellent set of documentation for unit testing. Here, I will share my knowledge about writing unit testing for Angular application.
Karma and Protractor are the two tools for testing AngularJS applications, that was shared in the documentation.
Karma is the command line tool for unit testing and Protractor is a testing framework for writing end-to_end(E2E) tests.
In this blog I am going to focus on writing unit test cases for AngularJS application using karma.
Tools used for testing Angular applications :
1. Karma: Karma is a Javascript command line tool which is executed and displays the results in command line. It is a NodeJS application and should be installed through npm.
2.Jasmine: Jasmine is the most popular BDD(Behavior Driven Development) framework for JavaScript. It also provides in-built functions to structure our tests.
Karma installation and configuration steps,

  • If you have not installed NodeJS –
    first install NodeJS.
  • Install karma CLI globally –
    [source]$ npm install -g karma-cli[/source]
  • Install Karma locally in your project –
    [source]$ npm install karma –save-dev[/source]
  • To configure Karma run the command in command line –
    [source]$ karma init[/source]

This will create a configuration [karma.conf.js] file in your project directory.
Next, we will load all js files in karma.conf.js which allows these files to be available during testing.
[source]files: [
1. Testing a controller
Here, I have written a simple controller, Module name is app and controller name is studentMarkController.
Next we will write testing for this controller.
Here, <describe>, <beforeEach> and <it> are keywords provided by Jasmine.
Then you can run this command and see that your test passed.
[source]$ karma start[/source]
2. Testing a directive,
Here, I have written a simple directive, this will accept only number values.
sampleApp is the module name and ‘autonext’ is the dependancy injection. Module function is defined in app.js.
We inject the $compile service and $rootScope before each jasmine test. $compile is used to render the directive. Then you can run your test and see them pass.
My test results in command line,

I have written testing for routing also. My source code is available here.

Related posts:

Leave a Reply

Your email address will not be published. Required fields are marked *