At Agira, Technology Simplified, Innovation Delivered, and Empowering Business is what we are passionate about. We always strive to build solutions that boost your productivity.

,

A Complete Cheat Sheet Tricks For Angular Unit Testing

  • By Manigandan
  • November 29, 2018
  • 1485 Views

Unit testing is one of the effective testing technique used to test every individual component of the software and its highly ensures to improve all integral part of application like designs, performance and refactoring. Also helping us to include new features without affecting the existing system. On utilizing its convenience favor on Angular, today we’re planning to discuss on applying unit testing on Angular along with its complete cheat tricks.
We don’t want to bore you with unnecessary statements so let’s jump straight to the concept, Basically, Jasmine and Karma test framework both are good choice and has everything to test the angular application and here am using Jasmine framework similarly go ahead with your choice and use the below command to run the test in angular CLI.

ng test

Once the command executed, you will get the no of success & failure messages as show in below pic,
Angular unit test
Parallely a separate local browser will get open for unit testing which you can check here, http://localhost:9876 and this will look like the below screen,
Angular Unit Browser
Initially we need to write the unit test code in *.spec.ts(app.component.spec.ts) in Angular CLI. You can note the status of each test cases in above picture and currently it got 3 success out of 3.
Those 3 success conditions are,

  1. Should create the app component
  2. Should have as title variable in app.component.ts
  3. Should render title in a h1 tag

Before writing the unit test code, we must import the modules. So based on my test case, below are the required modules to import. Similarly you can import the required modules based on your test case.

import { TestBed, async } from '@angular/core/testing';
import { AppComponent } from './app.component';

TestBed is the primary API for writing unit tests in Angular applications and also in libraries. Async is a utility module which provides straight-forward, powerful functions of asynchronous which will fetch and work based on every execution.
Before everything, we must describe the testing component and you can use the below code to test,

describe('AppComponent', () => {
beforeEach(async(() => {
TestBed.configureTestingModule({
declarations: [
AppComponent
],
}).compileComponents();
}));

Below code will help you to check whether the required component is available or not,

it('should create the app', async(() => {
const fixture = TestBed.createComponent(AppComponent);
const app = fixture.debugElement.componentInstance;
expect(app).toBeTruthy();
}));

Using this code, you can check whether the required variable is present in app component or not,

it(`should have as title 'app'`, async(() => {
const fixture = TestBed.createComponent(AppComponent);
const app = fixture.debugElement.componentInstance;
expect(app.title).toEqual('app');
}));

Now we weed to look for the specified element so in our scenario i have mentioned H1 tag so it will look for the exact tag to fetch the content from specified H1 tag.

it('should render title in a h1 tag', async(() => {
const fixture = TestBed.createComponent(AppComponent);
fixture.detectChanges();
const compiled = fixture.debugElement.nativeElement;   expect(compiled.querySelector('h1').textContent).toContain('Welcome to app');
}));

Unit Test Case For Creating Login

Next will look into creating a unit test for simple login component so with that we can able to check whether the user logged in or Not.
The following ng comment for create a new component, In our example create a login component.

ng generate component login
Or
ng g c login

After executing this command then automatically the below mentioned files will be created for you,

user.component.ts

user.component.css

user.component.html

user.component.spec.ts

Let’s look into the purpose of each files,

user.component.ts

The user.component.ts file will have one user object (user), Boolean variable (isLogin) and one user object which will assign the name.

user: {name: string};
isLogin = true;
ngOnInit() {
this.user = {name: 'mani'} ;
}

user.component.html

This will check whether the user logged in or not,

<div *ngIf="isLogin">
<p>{{user.name}}</p>
</div>
<div *ngIf="!isLogin">
<p>User not loged in</p>
</div>

user.component.spec.ts

This will import and declare the component,

import { async, ComponentFixture, TestBed } from '@angular/core/testing';
import { UserComponent } from './user.component';

Declare the user component as follow,

describe('UserComponent', () => {
let component: UserComponent;
let fixture: ComponentFixture<UserComponent>;
// write the unit test code here
});

Related: How to make Angular Application SEO Friendly Using Pre Render

Test case to track behavioral changes of the components

beforeEach(() => {
fixture = TestBed.createComponent(UserComponent);
component = fixture.componentInstance;
fixture.detectChanges();
});

Test case to check whether the user component is available or not,

it('should create a user component', () => {
expect(component).toBeTruthy();
});

Next, we need to check whether the user name is declared or Not. if it’s declared then the user will be logged in, else the user cannot login.

Test case to check the user state by assigning Boolean values to isLogin variable,

it('should display the user name if user is logged in', () => {
fixture = TestBed.createComponent(UserComponent);
component = fixture.debugElement.componentInstance;
component.isLogin = true;
fixture.detectChanges();
let compiled = fixture.debugElement.nativeElement;   expect(compiled.querySelector('p').textContent).toContain(component.user.name);
});

If the user is logged in then we will be updated with the user object name,

Test case for the users who’re not logged in,

it('should display the user name if user is logged in', () => {
fixture = TestBed.createComponent(UserComponent);
component = fixture.debugElement.componentInstance;
component.isLogin = false;
fixture.detectChanges();
let compiled = fixture.debugElement.nativeElement;
expect(compiled.querySelector('p').textContent).toContain('User not loged in');
});

Best To Read: Angular 7 Released! Track The Major Changes In Angular

Angular help us to view the test results in your browser so then & there you can able to view the complete track record of test cases in browser.

We have done with all the simple unit test cases for Angular, try this on your angular application and let us know your opinions on comment section. Also you can get the complete source code here in case of any reference. Hope you will find it helpful!

Are you looking for Angular developers to build your application? Here is the comprehensive guide on how to hire Angular developers. Also, it guides you with the following topics.

  • Angular developer skills.
  • How an ideal Angular developer resume should look.
  • Top Angular developer tools.
  • Commonly asked Angular developer interview questions.
  • Present Angular developer job opportunities.

Manigandan

An ideal Full Stack Developer, having around 5+ years of experience in web development arena, expertise in AngularJS, Nodejs, PHP and also scoring 6 years of experience in Networking & Window servers. A perfect all-rounder has fondness to play diverse role. he always strives to match perfection and likely remains the best in whatever role he takes.