Web Analytics
  • Culture
      Back
      Agile Mindset

      Agile is not a principal or a method, but it’s an integral part of being Agile that is guided by principles, defined by values and manifested through various practices.

      Bacancy Values

      You add value to your customer when you deliver a product or service that has been designed specifically to solve their problem.

      Bacancy Culture

      Core Team will work as Scrum Team where Team will have quarterly goal to make sure that we run financial, administrative and project management prospective.

  • What we do
      Back
      Product Engineering

      Seize the opportunity to make your product stand out. We enable our clients

      AI & ML

      We automate businesses and optimize processes by deploying smart AI and...

      Blockchain

      Get a full spectrum of blockchain development services from us to bring scalability...

      IOT

      Improve Business Productivity and Efficiency using our high-end IOT professional services...

      Digital Transformation

      We truly become a part of your business by helping you think through the...

  • Who we work with
      Back
      Real Estate

      We can help you uncover the hidden revenue opportunities to showcase your...

      Finance & Insurance

      In the emerging technological environment, we are offering reliable banking and financial...

      Oil & Gas

      Reshape your energy landscape and gain better control by harnessing the best...

      Healthcare

      Utilizing advanced technologies to provide best software, web & mobile development services...

      Travel & Transport

      Manage your logistics and transportation business at the ease of your fingertips...

      Startups

      We can help you to build your MVP with advanced technologies....

  • About Us
      Back
      About

      Agile, A Process Delivering Values & Successful Products

      Blog

      Abstract Technology News Driven by Sources

      Career

      If you are passionate about your career, have creative flair and good craft skills, we want you!

  • Technology
      Back

      Front-End

      AngularJS ReactJS Vue.JS JavaScript Backbone.JS Ember.JS MEAN MERN

      Back-End

      Ruby on Rails Node.JS Golang Laravel PHP Python .NET Yii

      Mobile

      Android iOS React Native Flutter Ionic Kotlin

      CMS & CRM

      Spree Magento Wordpress Drupal Umbraco Woocommerce Salesforce Microsoft Dynamics 365<
      Explore All
  • Talk to Us
Talk to Us
Close
    MENU
  • Culture
    • Agile Mindset
    • Bacancy Values
    • Bacancy Culture
  • What we do
    • Product Engineering
    • AI & ML
    • Blockchain
    • IOT
    • Digital Transformation
  • Who we work with
    • Real Estate
    • Finance & Insurance
    • Oil & Gas
    • Healthcare
    • Travel & Transport
    • Startups
  • About Us
    • About
    • Blog
    • Career
  • Technology
      Front-End
    • AngularJS
    • ReactJS
    • Vue.JS
    • JavaScript
    • Backbone.JS
    • Ember.JS
    • MEAN
    • MERN
    • Back-End
    • Ruby on Rails
    • Node.JS
    • Golang
    • Laravel
    • PHP
    • Python
    • .NET
    • Yii
    • Mobile
    • Android
    • iOS
    • React Native
    • Flutter
    • Ionic
    • Kotlin
    • CMS & CRM
    • Spree
    • Magento
    • Wordpress
    • Drupal
    • Umbraco
    • Woocommerce
    • Salesforce
    • Microsoft Dynamics 365
    • Explore All
  • Contact Us
  • CLOSE
Unit Testing in Angular Application

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

Parth Sardhara
Parth Sardhara
March 25, 2020 8 min read

Last Updated on September 24, 2020

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 Contents

1) What are the test cases?

2) Type of testing and their benefits.

  • Unit test
  • Benefit to write the unit test
  • Integration test
  • Benefit to write an integration test
  • End-to-end test
  • Benefit to write End-to-end test

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

  • What is Jasmine?
  • What is Karma?
  • What is Protractor?

4) Unit test fundamentals.

5) Point for Implementation

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.

What is karma in Angular testing?

  • 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

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.

Parth Sardhara
Parth Sardhara View all post
I am a Frontend web developer who is always keen to learn about trending frontend technologies. My core areas of expertise are ECMAScript 2015 (ES6), Angular (6,7,8), JavaScript, CSS, Bootstrap, Reactjs, and many more that fall in-between. I love to share my knowledge by conducting training sessions and helping my colleagues in resolving technical problems. Apart from programming in front-end, I just love to do Dance, perform stunts, and solve the Rubik’s cube.

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 !



0 Comments on "Unit Testing in Angular Application Using Jasmine and Karma Part-1"

Leave a Reply Cancel

Related articles
lazy loading in angular
AngularJS
Step by Step Guide on Lazy Loading in Angular 11
March 5, 2021 by: Archita Nayak
Angular Routing
AngularJS
Angular 11 Routing Example: How to Implement Basic Angular Routing and Nested Routing With Params
March 1, 2021 by: Archita Nayak
Angular Best Practices
AngularJS
Top 7 Angular Best Practices to Organize Your Angular App
February 5, 2021 by: Archita Nayak

Top 1% IT Talent

Bacancy Technology is an exclusive hub of top dedicated software developers, UI/UX designers, QA experts, and product managers with an incredibly rare and hidden talents you will ever come across. We let you access the top 1% IT talent from independent software developers to the fully managed teams.

Time Zone Aligned

Timezone is never a constraint when you are working with Bacancy Technology. We follow one very simple principle – our developers and your time zone. Hire dedicated software developers from us and make collaboration in a faraway to work according to your time zone, deadline, and milestone.

Experienced Team

Whether you are looking for skilled developers in emerging technologies or looking for an extended arms to augment your existing team, we can lend a helping hand in both situations. We are a full-stack software development company with 300+ skilled and experienced software developers whom you can hire at your convenience to address the ongoing business challenges

Let us help you build a modern digital business to overcome traditional culture and succeed in the age of digital transformation.

  • USA
  • Canada
  • Australia
  • India
  • UAE
  • Sweden

USA

Bacancy Technology LLC

Florida

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

Phone

+1 347 441 4161

Email

[email protected]

We guarantee 100% security of your information. We will not share the details you provide above with anyone. Your email won't be used for spamming.

Canada

Bacancy Technology Inc

Toronto

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

Phone

+1 416 907 6738

Email

[email protected]

We guarantee 100% security of your information. We will not share the details you provide above with anyone. Your email won't be used for spamming.

Australia

Bacancy Technology

South Australia

351A Hampstead Rd, Northfield SA 5085

Phone

(02) 8005 8222

Email

[email protected]

We guarantee 100% security of your information. We will not share the details you provide above with anyone. Your email won't be used for spamming.

India

Bacancy Technology Pvt Ltd

Ahmedabad

1207-1210, Time Square, Thaltej-Shilaj Road, Ahmedabad

Pune

2nd Floor, Marisoft-1, Marigold IT Park, Pune

Phone

079- 40037674

Email

[email protected]

We guarantee 100% security of your information. We will not share the details you provide above with anyone. Your email won't be used for spamming.

UAE

Bacancy Technology

Dubai

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

Phone

+1 347 441 4161

Email

[email protected]

We guarantee 100% security of your information. We will not share the details you provide above with anyone. Your email won't be used for spamming.

Sweden

Bacancy Technology

Hagersten

Junkergatan 4, 126 53 Hagersten

Phone

+1 347 441 4161

Email

[email protected]

We guarantee 100% security of your information. We will not share the details you provide above with anyone. Your email won't be used for spamming.

How Can We Help?

  • Employee
  • Brochure
  • Quality Assurance
  • Resources
  • Privacy Policy
  • Sitemap
  • Solution
  • Contact Us
DMCA.com Protection Status
Request A Free Consultation