import { TestBed } from '@angular/core/testing'; import { HttpClientTestingModule, HttpTestingController } from '@angular/common/http/testing'; import { HttpClient } from '@angular/common/http';
describe('Your Component', () => { let httpClient: HttpClient; let httpTestingController: HttpTestingController;
beforeEach(() => { TestBed.configureTestingModule({ imports: [ HttpClientTestingModule ], providers: [ YourService ] });
httpClient = TestBed.inject(HttpClient);
httpTestingController = TestBed.inject(HttpTestingController);
});
afterEach(() => { httpTestingController.verify(); });
it('should get data with query params', () => { const query = { param: 'value' }; const response = { data: 'your data' };
httpClient.get('/your/api/route', { params: query }).subscribe((data) => {
expect(data).toEqual(response);
});
const req = httpTestingController.expectOne('/your/api/route?param=value');
expect(req.request.method).toEqual('GET');
req.flush(response);
}); });
在测试用例中使用httpClient.get方法并传入需要的查询参数。在subscribe回调中使用expect方法验证是否得到了正确的响应数据。
使用httpTestingController.expectOne方法捕捉http请求,并验证请求方法和API地址是否正确,最后使用req.flush方法输出响应数据。
最后,在afterEach钩子函数中使用httpTestingController.verify方法验证是否所有请求都被捕捉并且响应了。