Currently, I am in the process of writing unit tests for a basic service. This service is responsible for fetching a list of users from the backend REST API.
// user.service.ts
import {Injectable} from '@angular/core';
import {HttpClient} from '@angular/common/http';
import {Observable} from 'rxjs';
import {environment} from '../../../environments/environment';
import {ListDto} from '../../dto/commons/list.dto';
@Injectable()
export class UserService {
constructor(
private http: HttpClient
) { }
getUserList(): Observable<ListDto> {
return this.http
.get<ListDto>(environment.coreUrl + environment.basePath + '/user');
}
During my unit testing phase, I encountered an issue where there was no output when trying to log the Observable
returned by the function getUserList()
. As a result, I am unable to perform any validations. Below is the snippet of my unit test:
// user.service.spec.ts
import {UserService} from './user.service';
import {inject, TestBed} from '@angular/core/testing';
import {HttpClientTestingModule, HttpTestingController} from '@angular/common/http/testing';
describe('UserService', () => {
beforeEach(() => {
TestBed.configureTestingModule({
imports: [
HttpClientTestingModule
],
providers: [
UserService
]
});
});
afterEach(inject([
HttpTestingController
], (httpMock: HttpTestingController) => {
httpMock.verify();
}));
it('should be able to get the list of users',
inject(
[HttpTestingController, UserService],
(httpMock: HttpTestingController, service: UserService) => {
service.getUserList().subscribe((data) => {
console.log(data); // no output
});
// sanity
const req = httpMock.expectOne('http://localhost:8080/v1/api/user');
expect(req.request.method).toEqual('GET');
}
)
);
Given that I am relatively new to Angular, I could use some guidance on where I might have gone wrong. Any assistance would be greatly appreciated.