Unit Testing Angular Application using Jasmine

Unit Testing Angular Application using Jasmine

Unit testing is one of the most important part of any application development. It helps us to make our source code more robust. Purpose of this article is to cover Jasmine test cases for core component of Angular Application.

Prerequisites:

  1. You are familiar with Angular.
  2. You have created your project with Angular-CLI. i.e. All dependencies are installed and Karma config is ready.

Step 1: Create Global Mocks

Create a globalmocks.ts which will be keeping all test data and other global mocks. Make sure to export data and mocks. There are different levels of mock in case of callback functions.

Source Code of Global Mocks

Step 2: Test cases for Angular Component

When you create a new component using ng component new <component_name> command, it will create component as well as spec file for that component. Ex. your component file name is home.component.ts then spec file name will be home.component.spec.ts.

It will be having basic test case of checking Component is created or not.
All services injected into Component should be mocked once. We need to integrate those mocked services into this component’s specs.

Our Angular Component is as below:

Source Code of Angular Component

Spec file for our Angular Component is as below:

Spec File for Angular Component

Step 3: Test cases for Service

Similar to Step 2, when new service is created using Angular-CLI, it will create spec file with very basic test case. We need to integrate global mocks into this service’s specs.

Our Angular Service is as below:

Source Code of Angular Service

Spec file for our Angular Service is as below:

Spec File for Angular Service

Conclusion:

In this blog post we looked at unit testing Angular application with:

  • Global Mocks
  • Angular Component Test Cases
  • Angular Service Test Cases

Hope this blog post will help you in getting up the pace for Unit testing Angular application using Jasmine

--

--

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store