[英]angular http service call unit test with params
我正在嘗試測試此服務呼叫
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[object Object]”的匹配請求,未找到。 關於傳遞給調用的參數的問題,我不知道如何添加它們。 你能幫忙嗎?
不確定 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);
})});
可能是我遲到了,但下面的解決方案對你們有用
HttpParams
對象append()
所有查詢參數添加到其中。HttpRequest
對象並為其提供適當的值。httpTestingController.expectOne()
如下所示urlWithParams
來比較 url,因為它減少了檢查每個 param 對象的代碼。 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();
});
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.