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:
- You are familiar with Angular.
- You have created your project with
Angular-CLI
. i.e. All dependencies are installed andKarma
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.
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:
Spec file for our Angular Component is as below:
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:
Spec file for our Angular Service is as below:
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