{"id":12276,"date":"2020-03-25T12:17:31","date_gmt":"2020-03-25T12:17:31","guid":{"rendered":"https:\/\/www.bacancytechnology.com\/blog\/?p=12276"},"modified":"2025-03-12T06:50:40","modified_gmt":"2025-03-12T06:50:40","slug":"unit-testing-in-angular-application-using-jasmine-and-karma-part-1","status":"publish","type":"post","link":"https:\/\/www.bacancytechnology.com\/blog\/unit-testing-in-angular-application-using-jasmine-and-karma-part-1","title":{"rendered":"Unit Testing in Angular Application Using Jasmine and Karma Part-1"},"content":{"rendered":"<style>\nul.index-list {\n    text-align: left;\n    list-style-type: square;\n}\np{\n   width:100%;\n}\n.post-content p img {\n    margin-bottom: 0 !important;\n}\n.text-orange,.text-orange> strong{\ncolor: #ec6100 !important;\nfont-weight: 700;\n}\n.border-box{\npadding: 12px;\nborder: 1px solid #000;\nmargin-bottom: 16px;\n}\n.border-div{border: 1px solid #000; padding: 22px; text-align: center; margin-bottom: 32px;}\n\t\t.border-bottom{\n\t\t\tborder-bottom: 1px solid #000;\n\t\t\ttext-align: center;\n\t\t\tdisplay: inline-block;\n\t\t}\n\t\t.border-div p{text-align: left;}\n\t\t.cust-list{padding: 0; text-align: left;}\n\t\t.cust-list li{padding-left: 32px; list-style: none}\npre {\n    background: #f7e9dd;\n    border: none;\n    font-size: 16px;\n}\n.cross-platform{\n    background: #f7e9dd;\n    border: none;\n    font-size: 20px;\n    text-align:center;\n    padding:40px;\n}\n.cross-platform a{\n   font-size: 20px !important;\n    font-weight: bold !important;\n    margin-top: 10px;\n    border-radius: 10px !important;\n    background: #ec6100 !important;\n    border: 1px solid transparent !important;\n}\n.final{\n    background: #f7e9dd;\n    border: none;\n    font-size: 20px;\n    text-align:left;\n    padding:40px;\n}\n.final a{\n   font-size: 20px !important;\n    font-weight: bold !important;\n    margin-top: 10px;\n    border-radius: 10px !important;\n    border: 1px solid transparent !important;\n}\n<\/style>\n<p>Hello guys, welcome again!<\/p>\n<p>In my previous blog post, we discussed<a href=\"https:\/\/www.bacancytechnology.com\/blog\/http-interceptors-in-angular\" rel=\"noopener\" target=\"_blank\"> what are Angular HTTP interceptors and how to use them<\/a>, and now I am back with another blog post, where we will discuss unit testing in Angular using Jasmine and karma. <\/p>\n<p>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&#8217;s get started.<\/p>\n<div class=\"border-div\">\n<h2 class=\"border-bottom\">Table Of Content<\/h2>\n<p><a href=\"#1\">What is a test case in software testing?<\/a><\/p>\n<p><a href=\"#2\">Types of Testing<\/a><\/p>\n<p><a href=\"#3\">What are the testing tools and methods which are used for the unit test<\/a><\/p>\n<p><a href=\"#4\">Unit test fundamentals<\/a><\/p>\n<p><a href=\"#5\">Point for Implementation<\/a><\/p>\n<p><a href=\"#6\">Conclusion <\/a><\/p>\n<\/div>\n<h2 id=\"1\">What is a test case in software testing?<\/h2>\n<ul class=\"bullets\"><\/li>\n<li>Tests are one of the best ways to prevent software defects<\/li>\n<li>We write the test cases that the behavior of the code will work as per our expectations or not<\/li>\n<li>Jasmine is a BDD framework for testing JavaScript code that performs well with Karma<\/li>\n<li>What is Suite and specs in unit testing?\n<ul class=\"bullets\">\n<li>Suite is the collection of single test.<\/li>\n<li>Spec is the only unit test<\/li>\n<\/ul>\n<\/li>\n<\/ul>\n<h2 id=\"2\">Types of Testing<\/h2>\n<ul class=\"bullets\">\n<li>Unit test<\/li>\n<li>Integration test<\/li>\n<li>End-to-end test<\/li>\n<\/ul>\n<p><strong>Unit Test<\/strong><\/p>\n<ul class=\"bullets\">\n<li>Test the component in isolation, without external resources (API endpoint, database)<\/li>\n<li>Just create a fake response or instance and just write the test case base on that.<\/li>\n<\/ul>\n<p>Benefits of writing the Unit test<\/p>\n<ul class=\"bullets\">\n<li>Easier to write<\/li>\n<li>Super-fast<\/li>\n<li>Give us much confidence for the  functionality<\/li>\n<\/ul>\n<p><strong>Integration test<\/strong> <\/p>\n<ul class=\"bullets\">\n<li>Test the component with external resources, API endpoint also with access database.<\/li>\n<\/ul>\n<p>Benefit of writing the integration testing<\/p>\n<ul class=\"bullets\">\n<li>Easier to write<\/li>\n<li>Super-fast<\/li>\n<li>Give us much confidence for the functionality<\/li>\n<\/ul>\n<p><strong>End-to-end testing<\/strong><\/p>\n<ul class=\"bullets\">\n<li>Test the component with external resources, API endpoint also with access database.<\/li>\n<li>Protractor Testing Tool is used for end-to-end testing especially for AngularJS apps<\/li>\n<\/ul>\n<p>Benefits of writing end-to-end testing: <\/p>\n<ul class=\"bullets\">\n<li>We can test all the component or project<\/li>\n<li>Best practice for testing for all the functionality of the project<\/li>\n<li>Give us much more confidence for the product testing<\/li>\n<\/ul>\n<h2 id=\"3\">What are the Testing tools (Test runners) or methods used to write and run the test cases?<\/h2>\n<p>(1) Jasmine<\/p>\n<p>(2) Karma<\/p>\n<p>(3) Protractor<\/p>\n<h3>What is the use of Jasmine in Angular?<\/h3>\n<ul class=\"bullets\">\n<li>Jasmine is a JavaScript testing framework.<\/li>\n<li>Jasmine lets you run on any JS enabled platform and make it easy-to-read syntax.<\/li>\n<\/ul>\n<h3>Testing Angular with Karma<\/h3>\n<ul class=\"bullets\">\n<li>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.<\/li>\n<li>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.<\/li>\n<\/ul>\n<h3>What is the Protractor testing tool?<\/h3>\n<p>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.<\/p>\n<h2 id=\"4\">Unit Testing Fundamentals:-<\/h2>\n<p><strong>Clean coding practice<\/strong><\/p>\n<ul class=\"bullets\">\n<li>Small function\/ methods (10 to 15 line of code)<\/li>\n<li>Proper naming for the test case (Test case which testing for what )<\/li>\n<li>Single responsibility<\/li>\n<\/ul>\n<h2 id=\"5\">Point for Implementation:-<\/h2>\n<p>In Angular, we have a .spec file for component, service, pipe, and for others also and every .spec file has 1 method called <strong>Describe<\/strong>.<\/p>\n<p>Describe has many single tests we can write and run for that component, service, pipe, etc.<\/p>\n<p>So Describe => is a Group of test cases. <strong>Also called a Suite<\/strong> and<br \/>\nIt(&#8216;should create) => Single test case, <strong>Also called a Spec<\/strong>.<\/p>\n<p><strong>Before we jump into writing the unit test, let me explain what we have inside the spec file for the component.<\/strong><\/p>\n<p><strong>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.<\/strong><\/p>\n<p><img loading=\"lazy\" decoding=\"async\" src=\"https:\/\/www.bacancytechnology.com\/blog\/wp-content\/uploads\/2020\/03\/app.component.spec_.ts-file.png\" alt=\"app.component.spec.ts file\" width=\"512\" height=\"387\" class=\"aligncenter size-full wp-image-12284\" srcset=\"https:\/\/www.bacancytechnology.com\/blog\/wp-content\/uploads\/2020\/03\/app.component.spec_.ts-file.png 512w, https:\/\/www.bacancytechnology.com\/blog\/wp-content\/uploads\/2020\/03\/app.component.spec_.ts-file-300x227.png 300w, https:\/\/www.bacancytechnology.com\/blog\/wp-content\/uploads\/2020\/03\/app.component.spec_.ts-file-20x15.png 20w\" sizes=\"auto, (max-width: 512px) 100vw, 512px\" \/><\/p>\n<p>So as per the above image, it has 1 method called <strong>describe <\/strong>and inside <strong>describe<\/strong>, it has 3 single test write with it() method.<\/p>\n<p><strong>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.<\/strong><\/p>\n<p>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.<\/p>\n<pre>\r\n   const fixture = TestBed.createComponent(AppComponent);\r\n   const app = fixture.debugElement.componentInstance;\r\n<\/pre>\n<p>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.<\/p>\n<p><strong>Like if we have a title in TS file like,<\/strong><\/p>\n<pre>\r\ntitle = 'Unit testing';\r\n<\/pre>\n<p>Then we can access the title variable using the app.title where we are able to write the unit test for that variable.<\/P><\/p>\n<p>So if we want to access the component HTML file of any element, then we need to write the below line of the code.<\/p>\n<pre>\r\n const fixture = TestBed.createComponent(AppComponent);\r\n   fixture.detectChanges();\r\n   const compiled = fixture.debugElement.nativeElement;\r\n<\/pre>\n<p>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.<\/p>\n<p><strong>Like if we have a div in html file like,<\/strong><\/p>\n<pre>\r\n< h1 >{{title}} app is running!< \/h1 >\r\n<\/pre>\n<p><strong>Then we can write the test cases like below first need to select that h1 then we need to test it. <\/strong><\/p>\n<pre>\r\n expect(compiled.querySelector('h1').textContent).toContain('Unit testing app is running!');\r\n<\/pre>\n<p>To run the test cases, you need to go to the terminal and need to enter the command, which is <strong>ng test<\/strong>.<\/p>\n<p><strong>This will automatically open the chrome browser with karma and will look like the image below.<\/strong><\/p>\n<p><img loading=\"lazy\" decoding=\"async\" src=\"https:\/\/www.bacancytechnology.com\/blog\/wp-content\/uploads\/2020\/03\/karma-connected.png\" alt=\"karma connected\" width=\"512\" height=\"293\" class=\"aligncenter size-full wp-image-12285\" srcset=\"https:\/\/www.bacancytechnology.com\/blog\/wp-content\/uploads\/2020\/03\/karma-connected.png 512w, https:\/\/www.bacancytechnology.com\/blog\/wp-content\/uploads\/2020\/03\/karma-connected-300x172.png 300w, https:\/\/www.bacancytechnology.com\/blog\/wp-content\/uploads\/2020\/03\/karma-connected-20x11.png 20w\" sizes=\"auto, (max-width: 512px) 100vw, 512px\" \/><\/p>\n<p><strong>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<\/strong>.<\/p>\n<p><strong>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.<\/strong><\/p>\n<p><img loading=\"lazy\" decoding=\"async\" src=\"https:\/\/www.bacancytechnology.com\/blog\/wp-content\/uploads\/2020\/03\/home.component.spec_.ts-file.png\" alt=\"home.component.spec.ts file\" width=\"509\" height=\"649\" class=\"aligncenter size-full wp-image-12286\" srcset=\"https:\/\/www.bacancytechnology.com\/blog\/wp-content\/uploads\/2020\/03\/home.component.spec_.ts-file.png 509w, https:\/\/www.bacancytechnology.com\/blog\/wp-content\/uploads\/2020\/03\/home.component.spec_.ts-file-235x300.png 235w, https:\/\/www.bacancytechnology.com\/blog\/wp-content\/uploads\/2020\/03\/home.component.spec_.ts-file-16x20.png 16w\" sizes=\"auto, (max-width: 509px) 100vw, 509px\" \/><\/p>\n<p>Now, let&#8217;s start to write the test cases for the different scenarios for the component.<\/p>\n<p><strong>1. How to check the value of variable state value is &#8216;state value&#8217;.<\/strong><\/p>\n<pre>\r\nit('Variable stateValue should be state value', () => {\r\n   expect(component.stateValue).toBe('state value');\r\n });\r\n<\/pre>\n<p><strong>2. How to check the value of variable state value should not be other than state value.<\/strong><\/p>\n<pre>\r\n it('Variable stateValue should not be other than state value', () => {\r\n   expect(component.stateValue).not.toBe('hello1');\r\n });\r\n<\/pre>\n<p><strong>3. How to check the variable state value should start with &#8216;state.&#8217;<\/strong><\/p>\n<pre>\r\n it('stateValue variable should start with state', () => {\r\n   const mockState = 'state';\r\n   expect(component.stateValue).toMatch(mockState);\r\n });\r\n<\/pre>\n<p><strong>4. How to call the method and match with the result of that method?<\/strong><\/p>\n<p><strong>Let&#8217;s say we have a method in TS file like.<\/strong><\/p>\n<pre>\r\nname(name) {\r\n   return 'Welcome ' + name + '!';\r\n }\r\n<\/pre>\n<p><strong>So if we pass the name, then we will get the result based on that return statement.<\/strong><\/p>\n<pre>\r\n it('name method should return as per the parameter passed', () => {\r\n   const name = component.name('parth');\r\n   expect(name).toBe('Welcome parth!');\r\n });\r\n<\/pre>\n<p><strong>5. How to check the value of the array?<\/strong><\/p>\n<p><strong>Let&#8217;s say we have a method in TS file, which is ArrayList and which will return an array.<\/strong>\n<\/p>\n<pre>\r\nArrayList() {\r\n   return ['first name', 'last name', 'middle name'];\r\n }\r\n<\/pre>\n<p><strong>So we can use the container method for that to check array contain the value or not.<\/strong><\/p>\n<pre>\r\nit(\"ArrayList should contain 'first name'.\", () => {\r\n   const name = component.arrayList();\r\n   expect(name).toContain('first name');\r\n });\r\n<\/pre>\n<p><strong>6. How to write the test cases for the scenario like Variable value should be changed if a particular method is called.<\/strong><\/p>\n<p><strong>Here we called the method ngOnInit, and then the value of the welcome is changed to &#8216;a.&#8217;<\/strong><\/p>\n<pre>\r\nngOnInit() {\r\n   this.welcome = this.isLoggedIn;\r\n }\r\n<\/pre>\n<p><strong>For that first, we need to call the method; then, we need to compare it something like as shown in the below image.<\/strong><\/p>\n<pre>\r\n it('value of the welcome variable should be a once ngOnInit method have been called', () => {\r\n   component.ngOnInit();\r\n   expect(component.welcome).toContain(component.isLoggedIn);\r\n });\r\n<\/pre>\n<p><strong>7. If the array has only value, then how to check if the array is the same or not?<\/strong><\/p>\n<p><strong>Like we have an array isLoggedInArray having 1 string value a.<\/strong><\/p>\n<pre>\r\n public isLoggedInArrary = ['a'];\r\n<\/pre>\n<p><strong>So for that, we will use the toEqual method and will check that array has &#8216;a&#8217; or not, which is something like,<\/strong><\/p>\n<pre>\r\n it('should have only 1 value which is a  in isLoggedInArrary', () => {\r\n   const isLoggedInArrary = component.isLoggedInArrary;\r\n   expect(isLoggedInArrary).toEqual(['a']);\r\n });\r\n<\/pre>\n<p><strong>8. How to check that 2 objects are the same or not in terms of key and value?<\/strong><\/p>\n<p><strong>Let&#8217;s say we have two objects named Object1 and Object2 whose values are the same.<\/strong><\/p>\n<pre>\r\npublic Object1 = {\r\n   bath: true,\r\n   bedrooms: 4,\r\n   kitchen: {\r\n     amenities: ['oven', 'stove', 'washer'],\r\n     area: 20,\r\n     wallColor: 'white',\r\n   },\r\n };\r\n \r\npublic Object2 = {\r\n   bath: true,\r\n   bedrooms: 4,\r\n   kitchen: {\r\n     amenities: ['oven', 'stove', 'washer'],\r\n     area: 20,\r\n     wallColor: 'white',\r\n   },\r\n };\r\n<\/pre>\n<p><strong>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.<\/strong><\/p>\n<pre>\r\n it('Object1 and Object2 should have the equal value.', () => {\r\n   expect(component.Object1).toEqual(component.Object2);\r\n });\r\n<\/pre>\n<p><strong>9. How to check the variable is null or not?<\/strong><\/p>\n<pre>\r\n public stateValueNull: string = null;\r\n<\/pre>\n<pre>\r\n it('stateValueNull should be null initially.', () => {\r\n   expect(component.stateValueNull).toBeNull();\r\n });\r\n<\/pre>\n<p><strong>10. How to check the variable is undefined or not?<\/strong><\/p>\n<pre>\r\npublic stateValueUndefine;\r\n<\/pre>\n<pre>\r\n it('stateValueUndefine should be null initially undefined', () => {\r\n   expect(component.stateValueUndefine).toBeUndefined();\r\n });\r\n<\/pre>\n<p><strong>How to Run the Test Cases and Validate It is a Failure or Successful?<\/strong><\/p>\n<p>https:\/\/drive.google.com\/file\/d\/1Y1QklM5oEg8eMJpBNqfzjdXLmANqOxFc\/view<\/p>\n<h2 id=\"6\">Conclusion<\/h2>\n<p>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 <a href=\"https:\/\/www.bacancytechnology.com\/angular-js-development\" rel=\"noopener\" target=\"_blank\">hire Angular developer<\/a> from us to leverage our top-of-the-line expertise. Apart from that, we also offer <a href=\"https:\/\/www.bacancytechnology.com\/angular-upgrade-service\" rel=\"noopener\" target=\"_blank\">Angular upgrade service<\/a> to migrate or upgrade your existing Angular application to the latest version of Angular Ivy.<\/p>\n<p>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.<\/p>\n","protected":false},"excerpt":{"rendered":"<p>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 [&hellip;]<\/p>\n","protected":false},"author":37,"featured_media":12289,"comment_status":"open","ping_status":"open","sticky":false,"template":"","format":"standard","meta":{"_acf_changed":false,"inline_featured_image":false,"_lmt_disableupdate":"no","_lmt_disable":"","footnotes":""},"categories":[989,1364],"tags":[],"coauthors":[1580],"class_list":["post-12276","post","type-post","status-publish","format-standard","has-post-thumbnail","hentry","category-angularjs","category-application-development"],"acf":[],"modified_by":"Binal Prajapati","_links":{"self":[{"href":"https:\/\/www.bacancytechnology.com\/blog\/wp-json\/wp\/v2\/posts\/12276","targetHints":{"allow":["GET"]}}],"collection":[{"href":"https:\/\/www.bacancytechnology.com\/blog\/wp-json\/wp\/v2\/posts"}],"about":[{"href":"https:\/\/www.bacancytechnology.com\/blog\/wp-json\/wp\/v2\/types\/post"}],"author":[{"embeddable":true,"href":"https:\/\/www.bacancytechnology.com\/blog\/wp-json\/wp\/v2\/users\/37"}],"replies":[{"embeddable":true,"href":"https:\/\/www.bacancytechnology.com\/blog\/wp-json\/wp\/v2\/comments?post=12276"}],"version-history":[{"count":0,"href":"https:\/\/www.bacancytechnology.com\/blog\/wp-json\/wp\/v2\/posts\/12276\/revisions"}],"wp:featuredmedia":[{"embeddable":true,"href":"https:\/\/www.bacancytechnology.com\/blog\/wp-json\/wp\/v2\/media\/12289"}],"wp:attachment":[{"href":"https:\/\/www.bacancytechnology.com\/blog\/wp-json\/wp\/v2\/media?parent=12276"}],"wp:term":[{"taxonomy":"category","embeddable":true,"href":"https:\/\/www.bacancytechnology.com\/blog\/wp-json\/wp\/v2\/categories?post=12276"},{"taxonomy":"post_tag","embeddable":true,"href":"https:\/\/www.bacancytechnology.com\/blog\/wp-json\/wp\/v2\/tags?post=12276"},{"taxonomy":"author","embeddable":true,"href":"https:\/\/www.bacancytechnology.com\/blog\/wp-json\/wp\/v2\/coauthors?post=12276"}],"curies":[{"name":"wp","href":"https:\/\/api.w.org\/{rel}","templated":true}]}}