DEV Community

Cover image for Getting Started with Jasmine Testing in Angular: A Beginner's Guide
Ayush Agarwal
Ayush Agarwal

Posted on • Edited on • Originally published at blogs.ayushdev.com

Getting Started with Jasmine Testing in Angular: A Beginner's Guide

As developers, we all know the importance of testing our code. It's a critical part of the software development process that ensures the functionality and quality of our applications. However, writing tests can often be a daunting task, especially for those new to the testing world.

Fortunately, Angular provides a powerful testing framework that makes writing tests easier and more efficient: Jasmine. Jasmine is a popular testing framework that allows developers to write behavior-driven tests in a readable and expressive format. It integrates seamlessly with Angular, providing a simple and effective way to test components, services, pipes, and directives.

In this blog post, we will cover the basics of Jasmine, including how to set it up in an Angular project and write small tests to get a basic understanding.

If you're new to Angular testing, this blog will provide you with the knowledge and tools you need to write tests and ensure the quality of your applications confidently. So let's dive in and get started with Jasmine testing in Angular!

Introduction to Jasmine

Jasmine is a popular testing framework that has gained widespread adoption in the Angular community. It provides a simple and intuitive way to write behavior-driven tests in a readable and expressive format. Jasmine's syntax is designed to be easy to read and understand, even for those new to testing. It uses descriptive language to define test cases and expectations, making it easy to understand what each test is checking.

Jasmine is particularly well-suited for testing Angular applications, as it integrates seamlessly with Angular's dependency injection system and provides several built-in matchers and assertion functions specific to it. These features make it easy to write tests that test specific aspects of an Angular application, such as components, services, pipes, and directives.

One of the key benefits of Jasmine is that it allows developers to write tests focused on behaviour rather than implementation details. This means that tests are less likely to break as the codebase evolves and changes over time. Jasmine's syntax is also designed to be easy to read and understand, even for those unfamiliar with the underlying code. This makes it easier for developers to collaborate on testing efforts and communicate the test's intent and results to non-technical stakeholders.

Setting up Jasmine in Angular Project

Setting up Jasmine in an Angular project is a straightforward process involving installing and configuring the Jasmine framework to work with your Angular application.

Here are the steps you'll need to follow to set up Jasmine in your Angular project:

  • Install Jasmine: The first step is to install the Jasmine framework in your project. You can do this by running the following command in your project directory.
npm install jasmine --save-dev
Enter fullscreen mode Exit fullscreen mode

This will install Jasmine as a development dependency in your project.

  • Configure Jasmine: Once you've installed Jasmine, you'll need to configure it to work with your Angular application. The easiest way to do this is to create a new test.ts file in your project's src directory. This file should include the following code:
import 'zone.js/dist/zone-testing';
import { getTestBed } from '@angular/core/testing';
import { BrowserDynamicTestingModule, platformBrowserDynamicTesting } from '@angular/platform-browser-dynamic/testing';

getTestBed().initTestEnvironment(
  BrowserDynamicTestingModule,
  platformBrowserDynamicTesting()
);

Enter fullscreen mode Exit fullscreen mode

This code initializes the Angular testing environment and configures it to use the dynamic browser testing module.

  • Write Your First Test: With Jasmine and your test environment set up, you're ready to write your first test. Create a new file in your project's src directory with a .spec.ts extension (e.g., app.component.spec.ts) and include your test code using Jasmine's syntax.
import { TestBed } from '@angular/core/testing';
import { AppComponent } from './app.component';

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

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

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

Enter fullscreen mode Exit fullscreen mode

This code imports the necessary modules and components and defines a test suite using the describe function. The beforeEach function configures the test environment by configuring the TestBed with the necessary components and services. The it functions define the individual test cases and use Jasmine's matchers to check whether the expected behavior is met.

With these steps completed, you should now have Jasmine set up and ready to use in your Angular project. From here, you can write tests for all of your Angular components, services, pipes, and directives to ensure the quality and reliability of your application.

In the next section, we will learn how to write Jasmine test cases for methods or functions in our Angular application.

Writing Jasmine Test Cases for Angular Methods: A Step-by-Step Guide

In this section, we'll walk through the process of writing Jasmine test cases for two simple methods. These methods include a function that truncates a string and a function that toggles a boolean value. By following along with these examples, you'll gain a solid understanding of how to write effective and efficient tests for the methods in your Angular applications.

Method 1 - Truncate a String

  • Create the Component: First, create a new Angular component by running the following command in your terminal:
ng generate component truncate-string
Enter fullscreen mode Exit fullscreen mode

This will create a new component called my-component in your Angular project.

  • Define the Method: In your truncate-string.component.ts file, add the truncateString method to the component class using the code below:
import { Component, OnInit } from '@angular/core';

@Component({
  selector: 'app-truncate-string',
  templateUrl: './truncate-string.component.html',
  styleUrls: ['./truncate-string.component.scss']
})
export class TruncateStringComponent implements OnInit {

  constructor() { }

  ngOnInit(): void {
  }

  longDescription = 'Lorem Ipsum is simply dummy text of the printing and typesetting industry. Lorem Ipsum has been the industry standard dummy text ever since the 1500s, when an unknown printer took a galley of type and scrambled it to make a type specimen book.';
  truncatedString: string;

  public truncateString (){
    if(this.longDescription.length>50){
      this.truncatedString = this.longDescription.slice(0,50);
    }
    else{
      this.truncatedString = this.longDescription;
    }
  }

}
Enter fullscreen mode Exit fullscreen mode

This method takes the longDescription string and checks if it's longer than 50 characters. If it is, it truncates the string to the first 50 characters using the slice method and assigns it to the truncatedString property. If not, it assigns the entire longDescription string to truncatedString.

  • Write the Test Cases: In your my-component.component.spec.ts file, write the following test cases for the truncateString method:
import { ComponentFixture, TestBed } from '@angular/core/testing';

import { TruncateStringComponent } from './truncate-string.component';

describe('TruncateStringComponent', () => {
  let component: TruncateStringComponent;
  let fixture: ComponentFixture<TruncateStringComponent>;

  beforeEach(async () => {
    await TestBed.configureTestingModule({
      declarations: [ TruncateStringComponent ]
    })
    .compileComponents();
  });

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

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

  it('should truncate long description to 50 characters', () => {
    component.longDescription = 'Lorem Ipsum is simply dummy text of the printing and typesetting industry. Lorem Ipsum has been the industry standard dummy text ever since the 1500s.';
    component.truncateString();
    expect(component.truncatedString).toEqual('Lorem Ipsum is simply dummy text of the printing and typesetting industry. L');
  });

  it('should not truncate short description', () => {
    component.longDescription = 'Short Description';
    component.truncateString();
    expect(component.truncatedString).toEqual('Short Description');
  });
});

Enter fullscreen mode Exit fullscreen mode

The first it block tests whether the truncateString method correctly truncates the longDescription string to 50 characters. The second it block tests whether the method leaves short strings unchanged.

  • Run the Test Cases: Run the test cases using the following command in your terminal:
ng test
Enter fullscreen mode Exit fullscreen mode

Method 2 - Toggle a boolean

Similar to as discussed above create a component boolean-test using terminal. Then:

  • Write the Method: In your boolean-test.component.ts file, add the toggleVisibility method to the component class, using the code provided:
import { Component, OnInit } from '@angular/core';

@Component({
  selector: 'app-boolean-test',
  templateUrl: './boolean-test.component.html',
  styleUrls: ['./boolean-test.component.scss']
})
export class BooleanTestComponent implements OnInit {

  constructor() { }

  ngOnInit(): void {
  }
  isVisible = true;

  toggleVisibility() {
    this.isVisible = !this.isVisible;
  }

}
Enter fullscreen mode Exit fullscreen mode

This method simply toggles the value of the isVisible property between true and false when it is called.

  • Write the Test Cases: In your boolean-test.component.spec.ts file, write the following test cases for the toggleVisibility method:
import { ComponentFixture, TestBed } from '@angular/core/testing';

import { BooleanTestComponent } from './boolean-test.component';

describe('BooleanTestComponent', () => {
  let component: BooleanTestComponent;
  let fixture: ComponentFixture<BooleanTestComponent>;

  beforeEach(async () => {
    await TestBed.configureTestingModule({
      declarations: [ BooleanTestComponent ]
    })
    .compileComponents();
  });

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

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

  it('should toggle the value of isVisible', () => {
    component.toggleVisibility();
    expect(component.isVisible).toEqual(false);
    component.toggleVisibility();
    expect(component.isVisible).toEqual(true);
    });
});
Enter fullscreen mode Exit fullscreen mode

The it block tests whether the toggleVisibility method correctly toggles the isVisible property when called.

  • Run the Test Cases: Run the test cases using the following command in your terminal:
ng test
Enter fullscreen mode Exit fullscreen mode

This should execute the tests and display the results in your terminal. If the tests pass, you can be confident that your toggleVisibility method is working as intended.

In this section, we covered two basic methods in Angular components and learned how to write test cases for them using Jasmine. By following these steps, you can ensure that your methods are functioning properly and maintain the quality of your Angular project.

Conclusion

Unit testing is a crucial aspect of software development that allows developers to catch errors and bugs early in the development cycle. By using Jasmine in Angular, developers can create and execute test cases that thoroughly examine the behaviour of their application components. By prioritizing unit testing with Jasmine, developers can create reliable and robust Angular applications that provide an exceptional user experience.

Lastly, Your support keeps me going, and I give my 100 percent to these blogs! If you've found value, consider fueling the blog with a coffee ☕️ donation at the below link.

Buy me a COFFEE!

Thank you! 🙏

Top comments (0)