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 developers

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 2

Unit Testing in Angular(7/8/9) Using Jasmine and Karma Part-2

Parth Sardhara
Parth Sardhara Software Engineer
Last Updated on August 26, 2022
May 8, 2020 6 min read

Welcome to the second installment of unit testing in Angular application. In this blog, you will learn the remaining things about unit testing in Angular application and how to write unit tests for different scenarios.

Before we start unit tests if you have missed the part-1, then you can check it here.

So, let’s get started.

Table of Contents to be covered:

  1. How to write test cases to check comparison for the numbers
  2. How to write test cases for EventEmitter
  3. How to run a single test case
  4. How to run a single spec file
  5. How to skip a single test case
  6. How to skip a single spec file
  7. How to run the test cases in Firefox
  8. Reference link

Let’s start with how to write the test cases for the different scenarios for the component.

(1) How to Write Test Cases to Check Comparison for the Numbers.

1. How to check if the value of a variable is a number or not?

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

public toBeNaN = 0 / 0;

If you want to check that toBeNaN should not be a number, then first, you need to access in the spec file, and then you need to use the method which is provided by jasmine.

 it('toBeNaN variable should not be a number.', () => {
   var toBeNaNValue = component.toBeNaN;
   expect(toBeNaNValue).toBeNaN();
 });

The above test cases will check the value of the toBeNaN variable should not be a number, and if the value is not a number, then it will run successfully, or else the above test case will be false.

2. How to check that array contains the desired value or not.

Let’s say we have a method in a TS file that returns an array with some value.

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

In order to check whether the array contains the first name or not, then we can check something like,

 it("Should contain 'first name' in an array which return by ArrayList method.", () => {
   const name = component.arrayList();
   expect(name).toContain('first name');
 });

So as per the above test case code first, it will call the ArrayList method and store the value in name const, and then it will check that name contain ‘first name’ or not if it has then test case will be a success and if not then it will be a failure.

3. How to check that array value should be equal.

Let’s tale the above example, and in that, we return the value in an array something like: [‘first name,’ ‘last name,’ ‘middle name’];

Then if we want to check that the return array should be the same or equal to the above array value, then we need to write the test case something like.

it("arrayList method return array value Should equal to mockArray value.", () => {
   const name = component.arrayList();
   const mockArray = ['first name','last name', 'middle name'];
   expect(name).toEqual(mockArray);
 });

Note: – The above solution will match the same array with value on a particular index as well.

4. How to check that variable value is less than or not.

Let’s say we have a variable in TS file, and if we want to check that, it should be less than 10.

public toBeLessThanValue: number = 1.5;

 it('Value of toBeLessThanValue variable should be less than 10.', () => {
   const percent = component.toBeLessThanValue;
   expect(percent).toBeLessThan(10);
 });

So in order to check that the value of the variable should be less than 10, we need to use the toBeLessThan method, which is provided by jasmine.

Note:- We can also simplify the above solution as I first store the value of the variable is a constant, instead of that, we can directly use that variable, something like the solution below.

it('Value of toBeLessThanValue variable should be less than 10.', () => {
   expect(component.toBeLessThanValue).toBeLessThan(10);
 });

For your practice, you can use the below method and write your own test cases.

  1. toBeLessThanOrEqual()
  2. tobe greater than()
  3. toBeGreaterThanOrEqual()

Looking for experts with the necessary skills to create front-end applications that are secure, scalable, and trustworthy?
Get in touch with us to hire Angular developer to create user-friendly applications beyond your expectations.

(2) How to write test cases for event emitter.

1. How to write test cases for EventEmitter.

Let’s say we have an EventEmitter in the TS file, and also we have a method emitToParent, and while calling this method, it should emit the value ‘true.’

So step 1, we should have an @output EventEmitter variable, and we should have a method for emitting the value. Here we have the emitToParent method.

@Output() data = new EventEmitter();
 emitToParent() {
   this.data.emit(true);
 }

So to write test cases for Event Emitter, we need to write case something like below.

it('Should emit the value once emitToParent method calling.', () => {
   spyOn(component.data, 'emit');
   component.emitToParent();
   expect(component.data.emit).toHaveBeenCalledWith(true);
 });

So using the toHaveBeenCalledWIth method, we can check that emit is successful or not.

(3) How to run a single test case.

If we want to run a single test case, then we need to add ‘f’ as a prefix in that test cases so it will become fit something like.

it('should not be null isLoggedInArrary', () => {
   const isLoggedInArrary = component.isLoggedInArrary;
   expect(isLoggedInArrary).toEqual(['a']);
 });
 
 fit('close should emit the value once emitToParent method calling.', () => {
   spyOn(component.data, 'emit');
   component.emitToParent();
   expect(component.data.emit).toHaveBeenCalledWith(true);
 });

In the above case, it will only run the second test case as we provided f as a prefix to that test case no matter if other test cases are gonna be a success or fail.

(4) How to run a single spec file.

If we want to run a single test spec file, then we need to add ‘f’ as a prefix in that spec file describe method so it will become fdescribe something like…

fdescribe('HomeComponent', () => {
 let component: HomeComponent;
 let fixture: ComponentFixture;
 
 beforeEach(async(() => {
   TestBed.configureTestingModule({
     declarations: [HomeComponent]
   })
     .compileComponents();
 }));

(5) How to skip a single test case

If we want to skip a single test case, then we need to add ‘X’ as a prefix in that test cases so it will become fit something like,

 it('should not be null isLoggedInArrary', () => {
   const isLoggedInArrary = component.isLoggedInArrary;
   expect(isLoggedInArrary).toEqual(['a']);
 });
 
 xit('close should emit the value once emitToParent method calling.', () => {
   spyOn(component.data, 'emit');
   component.emitToParent();
   expect(component.data.emit).toHaveBeenCalledWith(true);
 });

In the above case, it will only skip the second test case as we provided X as a prefix to that test case no matter if that test case is gonna be a success or fail.

(6) How to skip a single spec file.

If we want to skip a single test spec file, then we need to add ‘X’ as a prefix in that spec file describe method so it will become xdescribe something like.

xdescribe('HomeComponent', () => {
 let component: HomeComponent;
 let fixture: ComponentFixture;
 
 beforeEach(async(() => {
   TestBed.configureTestingModule({
     declarations: [HomeComponent]
   })
     .compileComponents();
 }));

So in the above case, xdescribe will not run the test case; it will run another spec file.

(7) How to run the test cases in Firefox.

So as we learn in Test cases in Angular part-1, while we run the test cases in Angular using ng test, then it will automatically open the chrome browser, but what if we want to run the test cases in Firefox.

That is also possible to run the test cases in Firefox, and for that first, you should have Firefox on your laptop or desktop. Then you need to install one package and need to set the configuration to run the test cases in Firefox.

Step 1: install node package karma-firefox-launcher using the terminal by below command

Command: npm install karma-firefox-launcher –save-dev

"karma-firefox-launcher": "^1.2.0",

Step 2: Then go to the karma.conf.js file and add plugins like using the below line after require(‘karma-chrome-launcher’), line.

require('karma-firefox-launcher'),

Step 3: Then add Firefox in browsers array something like below.

browsers: ['Chrome', 'Firefox'],

Step 4: Run the test case using the ng test, and it will open both the browser as shown in the below video.

Firefox Test case: https://drive.google.com/file/d/1DKluBomf8g6srN76HSg3bu9v-p_a520N/view?usp=sharing

(8) Reference link

Github: https://github.com/parthsardhara/Angular-Test-Cases

Wrapping Up:

I hope your purpose of landing on this blog post has been served. But, in case if you are looking for skilled Angular developers who can help you build experiences that deliver results, then get in touch with us today to hire angularJS developers monthly and hourly from the top-notch Angular development company, and you’re all set for Angular app development.


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

MotionLayout in Android
Ritwik Verma
Mansi Kothari

March 28, 2023

Application Development

A Detailed Tutorial On How To Use MotionLayout In Android

By : Ritwik Verma & Mansi Kothari

Quick Summary In the world of Android development, a vast array of widgets and libraries are available that you can use to create breathtaking animations...

7 Minute Read
Read More
angular micro frontends
Ritwik Verma
Harsh Koralwala

March 3, 2023

AngularJS

Everything You Need to Know About The Angular Micro Frontends Architecture

By : Ritwik Verma & Harsh Koralwala

Quick Summary: Technology surrounds us at every step of our traditional lifestyle. These technological surroundings evolve as time passes by. Every day a new technological...

12 Minute Read
Read More
Angular eCommerce
Ritwik Verma
Vivek Chhatbar

February 15, 2023

AngularJS

Why Angular eCommerce is perfect for Web App Development?

By : Ritwik Verma & Vivek Chhatbar

Quick Summary: Business owners strive to offer the best to their customers. The demand for Commerce portals has significantly increased as the market thrives. To...

9 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

book a 30 min call popup

Before You Go...

Try our free consultation to visualize the best outcome of your business ideas.

INSTANT 30 MIN FREE CONSULTATION CALL