Testing Services in Angular Like a Pro !

Shashank Vivek
2 min readApr 4, 2019

In my previous article, I have explained the fundamentals of Unit testing and how Karma-Jasmine works together to achieve this goal. I have also covered testing of HTML content and Component with injected services.

In this article, we’ll be focusing on testing services in Angular. I’ll be using a sample service which I have used during testing of Component with injected services with source code in my github repository.

List of methods in our students.service.ts file:

  1. getUserList [ get list of users ]
  2. getUserDetails [ get User details for id ]
  3. transformResponseToAddUniversity [ add “university” property to response]
  4. getDepartmentMapping [ get department association by passing “deptId” and “id ]
  5. saveUserAssociation [ POST call to save the data ].

Let’s start with a basic skeleton of the service:

Note that :

  • HttpClientTestingModule is imported to mock HttpClientModule because we don’t want to make actual http requests while testing the service.
  • HttpTestingController is injected into tests, that allows for mocking and flushing of requests.
  • httpMock.verify() is called after each tests to verify that there are no outstanding http calls

Testing of getUserList()

Testing of getUserDetails()

This method is something special where we are transforming the response of http by another method transformResponseToAddUniversity().

We have the code in students.service.ts as below:

As we can see, we are adding “university” property into the http response. To test this behavior, we need to create 2 response:

  1. The response that we expect from http . [dummyUserDetails]
  2. The transformed response that we get out of the method [tranformedDummyUserDetails ]

Testing of getDepartmentMapping()

The getDepartmentMapping() is slightly different, as we are passing params to GET request using HttpParam().

Note that in getUserDetails() we are simply calling a REST API, but here things are different. We are passing params using HttpParams

Testing of saveUserAssociation()

In the end, we end up with a good code coverage of all methods of our service. Checkout the final code here.

Cheers !

--

--