Bacancy Bacancy
      • About Company
      • Resources

      About Company

      About Us Leadership Team Customer Reviews Awards & Recognition
      Infrastructure Our Locations Partnership

      Resources

      Press Room Blog Insights
      We are great place to work certified™

      Building and Sustaining High-Trust, High-Performance Culture

      Get Quote
    • Engagement Models

      Hiring Software Developers becomes easier with just a few clicks.

      Software Development Outsourcing

      End-to-end delivery of custom solutions aligned to your roadmap.

      Staff Augmentation

      Scale your in-house team with pre-vetted specialists on demand.

      Dedicated Teams

      Get dedicated engineers who work exclusively on your project.

      • Enterprise Services
      • IT Services
      • Data Analytics
      • Cloud Services
      • AI & ML
      • Platforms

      Enterprise Services

      Digital Transformation Business Process Automation Digital Product Engineering Enterprise App Development Custom Software Development

      IT Services

      Legacy App Modernization DevOps & SRE Full Stack Development AI Testing & QA Automation

      Data Analytics

      Data Visualization & Reporting Data Engineering & Pipelines Data Science & Predictive Analytics Business Intelligence

      Cloud Services

      Cloud Strategy & Consulting Cloud Migration & Modernization Multi Cloud Management

      AI & ML

      AI Development Agentic AI Generative AI Computer Vision Machine Learning & MLOps

      Platforms

      Salesforce SAP ServiceNow Microsoft Dynamics Snowflake
      High-quality, Cost-effective IT Outsourcing

      Schedule a free discovery session to explore your needs and find tailored solutions with no obligation.

      explore all services
    • Industries
      Healthcare Fintech Real Estate
      Logistics Education Retail & Ecommerce
      Let's Grow Together! Get Quote
      • Front End
      • Backend
      • Mobile
      • Databases
      • DevOps & Infra
      • AI & Data Stack
      • Vibe Coding

      Front End

      React.js Next.js Angular Vue.js TypeScript
      Your Very Own UI/UX Architects

      Experience smooth navigation and user-friendly designs with our front-end expertise.

      Hire Frontend Developer

      Backend

      Node.js Python Java Spring Boot Laravel .NET C# Golang FastAPI
      Server Solutions To Change Power Dynamics

      Transform your data into digital experiences with optimized coding standards.

      Hire Backend Developer

      Mobile

      iOS Android Flutter React Native
      Innovating Mobile-Friendly App Solutions

      Create dynamic mobile apps that make your brand stand out from the crowd.

      Hire Mobile App Developer

      Databases

      PostgreSQL MongoDB MySQL Redis Supabase
      Dedicated Talent With Skilled Approach

      Bring your digital visions to life with a hired resource at your convenience.

      Hire Dedicated Developer

      DevOps & Infra

      AWS Azure Google Cloud Docker Kubernetes Terraform
      Redefining Scalable Digital Infrastructures

      Make your data accessible worldwide at will, and leave the stress behind.

      Get Quote

      AI & Data Stack

      OpenAI LangChain LlamaIndex Apache Spark Airflow Tableau PowerBI Databricks
      Guiding Decisions With Data-Driven Insights

      Transition from your gut calls to actionable insights with our rich Data Science expertise.

      Get Quote

      Vibe Coding

      Base44 Claude Code Cursor Lovable Github Copilot
      Your AI-Native Development Team

      Skip the boilerplate. Our vibe coding experts use AI-first tools to go from prompt to product, fast.

      Hire Vibe Coding Developer
  • Case Studies
  • Contact Us
Find a Developer book a 30 min call
      • About Us
      • Leadership Team
      • Customer Reviews
      • Awards & Recognition
      • Infrastructure
      • Our Locations
      • Partnership
      • Press Room
      • Blog
      • Insights
      • Digital Transformation
      • Business Process Automation
      • Digital Product Engineering
      • Enterprise App Development
      • Custom Software Development
      • Legacy App Modernization
      • DevOps & SRE
      • Full Stack Development
      • AI Testing & QA Automation
      • Data Visualization & Reporting
      • Data Engineering & Pipelines
      • Data Science & Predictive Analytics
      • Business Intelligence
      • Cloud Strategy & Consulting
      • Cloud Migration & Modernization
      • Multi Cloud Management
      • AI Development
      • Agentic AI
      • Generative AI
      • Computer Vision
      • Machine Learning & MLOps
      • Salesforce
      • SAP
      • ServiceNow
      • Microsoft Dynamics
      • Snowflake
    • Healthcare
    • Fintech
    • Real Estate
    • Logistics
    • Education
    • Retail & Ecommerce
      • React.js
      • Next.js
      • Angular
      • Vue.js
      • TypeScript
      • Hire Frontend Developer
      • Node.js
      • Python
      • Java
      • Spring Boot
      • Laravel
      • .NET
      • C#
      • Golang
      • FastAPI
      • Hire Backend Developer
      • iOS
      • Android
      • Flutter
      • React Native
      • Hire Mobile App Developer
      • PostgreSQL
      • MongoDB
      • MySQL
      • Redis
      • Supabase
      • Hire Dedicated Developer
      • AWS
      • Azure
      • Google Cloud
      • Docker
      • Kubernetes
      • Terraform
      • Get Quote
      • OpenAI
      • LangChain
      • LlamaIndex
      • Apache Spark
      • Airflow
      • Tableau
      • PowerBI
      • Databricks
      • Get Quote
      • Base44
      • Claude Code
      • Cursor
      • Lovable
      • Github Copilot
      • Hire Vibe Coding Developer
  • Case Studies
  • Contact Us
  • Find a Developer
  • book a 30 min call
Unit Testing in Angular Application

Unit Testing in Angular Application Using Jasmine and Karma Part-1

Parth Sardhara
Parth Sardhara Engineering Manager
Last Updated on March 12, 2025 | Written By: Parth Sardhara

Hello guys, welcome again!

In my previous blog post, we discussed what are Angular HTTP interceptors and how to use them, and now I am back with another blog post, where we will discuss unit testing in Angular using Jasmine and karma.

In this blog, you will learn so many new things about the type of testing in Angular and how to write unit tests for different scenarios for your existing angular project. I am very excited to share my knowledge with you. So let’s get started.

Table Of Content

What is a test case in software testing?

Types of Testing

What are the testing tools and methods which are used for the unit test

Unit test fundamentals

Point for Implementation

Conclusion

What is a test case in software testing?

  • Tests are one of the best ways to prevent software defects
  • We write the test cases that the behavior of the code will work as per our expectations or not
  • Jasmine is a BDD framework for testing JavaScript code that performs well with Karma
  • What is Suite and specs in unit testing?
    • Suite is the collection of single test.
    • Spec is the only unit test

Types of Testing

  • Unit test
  • Integration test
  • End-to-end test

Unit Test

  • Test the component in isolation, without external resources (API endpoint, database)
  • Just create a fake response or instance and just write the test case base on that.

Benefits of writing the Unit test

  • Easier to write
  • Super-fast
  • Give us much confidence for the functionality

Integration test

  • Test the component with external resources, API endpoint also with access database.

Benefit of writing the integration testing

  • Easier to write
  • Super-fast
  • Give us much confidence for the functionality

End-to-end testing

  • Test the component with external resources, API endpoint also with access database.
  • Protractor Testing Tool is used for end-to-end testing especially for AngularJS apps

Benefits of writing end-to-end testing:

  • We can test all the component or project
  • Best practice for testing for all the functionality of the project
  • Give us much more confidence for the product testing

What are the Testing tools (Test runners) or methods used to write and run the test cases?

(1) Jasmine

(2) Karma

(3) Protractor

What is the use of Jasmine in Angular?

  • Jasmine is a JavaScript testing framework.
  • Jasmine lets you run on any JS enabled platform and make it easy-to-read syntax.

Testing Angular with Karma

  • Karma is a test runner for JS that runs on Node.js. It is very well suited to testing AngularJS or any other JavaScript projects for testing purposes.
  • Karma is created by the AngularJS team to test their own framework features with existing tools. As a result of this, now Karma is transitioned to Angular as the default test runner with the Angular CLI.

What is the Protractor testing tool?

Protractor is an automation testing tool for end-to-end Angular and AngularJS web applications. It is a combination of powerful technologies like Selenium Web driver, Jasmine, Node.js, etc.

Unit Testing Fundamentals:-

Clean coding practice

  • Small function/ methods (10 to 15 line of code)
  • Proper naming for the test case (Test case which testing for what )
  • Single responsibility

Point for Implementation:-

In Angular, we have a .spec file for component, service, pipe, and for others also and every .spec file has 1 method called Describe.

Describe has many single tests we can write and run for that component, service, pipe, etc.

So Describe => is a Group of test cases. Also called a Suite and
It(‘should create) => Single test case, Also called a Spec.

Before we jump into writing the unit test, let me explain what we have inside the spec file for the component.

Basically, when we create a new project, angular by default, it gives some unit test in app.component.spec.ts file, which is something like the image below.

app.component.spec.ts file

So as per the above image, it has 1 method called describe and inside describe, it has 3 single test write with it() method.

Basically, we write the test cases based on the component Html file and typescript file, so we should have access to that variable as well as the div.

For in terms of access to the typescript file of variable or method, we need to create a component and their accessibility using the below lines of code, as shown in the first unit test.

   const fixture = TestBed.createComponent(AppComponent);
   const app = fixture.debugElement.componentInstance;

Here, TestBed provides the testing environment to write the test cases, and here we have an app that will give access to the typescript file of that component.

Like if we have a title in TS file like,

title = 'Unit testing';

Then we can access the title variable using the app.title where we are able to write the unit test for that variable.

So if we want to access the component HTML file of any element, then we need to write the below line of the code.

 const fixture = TestBed.createComponent(AppComponent);
   fixture.detectChanges();
   const compiled = fixture.debugElement.nativeElement;

Here, TestBed provides the testing environment to write the test cases, and here we have a compiled that offers access to the element of that component HTML file.

Like if we have a div in html file like,

< h1 >{{title}} app is running!< /h1 >

Then we can write the test cases like below first need to select that h1 then we need to test it.

 expect(compiled.querySelector('h1').textContent).toContain('Unit testing app is running!');

To run the test cases, you need to go to the terminal and need to enter the command, which is ng test.

This will automatically open the chrome browser with karma and will look like the image below.

karma connected

So in terms of writing the test cases, I have created a home component using the command line: go to terminal and enter the command ng g c home, which will create 4 files.

In the home.component.spec.ts file, I already define the variable and some method for testing, please copy past it, and then we will move to write the test cases for that.

home.component.spec.ts file

Now, let’s start to write the test cases for the different scenarios for the component.

1. How to check the value of variable state value is ‘state value’.

it('Variable stateValue should be state value', () => {
   expect(component.stateValue).toBe('state value');
 });

2. How to check the value of variable state value should not be other than state value.

 it('Variable stateValue should not be other than state value', () => {
   expect(component.stateValue).not.toBe('hello1');
 });

3. How to check the variable state value should start with ‘state.’

 it('stateValue variable should start with state', () => {
   const mockState = 'state';
   expect(component.stateValue).toMatch(mockState);
 });

4. How to call the method and match with the result of that method?

Let’s say we have a method in TS file like.

name(name) {
   return 'Welcome ' + name + '!';
 }

So if we pass the name, then we will get the result based on that return statement.

 it('name method should return as per the parameter passed', () => {
   const name = component.name('parth');
   expect(name).toBe('Welcome parth!');
 });

5. How to check the value of the array?

Let’s say we have a method in TS file, which is ArrayList and which will return an array.

ArrayList() {
   return ['first name', 'last name', 'middle name'];
 }

So we can use the container method for that to check array contain the value or not.

it("ArrayList should contain 'first name'.", () => {
   const name = component.arrayList();
   expect(name).toContain('first name');
 });

6. How to write the test cases for the scenario like Variable value should be changed if a particular method is called.

Here we called the method ngOnInit, and then the value of the welcome is changed to ‘a.’

ngOnInit() {
   this.welcome = this.isLoggedIn;
 }

For that first, we need to call the method; then, we need to compare it something like as shown in the below image.

 it('value of the welcome variable should be a once ngOnInit method have been called', () => {
   component.ngOnInit();
   expect(component.welcome).toContain(component.isLoggedIn);
 });

7. If the array has only value, then how to check if the array is the same or not?

Like we have an array isLoggedInArray having 1 string value a.

 public isLoggedInArrary = ['a'];

So for that, we will use the toEqual method and will check that array has ‘a’ or not, which is something like,

 it('should have only 1 value which is a  in isLoggedInArrary', () => {
   const isLoggedInArrary = component.isLoggedInArrary;
   expect(isLoggedInArrary).toEqual(['a']);
 });

8. How to check that 2 objects are the same or not in terms of key and value?

Let’s say we have two objects named Object1 and Object2 whose values are the same.

public Object1 = {
   bath: true,
   bedrooms: 4,
   kitchen: {
     amenities: ['oven', 'stove', 'washer'],
     area: 20,
     wallColor: 'white',
   },
 };
 
public Object2 = {
   bath: true,
   bedrooms: 4,
   kitchen: {
     amenities: ['oven', 'stove', 'washer'],
     area: 20,
     wallColor: 'white',
   },
 };

In terms of comparing the 2 same objects, we need to use the toEqual method the same as shown in the below image to check both the objects are equal or not.

 it('Object1 and Object2 should have the equal value.', () => {
   expect(component.Object1).toEqual(component.Object2);
 });

9. How to check the variable is null or not?

 public stateValueNull: string = null;
 it('stateValueNull should be null initially.', () => {
   expect(component.stateValueNull).toBeNull();
 });

10. How to check the variable is undefined or not?

public stateValueUndefine;
 it('stateValueUndefine should be null initially undefined', () => {
   expect(component.stateValueUndefine).toBeUndefined();
 });

How to Run the Test Cases and Validate It is a Failure or Successful?

https://drive.google.com/file/d/1Y1QklM5oEg8eMJpBNqfzjdXLmANqOxFc/view

Conclusion

So, this is part 1 of unit testing in Angular. I hope you have enjoyed reading this blog post. In case if you are looking for unit testing specialists, to make your Angular app more secure, then hire Angular developer from us to leverage our top-of-the-line expertise. Apart from that, we also offer Angular upgrade service to migrate or upgrade your existing Angular application to the latest version of Angular Ivy.

Soon I will be back with part 2 of unit testing, where we will discuss how to write the test cases for the service, pipe, input, output, and many more. I will also discuss how to run the test cases in Firefox instead of the default Chrome browser for Unit tests.


Expand Your Digital Horizons With Us.

Start a new project or take an existing one to the next level. Get in touch to start small, scale-up, and go Agile.


Or
E-mail us : solutions@bacancy.com

Your Success Is Guaranteed !

Related Articles

Dipal Bhavsar

November 21, 2025

AngularJS

Angular 21: Latest Features, Updates & Advancements

By : Dipal Bhavsar

Read More
Dipal Bhavsar

November 3, 2025

AngularJS

7 Easiest Ways to Use AI in Angular

By : Dipal Bhavsar

Read More
Dipal Bhavsar

July 17, 2025

Application Development

Application Modernization Strategy: A Complete Roadmap for Legacy Transformation

By : Dipal Bhavsar

Application modernization strategies help businesses update legacy systems to meet demanding performance, scalability, and integration needs. They include approaches such...

Read More

Offices and Development Centers

Bacancy Ahmedabad Ahmedabad

15-16, Times Corporate Park, Thaltej, Ahmedabad, 380059

Bacancy Gandhinagar Gandhinagar

422-A, 4th Floor, Pragya Tower Road 11, Block 15, Zone 1, SEZ-PA Gandhinagar, 382355

Bacancy Hyderabad Hyderabad

Awfis, Level 1, N Heights, Plot No 38, Phase 2, Hitech City Hyderabad, 500081

Bacancy Mumbai Mumbai

18th Floor, Cyberone, opp. CIDCO Exhibition Centre, Sector 30, Vashi, Navi Mumbai, 400703

Bacancy Pune Pune

2nd FloorMarisoft-1, Marigold IT Park, Pune - 411014

Bacancy Bengaluru Bengaluru

Raheja Towers, 26/27, Mahatma Gandhi Rd, East Wing, Craig Park Layout, Ashok Nagar, Bengaluru, 560001

Global Presence

Bacancy New Jersey New Jersey

33 South Wood Ave, Suite 600, Iselin NJ 08830

Bacancy California California

535 Mission St 14th floor, San Francisco, CA 94105

Bacancy Massachusetts Massachusetts

501 Boylston St, Boston, MA 02116

Bacancy Florida Florida

4995 NW, 72nd Avenue, Suite 307, Miami, FL, 33166

Bacancy London London

90 York Wy, London N1 9AG, United Kingdom

Bacancy Ontario Ontario

71 Dawes Road, Brampton, On L6X 5N9, Toronto

Bacancy Australia Australia

351A Hampstead Rd, Northfield SA 5085

Bacancy UAE UAE

One Central 8th and 9th Floor - Trade Centre - Trade Centre 2 - Dubai - United Arab Emirates

Bacancy Sweden Sweden

Junkergatan 4, 126 53 Hagersten

Get in Touch

Great Place to Work

Get in Touch

cal-icon

Looking for expert advice?

Schedule a Expert Call


  • Brochure
  • Quality Assurance
  • Resources
  • Tutorials
  • Customer Reviews
  • Privacy Policy
  • FAQs
  • Press Room
  • Contact Us
  • Sitemap
  • Employee

bacancy google review 4.6
bacancy google review
bacancy clutch review 4.8
bacancy clutch review
bacancy goodfirms review 4.8
bacancy goodfirms review
iso
  • Bacancy Behance
  • Bacancy Pinterest

Copyright © 2026 BACANCY SERVICES PRIVATE LIMITED All rights reserved.