带有参数的 Angular HTTP 服务调用单元测试



我有这个服务调用,我正在尝试测试

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[对象对象]"的匹配请求,没有找到。 关于传递给调用的参数的问题,我不确定如何添加它们。你能帮忙吗?

不确定 OP 是否修复了它!

expectOne(url.const + url.params) // Wrong
expectOne(url.const + '?param1=value') // should be that

可能您期待 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);
})});

可能是我迟到了,但下面的解决方案对你们有用

  1. 创建一个HttpParams对象,并在其中append()所有查询参数。
  2. 创建HttpRequest对象并为其提供适当的值。
  3. 然后拨打httpTestingController.expectOne(),如下所示
  4. 我用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();
});

相关内容

  • 没有找到相关文章

最新更新