使用HttpTestingController拦截HTTP请求并检查查询参数是否正确。示例代码:
import { HttpClientTestingModule, HttpTestingController } from '@angular/common/http/testing';
import { TestBed } from '@angular/core/testing';
import { HttpClient } from '@angular/common/http';
describe('my test', () => {
let httpClient: HttpClient;
let httpTestingController: HttpTestingController;
beforeEach(() => {
TestBed.configureTestingModule({
imports: [HttpClientTestingModule],
providers: [],
});
httpClient = TestBed.inject(HttpClient);
httpTestingController = TestBed.inject(HttpTestingController);
});
afterEach(() => {
httpTestingController.verify();
});
it('should send correct query params', () => {
const searchText = 'test';
const expectedParams = { q: 'test', limit: 10 };
httpClient.get('http://example.com/search?q=test&limit=10').subscribe();
const req = httpTestingController.expectOne((request) => {
return (
request.url === 'http://example.com/search' &&
request.params.get('q') === searchText &&
request.params.get('limit') === expectedParams.limit.toString()
);
});
req.flush({});
});
});
在此示例中,我们使用HttpClientTestingModule
模块和HttpTestingController
类来创建一个模拟的HttpClient
实例,并拦截发出的HTTP请求,以检查查询参数是否正确。我们使用expectOne
函数来请求HTTP请求,并使用参数谓词来检查请求的URL和查询参数。如果参数匹配,我们将使用req.flush
函数来模拟HTTP响应。
请注意,HttpTestingController
会自动管理用于拦截HTTP请求的模拟XHR。在每个测试之后,请使用httpTestingController.verify
函数来验证没有未处理的请求。