Testing HTTP

In Chapter 12Integrating Backend Data Services, we learned about integrating backend services and also learned about HTTPModule and HTTPClient. We also learned how to make HTTP requests to the server and process the responses. 

In this section, we will learn how to write test scripts to test HTTP requests and responses. We will continue to use the same project we created in this chapter—the AutoStop project. Before we proceed further, it's important to have the REST API endpoints ready so that we can use them in our application.

We will learn how to use the public API, https://jsonplaceholder.typicode.com/, which is available on the internet for free. We will also create a local server to return a mock JSON response from a local static JSON file.

We must import HttpClientModule and HttpClientTestingModule into our app.module.ts file.

Before we proceed to write our test scripts for testing Angular HTTP, we will need to update our dealers service, which we have used throughout this chapter. We will implement a few methods that will make HTTP calls—POST/GET to process data to the REST API endpoints.

We are working on the dealers.service.ts file, as follows:

import { HttpClient } from '@angular/common/http';
import { HttpHeaders, HttpParams, HttpErrorResponse } from '@angular/common/http';
readonly REST_ENDPOINT = 'https://jsonplaceholder.typicode.com/users';
readonly DEALER_REST_ENDPOINT = 'https://jsonplaceholder.typicode.com/users/1';
private _carurl = 'http://localhost:3000/cars';

In the preceding code, we are importing the required HTTP modules; that is, HttpClient, HttpHeaders, HttpParams, and HttpErrorResponse, and also defining two REST endpoints that have the API URL for users and a specific user.

We can also have a local server up and running. You can have local APIs using the JSON server. You can learn more about this at https://github.com/typicode/json-server.

It's time to add a few methods, through which we will make the HTTP calls to the REST endpoints:

getAllDealers()
{
this.allDealers = this.http.get(this.REST_ENDPOINT,
{
headers: new HttpHeaders().set('Accept', 'aplication/json')
});
return this.allDealers;
}

getDealerById(){
let params = new HttpParams().set('id', '1');
this.dealerDetails = this.http.get(this.REST_ENDPOINT, {params});
return this.dealerDetails;
}

In the preceding code, we are creating two methods, which make an HTTP GET request. The first method, getAllDealers, makes a call and expects a JSON response of users. The second method, getDealerById, will pass id as 1 and expect a single user data response. In the getDealerById method, we are using HttpParams to set the parameters to send to the endpoint. We will also modify our autoListComponent component to add a few methods to our Component class.

We are adding the following code to our auto-list.component.ts file:

findAuto() {
this.dealers = this._dealersService.getDealers();
return this.dealers;
}

listAllDealers(){
this.allDealers = this._dealersService.getAllDealers();
}

listDealerById(){
this.showDealerInfo = true;
this.dealerDetail = this._dealersService.getDealerById();
return this.dealerDetail;
}

getCarList() {
this.carList = this.http.get<Cars[]>(this._carurl);
}

In the preceding code, we are adding a few methods, namely findAuto, listDealerById, and getCarList, which are making HTTP calls and calling methods that are in the dealers service.

Alright, now that we have our component and services set up, which are making HTTP calls, we are good to write our tests for HTTP.

Use case #1: We want to test whether a GET call was made to a particular URL.

We will add the following code to the auto-list.component.spec.ts file:

// Test HTTP Request From Component
it('Test HTTP Request Method', async(() => {
const fixture = TestBed.createComponent(AutoListComponent);

component = fixture.componentInstance;
httpMock = TestBed.get(HttpTestingController);

let carList = component.getCarList();

fixture.detectChanges();
const req = httpMock.expectOne('http://localhost:3000/cars');

expect(req.request.method).toBe('GET');
req.flush({});

}));

In the preceding code, we are creating the instance of AutoListComponentusing which we will make a call to its getCarList method. In the getCarList method, we are making a call to the http://localhost:3000/cars URL to retrieve data. We are creating an instance of the HttpTestingController class named httpMock. Using the httpMock instance, we are asserting that at least one call should be made to the URL.

Use case #2: We want to expect that the data returned as the result is more than 1:

it('Test HTTP Request GET Method With subscribe', async(() => {
const fixture = TestBed.createComponent(AutoListComponent);
component = fixture.componentInstance;
component.listDealerById().subscribe(result =>
expect(result.length).toBeGreaterThan(0));

}));

In the preceding code, using the instance of AutoListComponent, we are calling the listDealerById method. Using subscribe, we are mapping the result and verifying that the result data length is greater than 0.

Use case #3: We want to verify that the data returned from the HTTP call matches the data. The following is the sample code for this use case scenario.

it('Test if the first Dealer is North Auto', () => {
const service: DealersService = TestBed.get(DealersService);
let dealers = service.getDealers();
expect(dealers[0].name).toBe('North Auto');
});

In the preceding code, using the DealersService instance, we are making a call to the getDealers methods. We are asserting data of the first index property name to be North Auto.

Run the tests using the ng test command. We should see the following output, as displayed and highlighted in the following screenshot:

If you see the preceding output, that's brilliant.

In this section, we have learned how to test components, services, and methods that are making HTTP request calls.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
3.144.96.40