不确定您显示的代码的确切用途,它试图测试模拟服务。覆盖问题在于组件和错误回调尚未被调用(仅在出现错误时调用)。
对于我的大多数可观察服务,我通常做的是创建一个模拟,其方法只是返回自身。模拟服务有一个subscribe
接受next
、error
和complete
回调的方法。模拟的用户可以将其配置为添加错误以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;
}
}
现在在您的测试中,您只需执行类似的操作
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();
})