【发布时间】:2019-12-11 15:22:33
【问题描述】:
我正在尝试测试此服务调用
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]”的匹配请求,但没有找到。 我们关于传递给调用的参数的问题,我不知道如何添加它们。你能帮忙吗?
【问题讨论】:
-
这可能是一个错字,但服务方法是 get() 但您实际上并没有在测试中调用该特定方法,而是调用 getCountries() 。同样是的,您不能将对象插入到这样的字符串中。使用模板字符串或字符串连接来提取您期望的特定属性。
+ '?pagesize' + params.pagesize或类似的。将其与正在运行的应用程序将 url 转换成的内容相匹配。 -
这是一个错字谢谢
-
将
expectOne与 GET 参数一起使用很痛苦。我发现使用expectOne(angular.io/api/common/http/testing/HttpTestingController) 的matchFn重载更容易。它接收HttpRequest对象,因此您可以轻松比较基本url和参数值 -
请举例,我看不到matchFn函数,只能匹配
标签: angular unit-testing jasmine karma-runner