Unit Testing for Angular service for GET Method

Madhumitha G
2 min readFeb 10, 2021

Setting up Testing:

The Angular Cli downloads everything that you need to test with Jasmine Framework.

The project you created with Angular is ready for test. Run the command

ng test

ng test
ng test

Code Coverage

To see how much code you covered run

ng test — code-coverage

once it runs will create a coverage folder in your project file . open coverage->my-app->src->index.html. open index.html in browser

code coverage for all files

you can also set coverage threshold that you want to achieve, in karma.conf.js

Testing utilities:

TestBed:

Configures and initializes environment for unit testing and provides methods for creating components and services in unit tests.

Component Fixture:

The ComponentFixture is a test harness for interacting with the created component and its corresponding element.

Service Testing for GET Method:

Let’s start off by taking a look at the service want to test. Here’s what our service.ts roughly looks like:

outputservice.ts

Here I will test for getData() method.The above code has http request which uses get method.

import httpclient, httptestingcontroller,HttpClientTestingModule

outputservice.spec.ts

Inject services,Httpclient, HttpTestingController in TestBed

import HttpclientTestingModule in Testbed

once the importing section is done call the function with service and subscribe the method.

use assert method from jasmine framework to check that you are meeting your expectations and call httptestingcontroller to check that response you are getting from same url and can check there request method to be GET then run ng test will get success and failures.

--

--