angular - 在Angular 6中测试httpClient的继承
问题描述
我在 ng 项目中扩展了 httpClient,以便为选项添加自定义参数。(这在我的应用程序中运行良好)
我的新服务如下所示:
export class CustomHttpClient extends HttpClient {
request(first: string | HttpRequest<any>, url?: string, options: CustomHttpOptions = {}): Observable<any> {
const res = super.request(first as string, url, options);
res.subscribe(
() => { // Success
// Some action on success
},
() => { // error
// Some action on error
}
);
return res;
}
post(url: string, body: any | null, options: CustomHttpOptions = {}): Observable<any> {
return this.request('POST', url, addBody(options, body));
}
put(url: string, body: any | null, options: CustomHttpOptions = {}): Observable<any> {
return this.request('PUT', url, addBody(options, body));
}
patch(url: string, body: any | null, options: CustomHttpOptions = {}): Observable<any> {
return this.request('PATCH', url, addBody(options, body));
}
}
function addBody<T>(options: CustomHttpOptions, body: T | null) {
const opts = { ...options, body };
return opts;
}
export interface CustomHttpOptions {
body?: any;
headers?: HttpHeaders | { [header: string]: string | string[]; };
observe?: 'body' | HttpObserve | any;
params?: HttpParams | { [param: string]: string | string[]; };
reportProgress?: boolean;
responseType?: 'arraybuffer' | 'blob' | 'json' | 'text' | any;
withCredentials?: boolean;
customParameter?: boolean;
}
我正在尝试对这个自定义实现进行单元测试,但在 expectOne 中出现以下错误
错误:应为条件“按功能匹配:”提供一个匹配请求,但找到了 2 个请求。
这是我正在做的单元测试
describe('CustomHttpClient', () => {
const httpOptions: CustomHttpOptions = {
CustomParameter: true
};
beforeEach(() => {
TestBed.configureTestingModule({
imports: [HttpClientTestingModule],
providers: [CustomHttpClient]
});
});
afterEach(inject([HttpTestingController], (httpMock: HttpTestingController) => {
httpMock.verify();
}));
it('receive the optional parameter for a GET method', inject([CustomHttpClient, HttpTestingController], (http: CustomHttpClient, httpMock: HttpTestingController) => {
http.get('/data', httpOptions).subscribe(
response => {
expect(response).toBeTruthy();
}
);
const req = httpMock.expectOne((request: HttpRequest<any>) => {
return request.method === 'GET';
});
expect(req.request.method).toEqual('GET');
httpMock.verify();
}));
});
我错过了什么?
解决方案
找出错误,我在自定义请求中使用的订阅方法导致重复调用,所以这解决了问题:
super.request(first as string, url, options).pipe(share());
推荐阅读
- c# - 如何在 ASP.NET Core 的 OData 中导航/配置从复杂类型到实体类型的导航?
- spring-boot - 为什么 jms 客户端确认不起作用
- apache-spark - 是否可以通过 mlflow 加载 Scala/Spark PipelineModel?
- python - python分析mongodb数据时操作DBRef数据的问题
- r - 使 Highchart R 成为 Shiny 中盒子的全宽和全高
- kubernetes - 我总是在 GKE 中得到 502
- mongodb - 恢复 MongoDB 时遇到问题
- python-3.x - 在我的表单中使用另一个模型的字段时如何将数据插入我的数据库?
- python - 如何从 CSV 文件列创建列表?
- google-maps - 使用 gcloud alpha CLI 为 API 密钥添加限制