Bacancy Bacancy
  • Customers

      Fortune 500 Clients

      Verizon
      Verizon
      Franklin Templeton
      Franklin Templeton
      The Container Store
      The Container Store
      KPMG
      KPMG
      Academy Sports & Outdoors
      Academy Sports & Outdoors
      Shell
      Shell
      Bangkok Bank Ltd
      Bangkok Bank Ltd
      The Children's Place
      The Children's Place
      Edward Jones
      Edward Jones
      United Parcel Service
      United Parcel Service
      AdviceWorks
      AdviceWorks
      NatWest Markets
      NatWest Markets
      Bridgestone
      Bridgestone

      Technologies

      React JS VueJS Angular JS React Native Flutter Full Stack
      Ruby on Rails Node JS Golang AI & ML Data Science Java
      Python Salesforce DevOps Block Chain Mobile App Embedded & Hardware
      Explore All
      skype-icon

      Skype ID

      bacancy
      gmail-icon

      Email Us

      [email protected]
      call-yellow-icon

      USA

      +1 347 441 4161
      wp-icon

      Canada

      +1 416 907 6738
  • what we do

      Experience

      Digital Workplace Services Product Enhancement

      Insights

      AI & Automation Data Analytics

      Innovate

      Blockchain Software Engineering Services Internet of Things (IoT) Data Science Artificial Intelligence Machine Learning

      Accelerate

      Cloud - Bacancy Combalt Digital Process Automation Open Source Microsoft Dynamics Salesforce

      Assure

      Quality Assurance IT Staff Augmentation

      Embedded & Hardware

      Product Engineering Analog Design Services FPGA Engineering Service Wireless Design Embedded Software Design

      not list

      Hardware Engineering Power Engineering IoT Hardware
      skype-icon

      Skype ID

      bacancy
      gmail-icon

      Email Us

      [email protected]
      call-yellow-icon

      USA

      +1 347 441 4161
      wp-icon

      Canada

      +1 416 907 6738
  • who we work with

      Industries

      Banking Financial services & Insurance Startups Oil & Gas

      not list

      Healthcare Life Science Real Estate & Construction Logistics
      bacancy

      Let’s grow together Partner with us

      get quote
      skype-icon

      Skype ID

      bacancy
      gmail-icon

      Email Us

      [email protected]
      call-yellow-icon

      USA

      +1 347 441 4161
      wp-icon

      Canada

      +1 416 907 6738
  • about us

      Culture

      Agile Mindset Bacancy Values Bacancy Culture

      About Company

      About Us Leadership Team Awards & Recognition Infrastructure

      not list

      Customer Reviews Our Locations Partnership Media Coverage

      WE ARE

      GREAT PLACE TO WORK - CERTIFIEDTM

      Building and sustaining High-Trust, High-Performance CultureTM

      Bacancy Great Place to Work
      skype-icon

      Skype ID

      bacancy
      gmail-icon

      Email Us

      [email protected]
      call-yellow-icon

      USA

      +1 347 441 4161
      wp-icon

      Canada

      +1 416 907 6738
  • technology

      Front End

      Angular Reactjs Vue.js UI/UX

      Platforms

      MS Dynamics Salesforce

      Back End

      Ruby on Rails Node.js Golang Laravel .NET Java Python

      Mobile

      React Native Flutter Android iOS

      Cloud

      AWS DevOps

      QA

      Automation Testing Software Testing

      Embedded & Hardware

      Embedded
      bacancy

      World-class expertise,Delivered

      get quote
      Explore All
      skype-icon

      Skype ID

      bacancy
      gmail-icon

      Email Us

      [email protected]
      call-yellow-icon

      USA

      +1 347 441 4161
      wp-icon

      Canada

      +1 416 907 6738
  • PRODUCTS

      EV Products

      Battery Management System Motor Controller AC Charger Explore All

      not list

      CCS2 Controller DC Fast Charger AC Charge Controller
      bacancy

      Let’s grow together Partner with us

      get quote
      skype-icon

      Skype ID

      bacancy
      gmail-icon

      Email Us

      [email protected]
      call-yellow-icon

      USA

      +1 347 441 4161
      wp-icon

      Canada

      +1 416 907 6738
hire us

Bacancy

Bacancy represents the connected world, offering innovative and customer-centric information technology experiences, enabling Enterprises, Associates and the Society to Rise™.

12+

Countries where we have happy customers

1050+

Agile enabled employees

06

World wide offices

10+

Years of Experience

05

Agile Coaches

14

Certified Scrum Masters

1000+

Clients projects

1458

Happy customers

  • Customers
      Technologies
      • React JS
      • Angular JS
      • Vue JS
      • Node JS
      • AI & ML
      • Explore All
      Fortune 500 Clients
      • Verizon
      • The Container Store
      • KPMG
      • Academy Sports & Outdoors
      • Bangkok Bank Ltd
      • The Children's Place
      • Edward Jones
      • Franklin Templeton
      • AdviceWorks
      • NatWest Markets
      • Bridgestone
      • United Parcel Service
  • What we do
      Experience
      • Digital Workplace Services
      • Product Enhancement
      Insights
      • AI & Automation
      • Data Analytics
      Innovate
      • Blockchain
      • Software Engineering Services
      • Internet of Things (IoT)
      Accelerate
      • Cloud - Bacancy Combalt
      • Digital Process Automation
      • Open Source
      • Microsoft Dynamics
      • Salesforce
      • Service Experience Transformation
      Assure
      • Testing
      • Resource Augmentation
      Embedded & Hardware
      • Product Engineering
      • Analog Design Services
      • FPGA Engineering Service
      • Wireless Design
      • Embedded Software Design
      • Hardware Engineering
      • Power Engineering
      • IoT Hardware
      • AL/ML
  • who we work with
      Industries
      • Banking Financial services & Insurance
      • Startups
      • Oil & Gas
      • Healthcare Life Science
      • Real Estate & Construction
      • Logistics
  • About Us
      About Company
      • About Us
      • Leadership Team
      • Awards & Recognition
      • Infrastructure
      • Our Locations
      • Partnership
      Culture
      • Agile Mindset
      • Bacancy Values
      • Bacancy Culture
  • Technology
      Front End
      • Angular
      • Reactjs
      • Vue.js
      • UI/UX
      Platforms
      • MS Dynamics
      • Salesforce
      Back End
      • Ruby on Rails
      • Node.js
      • Golang
      • Laravel
      • .NET
      • Java
      • Python
      Mobile
      • React Native
      • Flutter
      • Android
      • iOS
      Cloud
      • AWS
      • DevOps
      QA
      • Automation Testing
      • Software Testing
      Embedded & Hardware
      • Embedded
      Explore All
  • Products
    • Battery Management System
    • Motor Controller
    • CCS2 Controller
    • AC Charger
    • DC Fast Charger
    • AC Charge Controller
    • Explore All
  • Careers
  • Work @ Bacancy
  • Blogs
  • Resources
  • Customer Reviews
  • Contact
  • Get Quote
Unit Testing in Angular Application

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

Parth Sardhara
Parth Sardhara Software Engineer
Last Updated on October 11, 2022
March 25, 2020 8 min read

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 : [email protected]

Your Success Is Guaranteed !

Related Articles

Angular with AWS Combination
Ritwik Verma
Vivek Chhatbar

January 23, 2023

AngularJS

All You Need To Know About Angular With AWS Combination

By : Ritwik Verma & Vivek Chhatbar

Quick Summary: Every business owner, whether small or large, explicitly wants what's best for their business. Considering this approach, one thing that is taking a...

15 Minute Read
Read More
New Features of Angular 15
Ritwik Verma

November 30, 2022

AngularJS

What’s New in Angular 15: Deep Dive into Latest Features of Angular 15

By : Ritwik Verma

Quick Summary: The latest version of the most demanded front-end framework, Angular, is here with its latest release Angular 15. This year the Angular Team...

6 Minute Read
Read More
Why use Angular
Paridhi Wadhwani

November 29, 2022

AngularJS

Why Use Angular in 2023? [For Entrepreneurs & Programmers]

By : Paridhi Wadhwani

Quick Summary: Angular has become the first choice of young entrepreneurs who want to modernize their business and make it approachable to the GenZ audience....

14 Minute Read
Read More

india India (HQ)

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

USA USA

601 Brickell Key Drive, Suite 700, Miami, Florida, 33131, USA

canada Canada

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

australia-flag Australia

351A Hampstead Rd, Northfield SA 5085

UAE UAE

1608 Clover Bay, Business Bay, Dubai, UAE. PO Box 62049

sweden Sweden

Junkergatan 4, 126 53 Hagersten


Great Place to Work

Get in Touch

call-yellow-icon

Contact Number

+1 347 441 4161

gmail-icon

Email Us

[email protected]


  • Bacancy Behance
  • Bacancy Uplabs
  • Bacancy Pinterest
  • Brochure
  • Quality Assurance
  • Resources
  • Tutorials
  • Customer Reviews
  • Privacy Policy
  • FAQs
  • Contact Us
  • Sitemap
  • Employee
bacancy google review 4.6
bacancy google review
bacancy glassdoor review 4.5
bacancy glassdoor review
bacancy clutch review 4.8
bacancy clutch review
bacancy goodfirms review 4.5
bacancy goodfirms review
X

Get Our Newsletter

Be The First To Get The Latest Updates And Tutorials.

Request A Free Consultation