我想只测试请求是否正在发送到正确的api端点。例如:我有一个服务向http://localhost:port/sth/sth2发送请求,我想只有在有http://localhost:port的时候chcek。我正在使用HttpTestingController和expectOne函数,有可能吗?
这是你想要做的事情吗?
建立
let httpClient: HttpClient;
let httpTestingController: HttpTestingController;
beforeEach(() => {
TestBed.configureTestingModule({
imports: [ HttpClientTestingModule ]
});
httpClient = TestBed.get(HttpClient);
httpTestingController = TestBed.get(HttpTestingController);
});
测试
it('can test HttpClient.get', () => {
const testData: Data = {name: 'Test Data'};
httpClient.get<Data>('http://localhost:8085/test/suite')
.subscribe(data =>
expect(data).toEqual(testData)
);
const request = httpTestingController.expectOne(
(req: HttpRequest<any>) => req.url.includes('http://localhost:8085'));
request.flush(testData);
httpTestingController.verify();
});
这是Angular文档中的示例,除了您将函数传递给expectOne
之外,它接受一个req并返回一个布尔值,用于检查请求的url是否包含正确的端点。
当然,您将使用您的服务替换HttpClient。