|
| 1 | + |
| 2 | +## HttpClientTestingModule |
| 3 | +To test services with the [HttpClient](https://angular.io/api/common/http/HttpClient) dependency, we can use the utilities of Angular testing. We don't need to use all the object utilities of HttpClient, so we use [HttpClientTestingModule](https://angular.io/api/common/http/testing/HttpClientTestingModule#description) to test, this is a soft module designed just for testing. For example: |
| 4 | +```ts |
| 5 | +import { Injectable } from '@angular/core'; |
| 6 | +import { HttpClient } from '@angular/common/http'; |
| 7 | +import { Observable } from 'rxjs'; |
| 8 | +import { User } from '../models/user'; |
| 9 | + |
| 10 | +@Injectable({ providedIn: 'root' }) |
| 11 | +export class UserService { |
| 12 | + constructor(private http: HttpClient) {} |
| 13 | + |
| 14 | + findUserById(userId: number): Observable<User> { |
| 15 | + return this.http.get<User>(`api/users/${userId}`); |
| 16 | + } |
| 17 | + |
| 18 | + findAllUsers(): Observable<User[]> { |
| 19 | + return this.http.get('api/users') as Observable<User[]>; |
| 20 | + } |
| 21 | + |
| 22 | + saveUser(useId: number, changes: Partial<User>): Observable<User> { |
| 23 | + return this.http.put<User>(`api/user/${useId}`, changes); |
| 24 | + } |
| 25 | +} |
| 26 | +``` |
| 27 | + |
| 28 | +```ts |
| 29 | +import { TestBed } from '@angular/core/testing'; |
| 30 | +import { |
| 31 | + HttpClientTestingModule, |
| 32 | + HttpTestingController, |
| 33 | +} from '@angular/common/http/testing'; |
| 34 | +import { of } from 'rxjs'; |
| 35 | +import { USERS } from '../data/data'; |
| 36 | +import { UserService } from './user.service'; |
| 37 | + |
| 38 | +describe('UserService Using HttpClientTestingModule', () => { |
| 39 | + let service: UserService; |
| 40 | + let controller: HttpTestingController; |
| 41 | + beforeEach(() => { |
| 42 | + TestBed.configureTestingModule({ |
| 43 | + imports: [HttpClientTestingModule], |
| 44 | + providers: [], |
| 45 | + }); |
| 46 | + |
| 47 | + service = TestBed.inject(UserService); |
| 48 | + controller = TestBed.inject(HttpTestingController); |
| 49 | + }); |
| 50 | + |
| 51 | + it('create', () => { |
| 52 | + expect(service).toBeTruthy(); |
| 53 | + }); |
| 54 | +``` |
| 55 | +In this section, we configure the testing module with the dependency HttpClientTestingModule. |
| 56 | +Moreover, we don't need a fixture on this configuration due to the fact tha this is just a service |
| 57 | +and not a layout. |
| 58 | +
|
| 59 | +So, first of all we need to init the following variables: |
| 60 | +
|
| 61 | +1. The service |
| 62 | + a. `let service: UserService;` |
| 63 | + b. `service = TestBed.inject(userService);` |
| 64 | +
|
| 65 | +When using the `TestBed.inject` we are getting the instance of the injected dependency. This **doesn't** mean that |
| 66 | +we are injecting this dependency twice. |
| 67 | +
|
| 68 | +2. The controller |
| 69 | + a. `let controller: HttpTestingController;` |
| 70 | + b. `controller = TestBed.inject(HttpTestingController);` |
| 71 | +
|
| 72 | +In fact, the controller variable is optional, however, this dependency will help us to create more complete |
| 73 | +tests cases. |
| 74 | +
|
| 75 | +
|
| 76 | +```ts |
| 77 | +it('return all users', (done) => { |
| 78 | + service.findAllUsers().subscribe((users) => { |
| 79 | + expect(users).toEqual(USERS); |
| 80 | + done(); |
| 81 | + }); |
| 82 | + const req = controller.expectOne('api/users'); |
| 83 | + expect(req.request.method).toEqual('GET'); |
| 84 | + req.flush(USERS); |
| 85 | +}); |
| 86 | +``` |
| 87 | +In this test, we subscribe to ```findAllUsers```. Then, inside we create the assertion to verify the response data. ```done()``` is used to indicate the successful finish of the subscription. |
| 88 | +
|
| 89 | +With the [controller](https://angular.io/api/common/http/testing/HttpTestingController) we can mock and flush the request. |
| 90 | +
|
| 91 | +
|
| 92 | +```ts |
| 93 | +it('Should return user with specific Id', (done) => { |
| 94 | + const user = USERS[0]; |
| 95 | + service.findUserById(user.id).subscribe((selectedUser) => { |
| 96 | + expect(selectedUser).toEqual(user); |
| 97 | + done(); |
| 98 | + }, done.fail); |
| 99 | + const req = controller.expectOne(`api/user/${user.id}`); |
| 100 | + expect(req.request.method).toEqual('GET'); |
| 101 | + req.flush(user); |
| 102 | + }); |
| 103 | + |
| 104 | + it('should update user', (done) => { |
| 105 | + const user = USERS[0]; |
| 106 | + user.info.name = 'Andres'; |
| 107 | + service.saveUser(user.id, user).subscribe((updatedUser) => { |
| 108 | + expect(updatedUser).toEqual(user); |
| 109 | + done(); |
| 110 | + }, done.fail); |
| 111 | + const req = controller.expectOne(`api/user/${user.id}`); |
| 112 | + expect(req.request.method).toEqual('PUT'); |
| 113 | + expect(req.request.body.info.name).toEqual(user.info.name); |
| 114 | + |
| 115 | + req.flush(user); |
| 116 | + }); |
| 117 | + |
| 118 | + afterEach(() => { |
| 119 | + controller.verify(); |
| 120 | + }); |
| 121 | +}); |
| 122 | +``` |
| 123 | +Finally, in the afterEach we can verify that no unmatched requests are outstanding. |
0 commit comments