在我的项目中,共享文件夹中有一个sharedService,它被调用到所有服务中。 实际上,我的服务将其请求发送到此sharedService,并且sharedService根据接收到的URL发送一个http请求。 如何为我的服务编写unitTest?
sharedService具有Api方法:
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( );
}
}
users模块中的usersService将其请求发送到Api 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');
}
}
如何为usersService unitTest编写代码?
答案 0 :(得分:2)
请尝试这样。对于此示例,SharedService返回一个用户名数组。
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'])
})
})
})