Full stack Web Development

Introduction to Angular 2 Unit Testing

This blog introduces you to Angular 2 Unit Testing and we will learn how to write the test with Angular CLI. We will be focussing on how a test generally works and why we need tests in our projects and which testing utility does Angular 2 offer.

We recommend users to install node.js and Angular CLI before proceeding to work on this blog.

img1
needOf_unittest

Why do we need unit testing?

From the above pictorial representation, we can say that we need unit testing to confirm the following:

  • Does the component work as intended?
  • Does the pipe work as intended?
  • Does the service work as intended?
  • Does the input work as intended?
  • Does the injection work as intended?

Advantages of Unit Testing

img2
advantages_unittest

From the above pictorial representation, we can say that unit testing allows us to:

  1. Guard against breaking changes: While upgrading Angular 2 projects, we will re-run the test to know which tests have now failed.
  2. Analyse code behaviour (expected and unexpected): We can also analyse our code to detect the expected and unexpected results.
  3. Reveal design mistakes: We can also reveal design mistakes while writing the unit test.

Setup unit test

  1. Create a new project by running the command: ng new project_name

In your project there is one file app.specs.ts, in which we have different sets of rules for testing that is described in the “it block” as shown in the screenshots below:

img3
itblock

From the above pictorial representation, we can infer the following points:

  • A testbed is the main Angular 2 testing utility and it helps us set up dependencies for our test.
  • Every it block is executed independently of the other it block.

Karma Setup and its Definition:

Over here, we are using Karma for our test which is a JavaScript test runner and our Angular CLI already provides the initial configuration to use Karma. The setup is done through the common interface of the karma configuration file called karma.conf.js. This file will tell Karma which locations the tests are in, which reporting mechanism to use, and which browser to use to execute these tests.
Within this configuration file, the configuration code is put together by setting module.exports to point to a function which accepts one argument: the configuration object.

// karma.conf.js
module.exports = function(config) {
config.set({
basePath: '../..',
frameworks: ['jasmine'], // jasmine is a open source testing frame work.
//...
});
};

Let’s see what are we actually testing in the “it block”
In the first it block, we are expecting our app toBeTruthy, i.e., somehow existing.
In the second it block, we expect our app to have a title property with some defined values.
In the third it block, we expect to have an h1 element with textContent which contains some defined values.
Now let’s run the test to see some results
To run the test, open your command line, navigate to your project folder, and run the command ‘ng test’ which will start the Karma. If the test is successfully executed, you will see the following results:

img4
Test_Result

From the above pictorial representation, we can say that all the three tests which are described in the “it block” are executed successfully.
Change something in your project to see if the test fails
In your app.component.ts change the title to “works!” from “app works” as shown below.

img3
Change_Test

Now re-run the test, you will see the following result.

img6
failed_test

We can see that the two tests failed, for the 2nd and the 3rd it block.

Reasons behind the failure of this test:

  1. The second it block is expected to have the title “app works,” but it is changed to “works!”
  1. The third it block is expected to have an h1 element which has some textContent and contains the value “app works” but the value is changed to “works!”

Now we will dive deeper into testing by creating a new component and service.
In our user.component.html, our aim is to output the user name if a user is logged in or “Please Log In First” as shown below:

img7
username

Our next step is to create the user.service.ts file in the user folder, where we have our user component. In this file, we will export the class UserService and in this class, we have a user object.

// user.service.ts
export class UserService{
user={ // here user is a object
name:"Sumit Kumar "
};
}

To retrieve the user object, define in user.service .ts we will inject userservice in user.component.ts as shown below:

img8
injecting_userservice

We are now in a position to Create some test for the user component and for this we will define 3 it blocks in the user.component.spec.ts as shown below:

img8
custom_test

From the above pictorial representation, we can include that:

  1. In the 1st it block, we will test whether our app was created or not.
  2. In the 2nd it block, we will test if user service works, user name= app.user.name, and we are also running the changedetection method to update the changes.
  3. In the 3rd it block, we are testing whether the username is displayed or not or if the user is logged in, and for this, we will access our app and set isLoggedIn=true which is highlighted in the 3rd it block in the above pictorial representation. If you don’t mention app.isLoggedIn=true, then the test will fail because we don’t have access to the property isLoggedIn.

Save the file and run the command  ng test, we will see six successful tests, i.e., 3 tests from app.component.specs.ts and 3 from user.component.specs.ts as shown below:

final_result

Hope this blog helped you in understanding the need of Unit Testing and ways to write your own Test cases for your project.
Keep visiting www.acadgild.com for more updates on the technical and certification courses.

One Comment

Leave a Reply

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

This site uses Akismet to reduce spam. Learn how your comment data is processed.

Related Articles

Close
Close