在测试中使用HttpTestingController,并使用expectOne和flush。使用HttpClientTestingModule模拟Http请求,并实现以下测试代码:
it('should split up the query param into query params', () => {
const query = 'param1=value1¶m2=value2';
const expectedUrl = `https://api.example.com/test?${query}`;
const expectedResponse = { data: 'test' };
service.getData(query).subscribe(response => {
expect(response).toEqual(expectedResponse);
});
const req = httpTestingController.expectOne(expectedUrl);
expect(req.request.method).toEqual('GET');
req.flush(expectedResponse);
});
在该测试中,我们首先构建包含查询参数的url,然后使用模拟的Http请求检查该url是否被正确调用。接下来,我们断言调用方法为GET,并通过flush方法返回预期的响应。最后,我们使用HttpTestingController提供的expectOne方法来检查我们是否只执行了一个Http请求。