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?
What are the testing tools and methods which are used for the unit test
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.
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.
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.
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.