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 behaviour-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 confidently write tests and ensure the quality of your applications. 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 behaviour-driven tests in a readable and expressive format. Jasmine's syntax is designed to be easy to read and understand, even for those who are 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 that are specific to Angular. 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 that are focused on behaviour rather than implementation details. This means that tests are less likely to break as the codebase evolves and changes over time. Additionally, Jasmine's syntax is designed to be easy to read and understand, even for those who are not familiar with the underlying code. This makes it easier for developers to collaborate on testing efforts and to communicate the intent and results of tests to non-technical stakeholders. Overall, Jasmine is a powerful and versatile testing framework that can help developers ensure the quality and reliability of their Angular applications.
Setting up Jasmine in Angular Project
Setting up Jasmine in an Angular project is a straightforward process that involves installing the Jasmine framework and configuring it 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
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()
);
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');
});
});
This code imports the necessary modules and components and then defines a test suite using the describe function. The beforeEach
function sets up the testing 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 behaviour 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 we can 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
This will create a new component called my-component
in your Angular project.
- Define the Method: In your
truncate-string.component.ts
file, add thetruncateString
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;
}
}
}
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
truncate-string.component.spec.ts
file, write the following test cases for thetruncateString
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');
});
});
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
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 thetoggleVisibility
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;
}
}
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 thetoggleVisibility
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);
});
});
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
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.
I hope you found this blog useful in getting started with Jasmine testing in Angular. Thank you for taking the time to read through this content. By following the steps outlined in this blog, you can start writing effective unit tests for your Angular application components using Jasmine. Happy testing!
Subscribe to my newsletter
Read articles from Ayush Agarwal directly inside your inbox. Subscribe to the newsletter, and don't miss out.
Written by
Ayush Agarwal
Ayush Agarwal
As a software developer and coding enthusiast, I am constantly learning and exploring the world of programming and technology. In my free time, you can find me diving into finance and expanding my knowledge in that field. Through my blog, I aim to share my insights and experiences as a developer with the rest of the tech community.