【问题标题】:Mocking generated API service模拟生成的 API 服务
【发布时间】:2022-03-10 05:06:44
【问题描述】:

在我们的 Angular 应用程序中,我们正在使用从 API 生成的服务,并且我们面临着对使用它们的组件或自定义服务进行单元测试的问题。

// Generated code
getCurrentConnection(observe?: 'body', reportProgress?: boolean, options?: {
    httpHeaderAccept?: '*/*';
}): Observable<ConnectionResultDto>;
getCurrentConnection(observe?: 'response', reportProgress?: boolean, options?: {
    httpHeaderAccept?: '*/*';
}): Observable<HttpResponse<ConnectionResultDto>>;
getCurrentConnection(observe?: 'events', reportProgress?: boolean, options?: {
    httpHeaderAccept?: '*/*';
}): Observable<HttpEvent<ConnectionResultDto>>;

在定制服务中的使用

public getConnection(): Observable<ConnectionResultDto> {
  return this.connectionServiceAPI.getCurrentConnection('body').pipe(tap(res => this.updateConnectionStatus(res)));
}

并尝试在单元测试中模拟它(我们使用 Jest + Spectator + Ng-Mocks)

describe('ConnectionService', () => {
  let spectator: SpectatorHttp<ConnectionService>;
  const createHttp = createHttpFactory({
    service: ConnectionService,
    providers: [
      MockProvider(ConnectionControllerService, {
        getCurrentConnection: ('body') => of(CONNECTION_MOCK) // this throws error displayed below
      }),
    ],
  });

这是我们得到的错误(VS Code 下划线)

No overload matches this call.
  Overload 1 of 3, '(instance: AnyType<ConnectionControllerService>, overrides?: Partial<ConnectionControllerService>): FactoryProvider', gave the following error.
    Type 'string' is not assignable to type '{ (observe?: "body", reportProgress?: boolean, options?: { httpHeaderAccept?: "*/*"; }): Observable<ConnectionResultDto>; (observe?: "response", reportProgress?: boolean, options?: { ...; }): Observable<...>; (observe?: "events", reportProgress?: boolean, options?: { ...; }): Observable<...>; }'.
  Overload 2 of 3, '(provider: string | InjectionToken<{ getCurrentConnection: string; }>, useValue?: Partial<{ getCurrentConnection: string; }>): FactoryProvider', gave the following error.
    Argument of type 'typeof ConnectionControllerService' is not assignable to parameter of type 'string | InjectionToken<{ getCurrentConnection: string; }>'.
      Type 'typeof ConnectionControllerService' is missing the following properties from type 'InjectionToken<{ getCurrentConnection: string; }>': _desc, ɵprov
  Overload 3 of 3, '(provider: string, useValue?: Partial<{ getCurrentConnection: string; }>): FactoryProvider', gave the following error.
    Argument of type 'typeof ConnectionControllerService' is not assignable to parameter of type 'string'.ts(2769)
connectionController.service.d.ts(45, 5): The expected type comes from property 'getCurrentConnection' which is declared here on type 'Partial<ConnectionControllerService>'
(method) getCurrentConnection?(observe?: "body", reportProgress?: boolean, options?: {
    httpHeaderAccept?: "*/*";
}): Observable<ConnectionResultDto> (+2 overloads)

知道如何正确地模拟它吗?我尝试指定 getCurrentConnection 方法的每个可选参数,但没有任何效果。由于未定义结果上的pipe 运算符,没有覆盖方法的模拟将使单元测试失败。

【问题讨论】:

  • ('body') =&gt; of(CONNECTION_MOCK) 不是箭头函数的有效语法,参数需要 name。
  • 我没有想出箭头函数的工作版本。应该怎么写?

标签: angular typescript jestjs ng-mocks


【解决方案1】:

这里的问题是 typescript 聚合了所有参数和所有返回类型。因此,它的 mock 也应该遵循聚合类型。

在这种情况下,(_: 'body') =&gt; of(CONNECTION_MOCK) 只是 3 中的 1。 Typescript 期望 _ 为 'body' | 'response' | 'events',返回类型也是如此:应该尊重所有 3。

所有这些都导致使用as never 更简单,因为很难实现所需的回调。

MockProvider(ConnectionControllerService, {
  getCurrentConnection: (_: 'body') => of(CONNECTION_MOCK),
} as never); // as never

或更弱的选择

// jasmine
MockProvider(ConnectionControllerService, {
  getCurrentConnection: jasmine
    .createSpy()
    .and.returnValue(of(CONNECTION_MOCK)),
});

// jest
MockProvider(ConnectionControllerService, {
  getCurrentConnection: jest
    .fn()
    .mockReturnValue(of(CONNECTION_MOCK)),
});

【讨论】:

  • 非常感谢!两个选项都有效
猜你喜欢
  • 1970-01-01
  • 2016-10-17
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2021-05-14
  • 1970-01-01
  • 2021-05-14
  • 2019-07-20
相关资源
最近更新 更多