Unit Testing of AngularJs code using Jasmine

Posted By : Harsh Soni | 31-Dec-2018
Unit Testing your AngularJs code using Jasmine

 

As a developer, I can say that we all have seen that "Small changes to our code fixes one thing and breaks something else", because this is almost inevitable when you have a larger amount of code.

 

But what if we have a way of knowing when something breaks as a result of some changes? You can modify your code without any fear or worry about breaking anything. 

 

Unit Testing

 

Unit testing automatically detects any problems in the code and you can save your time and efforts of debugging easily. Testing your codebase is easy as you take a piece of code-- a function-- and verify it against specific situations. Unit testing is a structured and automated way of testing your code base. Angular Js has its own testing framework called "Karma". It is a command line tool which loads your application's source code and executes your tests on any web browser.

 

For here testing our angular code we are using Jasmine framework

 

Jasmine is the most popular behavior-driven development framework and it is most common amongst the developer for testing AngularJs applications. You can keep your test code well structured and documented for all time use.

 

In Jasmine we use the describe inbuild function to group our tests together:

 

describe("Sort the list of users", function() {
  // individual tests go here
});

 

After that, each individual test can be called using it inbuilt function.

 

 describe('sorting the list of users', function() {
  it('Sort the list of users', function() {
    // your test assertion goes here
  });
}); 

 

Jasmine also provides matchers which let you make assertions:

 

describe('sorting the list of users', function() {
  it('Sort the list of users', function() {
    var users = ['jack', 'igor', 'jeff'];
    var sorted = sortUsers(users);
    expect(sorted).toEqual(['jeff', 'jack', 'igor']);
  });
});

 

Jasmine comes with lots of matchers you can read the full documentation here. We can also user karma and jasmine together using the karma-jasmine library.

 

It also has sample codes to test filter, controllers modules and directives. You can learn more about then from here.

 

 

Request for Proposal

Recaptcha is required.

Sending message..