在Angular 6中,我们可以使用HttpTestingController进行HTTP请求的单元测试,并使用pipe(map())来处理响应数据。以下是一个示例解决方法:
首先,安装@angular/common
和@angular/common/http
依赖项:
npm install @angular/common @angular/common/http --save-dev
假设我们有一个名为DataService
的服务,它使用HttpClient
进行HTTP请求。我们将对其进行单元测试。
DataService
中,我们需要注入HttpClient
和HttpTestingController
:import { HttpClient } from '@angular/common/http';
import { HttpTestingController } from '@angular/common/http/testing';
@Injectable()
export class DataService {
constructor(private http: HttpClient) { }
// ...
}
DataService
中添加一个方法,该方法将使用HttpClient
进行HTTP请求:import { map } from 'rxjs/operators';
// ...
getData() {
return this.http.get('/api/data').pipe(
map((response: any) => response.data)
);
}
import { TestBed, inject } from '@angular/core/testing';
import { HttpClientTestingModule, HttpTestingController } from '@angular/common/http/testing';
import { HttpClient } from '@angular/common/http';
import { DataService } from './data.service';
describe('DataService', () => {
let httpClient: HttpClient;
let httpTestingController: HttpTestingController;
let dataService: DataService;
beforeEach(() => {
TestBed.configureTestingModule({
imports: [ HttpClientTestingModule ],
providers: [ DataService ]
});
httpClient = TestBed.inject(HttpClient);
httpTestingController = TestBed.inject(HttpTestingController);
dataService = TestBed.inject(DataService);
});
afterEach(() => {
httpTestingController.verify();
});
it('should retrieve data', () => {
const testData = { data: 'test data' };
dataService.getData().subscribe(data => {
expect(data).toEqual(testData.data);
});
const req = httpTestingController.expectOne('/api/data');
expect(req.request.method).toBe('GET');
req.flush(testData);
});
});
在上面的代码中,我们首先导入需要的依赖项。然后,在beforeEach
块中,我们使用TestBed.configureTestingModule
配置测试模块,并通过TestBed.inject
获取依赖项的实例。
在it
块中,我们调用dataService.getData()
方法,并使用expectOne
方法来匹配预期的HTTP请求。然后,我们使用flush
方法来模拟响应数据并完成HTTP请求。
最后,在afterEach
块中,我们调用httpTestingController.verify()
方法来验证没有未处理的HTTP请求。