Unit Testing in Angular — Jasmine & Karma

In this article, we will explore the basic about unit testing in angular,

Unit Testing

When you are developing any software that software goes through different types of testing (Unit Testing, Integration Testing, End to End Testing, etc.) after completing all types of testing only software is going to run in the production environment. A lot of confusion between developers on when to start testing software. The right way is to start testing software when you are developing it and the type of testing is called Unit Testing. Now next question may be what unit testing is,

Unit testing breaks the program down into the smallest part of code, usually function-level, and ensures that the function returns the value one expected by the developer. By using a unit testing framework, the unit tests become a separate entity of solution project which can then run automated tests on the program as it is being built.

Benefits of Unit Testing

1) Helps is finding the bugs early as we are running this test whenever we are developing any small functionality. If the Unit test is not there in the place we deploy the software into the Quality environment were the tester may or may not able to find that bug and if we move this into production and the end-user found that bug then resolving this bug will take a lot of time and efforts.

2) If we are following Unit testing in software it will help to reduce production bugs.

3) Unit test make complex code easy to understand

4) Its form of documentation because you defined it for each scenario

5) Easier to change in the future and builds confidence in the developer.

Unit Testing in Angular

We can test our angular application from scratch by writing and executing pure JavaScript functions. Creating an instance of relevant classes, calling function which is defined in the class, and checking actual vs expected results are the activities involved in writing test cases. But since testing is a very common activity therefore different testing tools and frameworks are there in angular called Jasmine and Karma which ultimately helps in reducing the amount of time required to write those tests compared to Java Script.

What is the Jasmine test framework?

Jasmine is the most popular JavaScript library for unit testing web apps. It’s used by default as the default testing framework in an angular project generated using Angular CLI.

Jasmine is a JavaScript testing framework that supports a software development practice called Behavior-Driven Development. Its Specific flavor of Test-Driven Development.

Jasmine, and BDD in general attempt to describe tests in a human-readable format so that non-technical people can understand what is being tested, however even if you are technical reading tests in BDD format makes it a lot easier to understand what’s going on.

Let’s understand some of the terminologies in Jasmine,

1) Suites:

A suite groups a set of specs or test cases. It’s used to test a specific behavior of the JavaScript code that’s usually encapsulated by an object/class or a function. It’s created using the Jasmine global function describe() that takes two parameters, the title of the test suite and a function that implements the actual code of the test suite.

How to Exclude Suites

You can temporarily disable a suite using the xdescribe() function. It has the same signature (parameters) as a describe() function which means you can quickly disable your existing suites by simply adding an x to the function.

Specs within an xdescribe() function will be marked pending and not executed in the report.

2) Specs:

A spec declares a test case that belongs to a test suite. This is done by calling the Jasmine global function it() which takes two parameters, the title of the spec (which describes the logic we want to test) and a function that implements the actual test case.

A spec may contain one or more expectations. Each expectation is simply an assertion that can return either true or false. For the spec to be passed, all expectations belonging to the spec have to be true otherwise the spec fails.

How to Exclude Specs

Just like suites, you can also exclude individual specs using the xit() function which temporarily disables it() spec and marks the spec as pending.

3) Expectations:

The expectation is created using the expect() function. The expectation is a combination of spec and matcher function. Matcher function expects what the developer expects from a specific unit code to perform.

A matcher function compares between actual value (passed to the expect() function it’s chained with) and expected value (directly passed as a parameter to the matcher) and returns either true or false which either passes or fails the spec.

For example, if we wanted to test this function:

function PrintHello() {
return ‘Hello!’;

We would write the Jasmine test spec as below,

describe (‘Print Hello’, () => {(1)it (‘says hello’, () => { (2)expect (PrintHello ()) (3). toEqual (‘Hello!’); (4)});});


1) describe (string, function) -: Defines a test suite that contains a collection of individual test specs.

2) It (string, function) -: Defines individual Test Spec, this contains one or more test expectation.

3) Expect (actual) -: Expression what we call as expectation. In conjunction with the matcher, it describes the expected behavior of the application.

Matcher (expected) -: Expression what we call as Matcher. It performs a Boolean comparison between the expected value and actual value. If the result is false then the spec fails.

Jasmine comes with some prebuilt matches as shown below,

Setup and Teardown:

Sometimes while doing test feature we need to perform some setup and also sometimes need to perform cleanup activities. Jasmine has few functions which make this easier.

1) beforeAll -: This function is called once, before all the specs in a test suite (describe function) are run.

2) afterAll -: This function is called once after all the specs in test suite are finished.

3) beforeEach -: This function is called before each test specification (it function) is run.

4) afterEach -: This function is called after each test specification is run.

We can use this our sample as shown below,

describe (‘Print Hello’, () => {let expected = “”;beforeEach (() => {expected = “Hello!”;});afterEach (() => {expected = “”;});it (‘says hello’, () => {expect (PrintHello ()). toEqual (expected);});});

If you are building an angular application using angular CLI you will have a whole test framework configured for you means Jasmine and Karma available for you.

Steps to follow,

Create a project using -> ng new project_name

After creating the project karma.conf.js file will be created for you in the chrome browser by default.

When you look there are already some test return for you called app.component.spec.ts (Using spec.ts test environment understands some test return and need to execute that)

In this test file, we are checking the header welcome to UnitTestSample is there or not.

For running this test execute the command in terminal -> ng test as shown below,

After running this karma launch a new browser and shows the result as below,

Now let’s right some of our own tests,

Create a file with name comp.spec.ts

Test 1 -: Compare two strings

Test Code:


Test2: Test a function created in service

Go to the terminal and create a service -> ng g service test

Add a function in the service file,

In the spec file below if you look we imported TestBed which is required in case if we are testing service, then we imported service also which we are testing. In beforeEach we are injecting a service which we imported it ensures that before running each test service must be available. Also using toBeTruthy matcher we are ensuring that service is there or not.

In the same way we are checking add function which we defined is exists or not and also it is returning correct result or not.


Configure Karma for other browsers:

For configuring in other browsers you need to install plugin related to that browser using npm,

npm install karma-firefox-launcher — save-dev

Do changes according to in Karma.config.json which includes adding browser plugin and adding browser name in the list.

What is karma test runner:

Manually running Jasmine tests by refreshing a browser tab repeatedly in different browsers every time we edit some code can become tiresome.

Karma is a tool which lets us spawn browsers and run Jasmine tests inside of them all from the command line. The results of the tests are also displayed on the command line.

Karma can also watch your development files for changes and re-run the tests automatically.

Karma lets us run Jasmine tests as part of a development tool chain which requires tests to be runnable and results inspectable via the command line. It’s not necessary to know the internals of how Karma works. When using the Angular CLI it handles the configuration for us and for the rest of this section we are going to run the tests using only Jasmine.

Thank You, See you in the next article !!

You can reach out or connect to me over here,

LinkedIn: https://www.linkedin.com/in/vaibhav-bhapkar

Email: vaibhavbhapkar.medium@gmail.com

If you want some technical topics to be discussed with group of participants please raise a request on following link: http://myblogsenquiry.somee.com/

Technical Speaker | Computer Engineer | Full Stack Web Developer | ML Enthusiast | * Knowledge Shared = Knowledge² *