使用 jasmine 进行 Angular Observable 错误部分单元测试

knb*_*bin 0 subscribe observable karma-jasmine angular

我的角度服务“config.service.ts”中有以下功能。我已经为此编写了一些单元测试用例,但无法覆盖订阅方法的错误部分。

getConfiguration(params){
  return new Promise((resolve, reject) => {
    try {
      this.httpService.post('getConfig', params).subscribe{
        data => {
         resolve(data);
        },
        error => {
         reject(error);
        }
      };
    } catch(error) {
     reject(error);
    }
  });
}
Run Code Online (Sandbox Code Playgroud)

以下是“config.service.spec.ts”代码。请让我知道如何覆盖相同的订阅错误部分。

it('coverage for getConfiguration()', () => {
 const service: ConfigService = Testbed.get(ConfigService);
 const param = {id: 10};
 const response = {success: true};
 const httpService: HttpService = Testbed.get(HttpService);
 spyOn(httpService, 'post').and.returnValue(of(response));
 service.getConfiguration(param).then(function() {});
 expect(service.getConfiguration).toBeTruthy();
});
Run Code Online (Sandbox Code Playgroud)

这里可观察误差部分没有被覆盖,无法达到覆盖范围。如果这里有什么不对的地方请指正。

Mik*_*keJ 5

要到达 Observable 的错误处理程序,您可以使用RxJS throwError来强制 Observable 抛出。所以你的测试可能看起来像这样:

it('rejects when post throws', async () => {
  const param = { id: 10 };
  const errorResponse = new Error('httpService.post error');
  spyOn(httpService, 'post').and.returnValue(throwError(errorResponse));

  await service.getConfiguration(param).catch(err => {
    expect(err).toBe('Subscribe error: httpService.post error');
  });
});
Run Code Online (Sandbox Code Playgroud)

这里有一个 StackBlitz展示了这种方法。

另外,关于您在问题中发布的测试,如果这是您的实际测试代码,您应该知道expect

expect(service.getConfiguration).toBeTruthy();
Run Code Online (Sandbox Code Playgroud)

总是会通过,因为service.getConfiguration是一个函数,所以它的计算结果总是为真。如果您想以某种方式验证该函数的行为,则需要调用该函数。

另外,我相信您发布的服务代码中的这一行有语法错误:

this.httpService.post('getConfig', params).subscribe{
Run Code Online (Sandbox Code Playgroud)

.subscribe在 后、左花括号之前需要一个左括号:

this.httpService.post('getConfig', params).subscribe({
Run Code Online (Sandbox Code Playgroud)

但我猜这只是构建您的问题时的复制粘贴错误。