How to write Karma Test Cases for Angular?

How to write Karma Test Cases for Angular?

Today, I'm going to explain how to write unit test cases using Karma/Jasmine in Angular. This will cover the basics of it so if you are looking for any advanced tutorial on Karma/Jasmine then this might not be for you. However, if you don't know what is Karma/Jasmine, I would suggest you to visit their official website because I am not a teacher to teach you the theoritical concepts of any programming language or framework. I am an experienced full-stack developer sharing my knowledge and experience for free via my blogs and videos.

External References:

Angular     Jasmine Framework     Karma Test Runner

Let's start.

Why do we write test cases in Karma/Jasmine?

Jasmine is a unit testing framework and Karma, built on top of that is a test-runner, mostly used with Angular applications for developers to write unit test cases. Karma was developed by team Angular for the sole purpose of easing the process of writing unit test cases.

Usually, there are two types of testing methods:

  1. Manual Testing
  2. Automation Testing

And, the one we're covering here is an automation testing approach. Further, we have different types of testing:

  1. Unit Testing (Component-level Testing)
  2. Integration Testing
  3. System Testing (End-to-End Testing)

So the automation testing approach we're covering is unit testing. In this approach, we write unit test cases on individual angular component or class level with no interaction with server at all. This helps in ensuring the logic written in our component file is working as per expectation or you may say that we are following test-driven development approach.

In this we follow AAA approach of testing.

What is AAA approach of unit testing?

AAA approach is defined as:

Arrange
Act
Assert

At first, we Arrange the necessary variables and requirements.
Then, we Act upon it by calling the methods and spyon.
At last, we Assert on it to ensure that we're getting the expected results.

describe("Your Suite Name here..", function() {

  it("It is a test case so specify a logical text here..", function() {
    // Arrange
    let myVar;

    // Act
    myVar = true;

    // Assert
    expect(myVar).toBe(true);
  });

});

This 3 As (AAA) approach of unit test development is all we need to write each test case (it) in our special file (under describe).

Now, let's dive into some actual coding part.

Basic skeleton of a spec.ts file

With Angular, Karma is a default test runner and is defined in angular.json file and the Karma/Jasmine related configuration is defined in karma.conf.js & test.ts under /src folder.

Suppose you are having a app.component.ts file as shown below:

import { Component } from '@angular/core';

@Component({
  selector: 'app-root',
  templateUrl: './app.component.html'
})
export class AppComponent {

    constructor () { }

    greeting () {
        return "Welcome to my blog!";
    }

    sum (value1, value2) {
        return value1+ value2;
    }

    divide (value1, value2) {
        if (value2 == 0) {
            return "Cannot be divided by 0";
        }
        return value1/value2;
    }

}

For that, your app.component.spec.ts file should look like:

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

describe("This is AppComponent Test Cases", function() {

  it("greeting method should execute", function() {
    let component = new AppComponent();
    let msg = "Welcome to my blog!";
    spyOn(component, 'greeting');
    expect(component.greeting()).toBe("Welcome to my blog!");
  });

  it("sun method should execute", function() {
    let component = new AppComponent();
    let val1 = 10;
    let val2 = 20;
    let result = 30;
    spyOn(component, 'sum');
    expect(component.sum(10, 20)).toEqual(result);
  });

});

To execute the test cases, you need to run the below command from your command prompt (cmd) from the root folder of your angular application.

ng test

This command shall give you status of success/failure of your Karma test cases. There are few flags you may add to this command.

ng test --code-coverage
ng test --watch=true

These are used to generate code coverage report and recompile the build if any file changes, respectively. Apart from these, there are few more flags that can be passed to include/exclude any specific spec file or to run test cases for a specific folder or project.

To cover all these possible values, you may either go to official website of Angular Karma Test Cases or explore our upcoming blogs & learn all the how to & tips to fix common issues in Angular Karma Test Cases.

Share this blog on:

Deepak Jain, Full-stack Developer, Blogger and Tech Consultant

About Author

Deepak Jain is an experienced professional full-stack developer, UI/UX designer, ex-startup entrepreneur, passionately writes blog on technology, startups, business ideas. He also shares his own life experiences and creates awesome inspiring stories from the lives of people. Check out full profile