SlideShare a Scribd company logo
Unit Testing in
Angular(7/8/9)
Using Jasmine and
Karma Part-2
WWW.BACANCYTECHNOLOGY.COM
How to write test cases to check comparison
for the numbers
How to write test cases for EventEmitter
How to run a single test case
How to run a single spec file
How to skip a single test case
How to skip a single spec file
How to run the test cases in Firefox
Reference link
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 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:
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.
toBeLessThanOrEqual()
tobe greater than()
toBeGreaterThanOrEqual()
it('Value of toBeLessThanValue variable should be
less than 10.', () => {
expect(component.toBeLessThanValue).toBeLessT
han(10);
});
For your practice, you can use the below method
and write your own test cases.
1.
2.
3.
(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).toHaveBeenCalledWit
h(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).toHaveBeenCalledWit
h(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).toHaveBeenCalledWit
h(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/1DKluBomf8g6
srN76HSg3bu9v-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. We are a globally
renowned AngularJS development company,
offering top-of-the-line Angular development
services and also let you hire dedicated Angular
developers at your convenience.
Thank you

More Related Content

KEY
Unittesting JavaScript with Evidence
PPTX
Rspec 101
PPTX
Introduction to nsubstitute
PDF
Unit testing with PHPUnit - there's life outside of TDD
PPT
Advanced PHPUnit Testing
PPTX
Unit Testing Presentation
PPT
Unit Testing using PHPUnit
KEY
Test-driven Development for TYPO3
Unittesting JavaScript with Evidence
Rspec 101
Introduction to nsubstitute
Unit testing with PHPUnit - there's life outside of TDD
Advanced PHPUnit Testing
Unit Testing Presentation
Unit Testing using PHPUnit
Test-driven Development for TYPO3

What's hot (20)

KEY
Test-Driven Development for TYPO3
PPT
Phpunit testing
KEY
Test-Driven Development for TYPO3 @ T3CON12DE
PDF
Introduction to Unit Testing with PHPUnit
PPS
Introduction to php 5
PPTX
Exception
PDF
JUnit Kung Fu: Getting More Out of Your Unit Tests
PPTX
Qunit Java script Un
PDF
PHPUnit best practices presentation
RTF
AutoComplete
PPTX
Mutation Testing: Testing your tests
PDF
PhpUnit Best Practices
PDF
Introduction To Testing With Perl
PPTX
Pragmatic unittestingwithj unit
PPT
Composing method
PPT
Mocking Dependencies in PHPUnit
PPTX
Unit Testng with PHP Unit - A Step by Step Training
PPTX
PHPUnit: from zero to hero
PDF
Test your code like a pro - PHPUnit in practice
PDF
Be smart when testing your Akka code
Test-Driven Development for TYPO3
Phpunit testing
Test-Driven Development for TYPO3 @ T3CON12DE
Introduction to Unit Testing with PHPUnit
Introduction to php 5
Exception
JUnit Kung Fu: Getting More Out of Your Unit Tests
Qunit Java script Un
PHPUnit best practices presentation
AutoComplete
Mutation Testing: Testing your tests
PhpUnit Best Practices
Introduction To Testing With Perl
Pragmatic unittestingwithj unit
Composing method
Mocking Dependencies in PHPUnit
Unit Testng with PHP Unit - A Step by Step Training
PHPUnit: from zero to hero
Test your code like a pro - PHPUnit in practice
Be smart when testing your Akka code
Ad

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

PDF
Unit-testing and E2E testing in JS
PDF
We Are All Testers Now: The Testing Pyramid and Front-End Development
PDF
Unit Testing in Angular
PDF
Unit Testing Front End JavaScript
PDF
The three layers of testing
PDF
Angular Application Testing
PDF
An Introduction to the World of Testing for Front-End Developers
PDF
FITC Web Unleashed 2017 - Introduction to the World of Testing for Front-End ...
PDF
Describe's Full of It's
PDF
Unit Testing - The Whys, Whens and Hows
PPTX
L2624 labriola
PPTX
Javascript Testing with Jasmine 101
PDF
Intro to Unit Testing in AngularJS
PDF
Angularjs - Unit testing introduction
PDF
Angularjs Test Driven Development (TDD)
PDF
10 Techniques to writing easy yet stupidly thorough unit tests.pdf
PPTX
Tests in Javascript using Jasmine and Testacular
PPTX
Angular Unit Testing
PPTX
In search of JavaScript code quality: unit testing
PDF
Testacular
Unit-testing and E2E testing in JS
We Are All Testers Now: The Testing Pyramid and Front-End Development
Unit Testing in Angular
Unit Testing Front End JavaScript
The three layers of testing
Angular Application Testing
An Introduction to the World of Testing for Front-End Developers
FITC Web Unleashed 2017 - Introduction to the World of Testing for Front-End ...
Describe's Full of It's
Unit Testing - The Whys, Whens and Hows
L2624 labriola
Javascript Testing with Jasmine 101
Intro to Unit Testing in AngularJS
Angularjs - Unit testing introduction
Angularjs Test Driven Development (TDD)
10 Techniques to writing easy yet stupidly thorough unit tests.pdf
Tests in Javascript using Jasmine and Testacular
Angular Unit Testing
In search of JavaScript code quality: unit testing
Testacular
Ad

More from Katy Slemon (20)

PDF
React Alternatives Frameworks- Lightweight Javascript Libraries.pdf
PDF
Data Science Use Cases in Retail & Healthcare Industries.pdf
PDF
How Much Does It Cost To Hire Golang Developer.pdf
PDF
What’s New in Flutter 3.pdf
PDF
Why Use Ruby On Rails.pdf
PDF
How Much Does It Cost To Hire Full Stack Developer In 2022.pdf
PDF
How to Implement Middleware Pipeline in VueJS.pdf
PDF
How to Build Laravel Package Using Composer.pdf
PDF
Sure Shot Ways To Improve And Scale Your Node js Performance.pdf
PDF
How to Develop Slack Bot Using Golang.pdf
PDF
IoT Based Battery Management System in Electric Vehicles.pdf
PDF
Understanding Flexbox Layout in React Native.pdf
PDF
The Ultimate Guide to Laravel Performance Optimization in 2022.pdf
PDF
New Features in iOS 15 and Swift 5.5.pdf
PDF
How to Hire & Manage Dedicated Team For Your Next Product Development.pdf
PDF
Choose the Right Battery Management System for Lithium Ion Batteries.pdf
PDF
Flutter Performance Tuning Best Practices From the Pros.pdf
PDF
Angular Universal How to Build Angular SEO Friendly App.pdf
PDF
How to Set Up and Send Mails Using SendGrid in NodeJs App.pdf
PDF
Ruby On Rails Performance Tuning Guide.pdf
React Alternatives Frameworks- Lightweight Javascript Libraries.pdf
Data Science Use Cases in Retail & Healthcare Industries.pdf
How Much Does It Cost To Hire Golang Developer.pdf
What’s New in Flutter 3.pdf
Why Use Ruby On Rails.pdf
How Much Does It Cost To Hire Full Stack Developer In 2022.pdf
How to Implement Middleware Pipeline in VueJS.pdf
How to Build Laravel Package Using Composer.pdf
Sure Shot Ways To Improve And Scale Your Node js Performance.pdf
How to Develop Slack Bot Using Golang.pdf
IoT Based Battery Management System in Electric Vehicles.pdf
Understanding Flexbox Layout in React Native.pdf
The Ultimate Guide to Laravel Performance Optimization in 2022.pdf
New Features in iOS 15 and Swift 5.5.pdf
How to Hire & Manage Dedicated Team For Your Next Product Development.pdf
Choose the Right Battery Management System for Lithium Ion Batteries.pdf
Flutter Performance Tuning Best Practices From the Pros.pdf
Angular Universal How to Build Angular SEO Friendly App.pdf
How to Set Up and Send Mails Using SendGrid in NodeJs App.pdf
Ruby On Rails Performance Tuning Guide.pdf

Recently uploaded (20)

PDF
Optimiser vos workloads AI/ML sur Amazon EC2 et AWS Graviton
PDF
Architecting across the Boundaries of two Complex Domains - Healthcare & Tech...
PDF
Approach and Philosophy of On baking technology
PDF
Encapsulation theory and applications.pdf
PPTX
MYSQL Presentation for SQL database connectivity
PDF
7 ChatGPT Prompts to Help You Define Your Ideal Customer Profile.pdf
PDF
Machine learning based COVID-19 study performance prediction
PPTX
Big Data Technologies - Introduction.pptx
PDF
Advanced methodologies resolving dimensionality complications for autism neur...
PPTX
Machine Learning_overview_presentation.pptx
PPTX
sap open course for s4hana steps from ECC to s4
PDF
The Rise and Fall of 3GPP – Time for a Sabbatical?
PDF
Diabetes mellitus diagnosis method based random forest with bat algorithm
PDF
Unlocking AI with Model Context Protocol (MCP)
PDF
Network Security Unit 5.pdf for BCA BBA.
PPT
Teaching material agriculture food technology
PDF
Review of recent advances in non-invasive hemoglobin estimation
PDF
Dropbox Q2 2025 Financial Results & Investor Presentation
PPTX
Cloud computing and distributed systems.
PDF
Blue Purple Modern Animated Computer Science Presentation.pdf.pdf
Optimiser vos workloads AI/ML sur Amazon EC2 et AWS Graviton
Architecting across the Boundaries of two Complex Domains - Healthcare & Tech...
Approach and Philosophy of On baking technology
Encapsulation theory and applications.pdf
MYSQL Presentation for SQL database connectivity
7 ChatGPT Prompts to Help You Define Your Ideal Customer Profile.pdf
Machine learning based COVID-19 study performance prediction
Big Data Technologies - Introduction.pptx
Advanced methodologies resolving dimensionality complications for autism neur...
Machine Learning_overview_presentation.pptx
sap open course for s4hana steps from ECC to s4
The Rise and Fall of 3GPP – Time for a Sabbatical?
Diabetes mellitus diagnosis method based random forest with bat algorithm
Unlocking AI with Model Context Protocol (MCP)
Network Security Unit 5.pdf for BCA BBA.
Teaching material agriculture food technology
Review of recent advances in non-invasive hemoglobin estimation
Dropbox Q2 2025 Financial Results & Investor Presentation
Cloud computing and distributed systems.
Blue Purple Modern Animated Computer Science Presentation.pdf.pdf

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

  • 1. Unit Testing in Angular(7/8/9) Using Jasmine and Karma Part-2 WWW.BACANCYTECHNOLOGY.COM
  • 2. How to write test cases to check comparison for the numbers How to write test cases for EventEmitter How to run a single test case How to run a single spec file How to skip a single test case How to skip a single spec file How to run the test cases in Firefox Reference link 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 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: Let’s start with how to write the test cases for the different scenarios for the component.
  • 3. (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(); });
  • 4. 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'); });
  • 5. 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.
  • 6. 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.
  • 7. toBeLessThanOrEqual() tobe greater than() toBeGreaterThanOrEqual() it('Value of toBeLessThanValue variable should be less than 10.', () => { expect(component.toBeLessThanValue).toBeLessT han(10); }); For your practice, you can use the below method and write your own test cases. 1. 2. 3.
  • 8. (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.
  • 9. it('Should emit the value once emitToParent method calling.', () => { spyOn(component.data, 'emit'); component.emitToParent(); expect(component.data.emit).toHaveBeenCalledWit h(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.
  • 10. 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).toHaveBeenCalledWit h(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.
  • 11. (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(); }));
  • 12. (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).toHaveBeenCalledWit h(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.
  • 13. (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.
  • 14. (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.
  • 15. 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/1DKluBomf8g6 srN76HSg3bu9v-p_a520N/view?usp=sharing (8) Reference link Github: https://github.com/parthsardhara/Angular -Test-Cases
  • 16. 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. We are a globally renowned AngularJS development company, offering top-of-the-line Angular development services and also let you hire dedicated Angular developers at your convenience.