Reputation: 41
In my project there is a sharedService in the share folder that is called into all the services. In fact, my services send their request to this sharedService and the sharedService send a http request according to the url that it received. How do I write a unitTest for my services?
sharedService has Api method:
import { Injectable } from "@angular/core";
import { Observable } from "rxjs";
import { HttpClient } from '@angular/common/http';
@Injectable({
providedIn: "root"
})
export class SharedService {
constructor(
private httpClient: HttpClient) {
}
Api(method, url): Observable<any> {
this.httpClient.request(method, url).subscribe( );
}
}
The usersService in the users module send its request to the Api method in sharedService:
import { Injectable } from '@angular/core';
import { SharedService } from 'app/shared/services/shared.service';
@Injectable({
providedIn: 'root'
})
export class usersService {
constructor(private sharedService:SharedService) { }
GetUsers() {
return this.sharedService.Api('get' , 'url');
}
}
How do I write for usersService unitTest?
Upvotes: 1
Views: 114
Reputation: 2363
Please try like this. SharedService returns an array of username for this example.
describe('usersService ', () => {
let userService;
let sharedService;
beforeEach(() =>
TestBed.configureTestingModule({
imports: [
HttpClientTestingModule,
],
providers: [
SharedService,
UsersService
]
})
);
beforeEach(() => {
userService = TestBed.get(UsersService);
sharedService = TestBed.get(SharedService);
});
it('should be created', () => {
expect(userService).toBeTruthy();
});
it('should test GetUsers()', () => {
spyOn(sharedService, 'Api').and.returnValue(of(['user 1', 'user2']));
userService.GetUsers().subscrbe(data => {
expect(sharedService.Api).toHaveBeenCalled()
expect(data).toEqual(['user 1', 'user2'])
})
})
})
Upvotes: 2