Behavior Driven Development Using Karma And Jasmine In Angular 2

Writing unit tests for applications is always given a secondary preference due to the time and the cost. Writing tests for logic for the front end script is more complex and time consuming. Thus, it is often left out. However, as more and more tools are coming, writing unit tests is becoming more easy and manageable.

In this article, we will learn how can we write unit tests for the components in Angular 2. Angular 2 is a powerful and fast JavasSript library, which is used to develop complex front-end Applications for the Web and mobiles.

TDD is Test Driven Development, where the developers write tests that drive the software development. It focuses more on each and every unit test for every function, as it doesn't matter what it does.

BDD is Behavior Driven Development that focuses on the functionalties in a story telling format. We write the behavior & specification that then drives our software development.

You should already have node.js installed tools that we will use.

Jasmine is a Behavior-Driven Development (BDD) framework to test JavaScript code. It does not depend on any other JavaScript frameworks.

npm install --save-dev jasmine

(Install Jasmine from NPM, if not already installed).

Karma is a JavaScript test runner, which is created by AngularJS team

npm install --save-dev karma

(Install Karma from NPM, if not already installed).

Thus, you can see that we will use 2 tools. Jasmine is for writing our Tests and Karma is for running the Tests.

Run NPM install, if you are downloading this article source code before proceding.

Important

Inside your Applictaion, there must be a karma.conf.js file, which has all the settings to run the Test. This config file tells Karma Test running which test framework to use (jasmine in our case), where our test files (*.spec.ts) are located etc.

Step 1

Under the app folder, create a folder Math and then create 3 files.

..app/math

math.component.ts (Component TypeScript file)

math.component.html (Component View HTML file)

math.component.spec.ts (Component Test file)

All Test files will have .spec.ts naming convention.

math.component.html

textboxes 2 way binding, using ngmodel with the varaible num1 and num2

Button that calls CallEvent, when clicked.

<h1>

Math Components

</h1>

Number 1 : <input type=text size=20 [(ngModel)] ="num1">

Number 2 : <input type=text size=20 [(ngModel)] ="num2">

<input type=button value="Multiply" (click)="CallEvent('MULTIPLY');">

<input type=button value="Multiply" (click)="CallEvent('ADD');">

<br>

Output : {{result}}

</h1>

math.component.ts

num1 and num2 are declared as number.

Callevent calls Add or Multiply method depending on an action.

Add and Multiply method. These two methods will be tested by us.

import {

Component

} from '@angular/core';

@Component({

selector: 'my-math',

templateUrl: './math.component.html'

})

exportclass MathComponent {

num1: number = 0;

num2: number = 0;

result: number = 0;

private CallEvent(action) {

switch (action) {

case'MULTIPLY':

this.result = this.Multiply();

case'ADD':

this.result = this.Add();

}

}

private Multiply() {

returnthis.num1 * this.num2;

}

private Add() {

returnthis.num1 + this.num2;

}

}

Finally, our Test file will look, as shown below.

math.component.spec.ts

import {

TestBed,

async

} from '@angular/core/testing';

import {

HttpModule

} from '@angular/http';

import {

MathComponent

} from './math.component';

import {

FormsModule

} from '@angular/forms';

describe('MathComponent', () => {

beforeEach(() => {

TestBed.configureTestingModule({

declarations: [

MathComponent

],

imports: [FormsModule, HttpModule]

});

TestBed.compileComponents();

});

it('should multiply 2 numbers', async(() => {

const fixture = TestBed.createComponent(MathComponent);

const app = fixture.debugElement.componentInstance;

app.num1 = 10;

app.num2 = 20;

let result = app.Multiply();

expect(result).toEqual(200);

}));

it('should add 2 numbers', async(() => {

const fixture = TestBed.createComponent(MathComponent);

const app = fixture.debugElement.componentInstance;

app.num1 = 10;

app.num2 = 20;

let result = app.Add();

expect(result).toEqual(30);

}));

});

Now, let's see our test file in detail.

The test suite should begin with describe(..).

Inside the describe(..) method, all the Tests of the math component are written.

beforeEach method runs code before each Test. Thus, in this case, it initializes our module and configures our test.

it(...) is used to create your test.

The test follows 3 simple rules

ArrangeSetup everything needed for the running the tested code. This includes any initialization of dependencies, mocks and data needed for the test to run.

const fixture = TestBed.createComponent(MathComponent);

const app = fixture.debugElement.componentInstance;

Action

Invoke the code.

app.num1 = 10;

app.num2 = 20;

let result = app.Multiply();

Assert

Specify the pass criteria for the test, which fails it, if not met.

expect(result).toEqual(200);

Now, we are ready to run our Tests.

STEP 2

Open the command prompt and run from your Angular 2 folder.

I hope I was able to explain how to run Tests, using Jasmine and Karma in Angular 2.Thanks.