使用服务中的observable测试错误情况

use*_*550 22 typescript karma-coverage angular2-testing angular2-observables angular

假设我有一个订阅服务功能的组件:

export class Component {

   ...

    ngOnInit() {
        this.service.doStuff().subscribe(
            (data: IData) => {
              doThings(data);
            },
            (error: Error) => console.error(error)
        );
    };
};
Run Code Online (Sandbox Code Playgroud)

订阅调用将两个匿名函数作为参数,我已设法为数据函数设置工作单元测试,但Karma不接受错误一的覆盖.

在此输入图像描述

我已经尝试过监视console.error函数,抛出一个错误,然后期待调用间谍已被调用,但这并没有完全做到.

我的单元测试:

spyOn(console,'error').and.callThrough();

serviceStub = {
        doStuff: jasmine.createSpy('doStuff').and.returnValue(Observable.of(data)),
    };

    serviceStub.doStuff.and.returnValue(Observable.throw(

        'error!'
    ));

serviceStub.doStuff().subscribe(

    (res) => {

        *working test, can access res*
    },
    (error) => {

      console.error(error);
      console.log(error);  //Prints 'error!' so throw works.
      expect(console.error).toHaveBeenCalledWith('error!'); //Is true but won't be accepted for coverage.
    }
);
Run Code Online (Sandbox Code Playgroud)

测试这些匿名函数的最佳实践是什么?确保测试覆盖率的最低要求是什么?

Ani*_*Das 33

你可以简单地模拟Observable抛出错误对象,Observable.throw({status: 404})并测试observable的错误块.

const xService = fixture.debugElement.injector.get(SomeService);
const mockCall = spyOn(xService, 'method')
                       .and.returnValue(Observable.throw({status: 404}));
Run Code Online (Sandbox Code Playgroud)

  • 对rxjs> = v6使用`import {throwError} from'rxjs'`,然后使用`returnValue(throwError({status:404}));;`。 (14认同)

Pau*_*tha 16

不确定您正在显示的代码的目的,即尝试测试模拟服务.覆盖问题是组件和错误回调未被调用(仅在出现错误时调用).

我通常对大多数可观察服务所做的是创建一个模拟方法,它的方法只会返回自己.模拟服务有一个subscribe接受的方法next,errorcomplete回调.模拟的用户可以将其配置为添加错误,以便error调用函数或添加数据,以便next调用该方法.我最喜欢这个的是它都是同步的.

下面是我通常使用的东西.它只是一个抽象类,可以扩展其他模拟.它提供了可观察提供的基本功能.扩展模拟服务应该只添加它需要的方法,在方法中返回自己.

import { Subscription } from 'rxjs/Subscription';

export abstract class AbstractMockObservableService {
  protected _subscription: Subscription;
  protected _fakeContent: any;
  protected _fakeError: any;

  set error(err) {
    this._fakeError = err;
  }

  set content(data) {
    this._fakeContent = data;
  }

  get subscription(): Subscription {
    return this._subscription;
  }

  subscribe(next: Function, error?: Function, complete?: Function): Subscription {
    this._subscription = new Subscription();
    spyOn(this._subscription, 'unsubscribe');

    if (next && this._fakeContent && !this._fakeError) {
      next(this._fakeContent);
    }
    if (error && this._fakeError) {
      error(this._fakeError);
    }
    if (complete) {
      complete();
    }
    return this._subscription;
  }
}
Run Code Online (Sandbox Code Playgroud)

现在在你的测试中你只需要做类似的事情

class MockService extends AbstractMockObservableService {
  doStuff() {
    return this;
  }
}

let mockService;
beforeEach(() => {
  mockService = new MockService();
  TestBed.configureTestingModule({
    providers: [{provide: SomeService, useValue: mockService }],
    declarations: [ TestComponent ]
  });
});
it('should call service success', () => {
  mockService.content = 'some content';
  let fixture = TestBed.createComponent(TestComponent);
  // test component for success case
});
it('should call service error', () => {
  mockService.error = 'Some error';
  let fixture = TestBed.createComponent(TestComponent);
  // test component for error case
  // this should handle your coverage problem
});

// this assumes you have unsubscribed from the subscription in your
// component, which you should always do in the ngOnDestroy of the component
it('should unsubscribe when component destroyed', () => {
  let fixture = TestBed.createComponent(TestComponent);
  fixture.detectChanges();
  fixture.destroy();
  expect(mockService.subscription.unsubscribe).toHaveBeenCalled();
})
Run Code Online (Sandbox Code Playgroud)