Testing is done to test our application by executing some functions by creating instances of corresponding classes,executing functions and checking the actual behaviour of our app with expected result. The tools and frameworks used in Angular are Jasmine and Karma. In this blog, I will describe about how I have implemented tests for Newly Added Knowledge API service that helped us to increase overall code coverage by 1.05% in Susper .
Adding tests for Knowledge API:
We need to check the API that whether it is functioning or not and this can be done by using a mocked response (hardcoded response) for any query and then comparing this with the received response from the API. This will help us to check proper functioning of our API.
This is a common practice in Angular and to achieve this we will be using some dependencies like MockBackend, MockConnection, BaseRequestOptions provided by Angular.
We will also need to define a Mock response, here I have used hard coded response for query India. Here is the mocked response.
Now we will use a Mock constant mock_Http_provider for http and will inject instances of MockBackend and BaseRequestOptions.
Now we need to add all the services and dependencies which we will be using in providers and we will inject the instances of Knowledgeapi Service and MockBackend in beforeEach function.
Now we will use the same query for which we have created the mocked response and we will be checking the response of from our API.
This will check the working of our API and if it is working then our test case will pass.
Like this we have implemented the tests for Knowledgeapi Service which helped us to test our API and increase overall code coverage significantly.
- Testing in Angular:https://angular.io/guide/testing
- Testing by Mockbackend:https://angular.io/api/http/testing/MockBackend
- Using MockBackend to simulate response: https://codecraft.tv/courses/angular/unit-testing/http-and-jsonp/#_using_the_code_mockbackend_code_to_simulate_a_response