Unit Testing Angular 9/8 Application using Jasmine & Karma Example

    Mar 30, 2020       by Pankaj Kumar
angular-app-unit-testing-karma-jasmint.jpg

In any programming language, Unit testing is the process by which an individual set of the source is tested to check whether they are fit for use. An individual set of source code or unit is the smallest possible testable component. Unit testing plays a very important role when new features are being added in a working functional application, Here it reduces the chances of bugs to the rest of the functionality due to the latest change.

 

In this article, We will see unit testing in one of the very popular Javascript frameworks, Angular. This article will explain step by step how to start writing unit test cases for Component and Service in Angular application using Jasmine test framework and Karma.

 

What is Jasmine?

Jasmine is an open-source testing framework for JavaScript. It aims to run on any JavaScript-enabled platform, to not intrude on the application nor the IDE, and to have easy-to-read syntax. It is heavily influenced by other unit testing frameworks, such as ScrewUnit, JSSpec, JSpec, and RSpec. 

Jasmine provides several valuable functions to write tests. Here are the main Jasmine methods:

  • it(): Declaration of a particular test
  • describe(): It’s a suite of tests
  • expect(): Expect some value in true form

 

What is Karma?

A simple tool that allows you to execute JavaScript code in multiple real browsers. The main purpose of Karma is to make your test-driven development easy, fast, and fun.

If we talk about the type of functional testing, Then there are mainly 3 types of testing.

A. Unit Testing

B. Integration Testing

C. End-to-End Testing

I assume that Node, NPM, and Angular CLI configured properly in your system.

 

Let's Get Started

 

Create Basic Angular Application

Run below command to create basic Angular application using Angular CLI

ng new ng-unit-test-app

 

Once you get below the message of Successful installation on the terminal/command prompt.

angular app created

 

Now move to the project folder using cd /ng-unit-test-app and run the app using ng serve.

 

Test Angular Component

Here We will create a component named post-list using angular CLI command, later on We will use dummy API to show the list of posts.

Create a component using the below command.

ng generate component post-list

 

Inside the generated component, Create a variable named userName with value in it.So that test case can be created on the base of this variable. Now the post-list.component.ts file will look like below:

 

 
import { Component, OnInit } from '@angular/core';
 
@Component({
selector: 'app-post-list',
templateUrl: './post-list.component.html',
styleUrls: ['./post-list.component.css']
})
export class PostListComponent implements OnInit {
 
constructor() { }
userName:String = "John Doe";
ngOnInit(): void {
}
 
}
 

 

When we create an Angular component with Angular CLI, A folder is created with the name of the component name provided having 4 different files inside it.

  • A CSS file for the component styles.
  • An HTML file for the component template.
  • A TypeScript file with a component class namedPostListComponent.
  • A test file for the PostListComponent class.

The last file in the above list, post-list.component.spec.ts is responsible for performing the testing related task in the Angular application.

By default, the Testing file looks like below.

 

 
import { async, ComponentFixture, TestBed } from '@angular/core/testing';
 
import { PostListComponent } from './post-list.component';
 
describe('PostListComponent', () => {
let component: PostListComponent;
let fixture: ComponentFixture<PostListComponent>;
 
beforeEach(async(() => {
TestBed.configureTestingModule({
declarations: [ PostListComponent ]
})
.compileComponents();
}));
 
beforeEach(() => {
fixture = TestBed.createComponent(PostListComponent);
component = fixture.componentInstance;
fixture.detectChanges();
});
 
it('should create', () => {
expect(component).toBeTruthy();
});
});
 

 

Below is a simple test case inside describe function.

 

 
it(`should have a userName 'John Doe'`, async(() => {
  fixture = TestBed.createComponent(PostListComponent);
  component = fixture.debugElement.componentInstance
  expect(component.userName).toEqual('John Doe');
}));
 

 

Now after adding above code, Save it and run below command to start testing Angular Component.

ng test

 

ng test command built the app in watch mode and launches the karma.

After the successful compilation of the app, A new pop window opens with the details about the success cases and failure cases.

Angular Component Unit TestingTest Angular Service

Now we will perform unit test for a service which manages the HTTP Requests in Angular application. Create a service with below Angular CLI command:

ng generate service _services/post

 

Above command created two different files inside the provided path

  • _services/post.service.spec.ts
  • _services/post.service.ts

We will use here JSON placeholder dummy API of post listing. A method postList() is created to fetch the post listing from the third party server. 

See the updated post.service.ts file below:

 

 
import { Injectable } from '@angular/core';
import { Observable } from 'rxjs';
import { HttpClient } from '@angular/common/http';
 
export interface Post {
userId: number;
id: number;
title: string;
body: string;
}
@Injectable({
providedIn: 'root'
})
export class PostService {
API_URL: String = 'https://jsonplaceholder.typicode.com/posts';
 
constructor(
private http: HttpClient
) { }
 
postList(): Observable<Post[]> {
return this.http.get<Post[]>(`${this.API_URL}`)
}
 
}
 

 

Angular’s new HttpClient has a testing module, HttpClientTestingModule, that makes it easy to unit test HTTP requests.

In this Article, we are going to write a unit test for the post method crated using the HTTP GET request by taking the help of the HttpTestingController service.

 

Below is the updated code of file post.service.spec.ts

 

 
import { TestBed, async, inject } from '@angular/core/testing';
import { HttpClientTestingModule, HttpTestingController } from '@angular/common/http/testing';
import { PostService } from './post.service';
 
describe('PostService', () => {
let service: PostService;
let httpMock: HttpTestingController;
 
beforeEach(() => {
TestBed.configureTestingModule({
imports: [
HttpClientTestingModule,
],
providers: [
PostService
]
});
service = TestBed.inject(PostService);
httpMock = TestBed.get(HttpTestingController);
});
 
it('should be created', () => {
expect(service).toBeTruthy();
});
it(`should fetch posts as an Observable`, async(inject([HttpTestingController, PostService],
(httpClient: HttpTestingController, postService: PostService) => {
 
const postItem = [
{
"userId": 1,
"id": 1,
"title": "sunt aut facere repellat provident occaecati excepturi optio reprehenderit",
"body": "quia et suscipit suscipit recusandae consequuntur expedita et cum reprehenderit molestiae ut ut quas totam nostrum rerum est autem sunt rem eveniet architecto"
},
{
"userId": 1,
"id": 2,
"title": "qui est esse",
"body": "est rerum tempore vitae sequi sint nihil reprehenderit dolor beatae ea dolores neque fugiat blanditiis voluptate porro vel nihil molestiae ut reiciendis qui aperiam non debitis possimus qui neque nisi nulla"
},
{
"userId": 1,
"id": 3,
"title": "ea molestias quasi exercitationem repellat qui ipsa sit aut",
"body": "et iusto sed quo iure voluptatem occaecati omnis eligendi aut ad voluptatem doloribus vel accusantium quis pariatur molestiae porro eius odio et labore et velit aut"
}
];
 
postService.postList()
.subscribe((posts: any) => {
expect(posts.length).toBe(3);
});
 
let req = httpMock.expectOne('https://jsonplaceholder.typicode.com/posts');
expect(req.request.method).toBe("GET");
 
req.flush(postItem);
httpMock.verify();
 
})));
});
 

 

Now again run ng test command to run the test cases created for Angular service.

After successful compilation, A popup  will open with below information.

Angular Service Unit Testing

 

Conclusion

In this article, we learned about how to start writing test cases for Angular Application. 

If you are new to Node.js then find Angular Sample Projects to start the app for enterprise-level application.

Let me know your thoughts over email demo.jsonworld@gmail.com. I would love to hear them and If you like this article, share it with your friends.


WHAT'S NEW

Find other similar Articles here: