【发布时间】:2021-02-20 21:17:25
【问题描述】:
我已经看到了很多关于这个错误的问题,但是我花了今天最好的时间尝试了每个解决方案,我需要你的帮助。
我正在尝试测试这个服务,它是一个 http 获取请求
getTrainInformation(url: string): Observable<any> {
return this.http.get(url,
{
params:
{
expand: 'true'
}
}
).pipe(catchError(this.handleError));
}
这是我的测试:
import { HttpTestingController, HttpClientTestingModule } from '@angular/common/http/testing';
import { TestBed } from '@angular/core/testing';
import { TrainInformationService } from "./traininformation.service";
describe('traininformation service', () => {
let service: TrainInformationService;
let httpTestingController: HttpTestingController;
beforeEach( () => {
TestBed.configureTestingModule({
imports: [HttpClientTestingModule],
providers: [TrainInformationService]
});
service = TestBed.get(TrainInformationService);
httpTestingController = TestBed.get(HttpTestingController);
});
it('should perform a GET', () => {
const url = service.getFullUrl('BOP');
const urlParam = { param: 'expand', value: 'true'};
const urlWithParams = `${url}?${urlParam.param}=${urlParam.value}`;
service.getTrainInformation(urlWithParams).subscribe();
const req = httpTestingController.expectOne(urlWithParams);
console.log('req is ' + req);
req.flush('Some');
// httpTestingController.verify();
});
});
当测试运行时,它失败了:
错误:预期有一个条件匹配请求“匹配 URL: >,没有找到。
如果我更改测试以便注释掉对 expectOne 的调用并刷新并调用 verify,那么测试变为:
it('should perform a GET', () => {
const url = service.getFullUrl('BOP');
const urlParam = { param: 'expand', value: 'true'};
const urlWithParams = `${url}?${urlParam.param}=${urlParam.value}`;
service.getTrainInformation(urlWithParams).subscribe();
// const req = httpTestingController.expectOne(urlWithParams);
// console.log('req is ' + req);
// req.flush('Some');
httpTestingController.verify();
});
我现在看到的错误是:
错误:预期没有打开的请求,发现 1:GET >
我做错了什么?
【问题讨论】:
标签: angular unit-testing http jasmine