首页 > 解决方案 > Angular 8 Jasmine 间谍和不同类型的 returnValue

问题描述

我的 REST 服务由 openapi-generator-cli 生成。所以生成的服务看起来像:

public list([...paramaters]): Observable<Array<CustomObject>>;
public list([...paramaters]): Observable<HttpResponse<Array<CustomObject>>>;
public list([...paramaters]): Observable<HttpEvent<Array<CustomObject>>>;
public list([...paramaters]): Observable<any> {
    [generated service code here]
}

我的问题是当我想测试服务时:

const httpServiceSpy = jasmine.createSpyObj('HttpCustomObjectService', [
    'list',
    'create',
  ]);

if('should', () => {
    const listOfValues: CustomObject[] = [value];
    httpService.list.and.returnValue(of(listOfValues));
})

我什至无法建造,因为我总是有:

Argument of type 'Observable<CustomObject[]>' is not assignable to parameter of type 'Observable<HttpEvent<CustomObject[]>>'

我可以写:

httpService.list.and.returnValue(of(new HttpResponse({ body: listOfValues})));

但我的代码的其余部分失败原因不是期望 Observable< HttpEvent< Array< CustomObject>>> 而是 Observable< Array< CustomObject>>

有没有办法在所有可能的自动生成之间选择“returnValue”的返回类型?

标签: angularjasmineopenapi-generator

解决方案


您可以使用as any,以便 TypeScript 了解您对类型不一致承担所有责任。

因此,您需要将代码更新为此httpService.list.and.returnValue(of(listOfValues) as any);


推荐阅读