我正在尝试测试此服务呼叫
get(): Observable<Country[]> { const config = { params: new HttpParams().set('pagesize', '300') }; return this.http .get<any>(`${api_url}countries`, config) .pipe(map(response => (response.data as Country[]))); }
这是测试:
describe('CountriesService Tests', () => {
let countriesService: CountriesService;
let httpTestingController: HttpTestingController;
let countries: Country[] = [
{ Country: 'ALBANIA', CountryCode: 'AL', ReportingCountryCode: 'ALB' },
{ Country: 'Canada', CountryCode: 'CA', ReportingCountryCode: 'CND' }];
beforeEach(() => {
TestBed.configureTestingModule({
imports: [HttpClientTestingModule],
providers: [CountriesService]
});
countriesService = TestBed.get(CountriesService);
httpTestingController = TestBed.get(HttpTestingController);
});
afterEach(() => {
httpTestingController.verify();
});
it('should return all countries', () => {
countriesService.get().subscribe((data: Country[]) => {
expect(data).toBe(countries);
});
const url = ({ const: environment.url + 'countries', params: {'pagesize': '300'}});
let countriesRequest: TestRequest = httpTestingController.expectOne(url.const + url.params);
expect(countriesRequest.request.method).toEqual('GET');
countriesRequest.flush(countries);
})});
我收到此错误:错误:预期对标准“匹配URL:/ api / publicdata / countries [对象对象]”的一个匹配请求,未找到任何请求。 这是我们传递给调用的参数问题,我不确定如何添加它们。你能帮忙吗?
答案 0 :(得分:1)
不确定OP是否已修复!
expectOne(url.const + url.params) // Wrong
expectOne(url.const + '?param1=value') // should be that
答案 1 :(得分:0)
创建http调用后,您可能会期待它,请尝试以下测试用例
it('should return all countries', () => {
const url = ({ const: environment.url + 'countries', params: {'pagesize': '300'}});
let countriesRequest: TestRequest = httpTestingController.expectOne(url.const + url.params);
countriesService.getCountries().subscribe((data: Country[]) => {
expect(data).toBe(countries);
});
expect(countriesRequest.request.method).toEqual('GET');
countriesRequest.flush(countries);
})});
答案 2 :(得分:0)
可能我来晚了,但是下面的解决方案适用于你们
HttpParams
对象,并在其中append()
您的所有查询参数。HttpRequest
对象并为其提供适当的值。httpTestingController.expectOne()
urlWithParams
来比较网址,因为它减少了检查每个网址的代码
参数对象。 it('should return all countries', fakeAsync(() => {
countriesService.getCountries().subscribe((data: Country[]) => {
expect(data).toBe(countries);
});
// you can create multiple parameters by appending on same object
let parameters = new HttpParams().append('pagesize', '30');
// environment is your base url
const httpReq = new HttpRequest('GET',environment.url, {params:parameters});
let countriesRequest = httpTestingController.expectOne((req:HttpRequest)=>
req.method === httpReq.method && req.urlWithParams === httpReq.urlWithParams
);
countriesRequest.flush(countries);
httpTestingController.verify();
});