无法读取Angular Test Mock的属性'subscribe'

Dan*_*bes 7 dependency-injection mocking jasmine rxjs angular

我正在尝试对具有注入服务的Angular组件进行单元测试.在组件的构造函数中,调用注入服务的方法,该方法返回Observable.我正在尝试在组件的单​​元测试中模拟服务,但我一直遇到这个错误:TypeError: Cannot read property 'subscribe' of undefined.

我试图通过以下方式模拟服务:

const serviceStub = {
  getObservable: () => { return {subscribe: () => {}}; },
};

beforeEach(async(() => {
  TestBed.configureTestingModule({
    providers: [
      {provide: MyService, useValue: serviceStub}
    ]
})


it('should create', () => {
  spyOn(serviceStub, 'getObservable').and.returnValue({subscribe: () => {}});
  expect(component).toBeTruthy();
});
Run Code Online (Sandbox Code Playgroud)

感觉我错过了一些明显的东西.有人可以指出来吗?

UPDATE

即使我在我的测试床提供商中注入实际服务,我也会收到此错误.

组件的构造函数看起来像这样:

private _subscription: Subscription;

constructor(private _service: MyService) {
  this._subscription = _service.getObservable().subscribe(console.log);
}
Run Code Online (Sandbox Code Playgroud)

Jul*_*ova 5

使用注入来注入服务并模拟它不存根

it('should create', inject([MyService], (myService: MyService) => {
  spyOn(myService, 'getObservable').and.returnValue({subscribe: () => {}});
  expect(component).toBeTruthy();
}));
Run Code Online (Sandbox Code Playgroud)

这是完整版本:

零件:

@Component({
  selector: 'my-cmp',
  template: 'my cmp {{x}}'
})
export class MyComponent {
  x;

  constructor(private myService: MyService) {
    this.myService.getObservable()
      .subscribe(x => {
        console.log(x);
        this.x = x;
      });
  }
}
Run Code Online (Sandbox Code Playgroud)

测试:

   describe('my component test', () => {
    let fixture: ComponentFixture<MyComponent>, comp: MyComponent, debugElement: DebugElement, element: HTMLElement;

    beforeEach(async(() => {
      TestBed.configureTestingModule({
        declarations: [MyComponent],
        providers: [MyService]
      });
    }));

    beforeEach(() => {
      fixture = TestBed.createComponent(MyComponent);
      comp = fixture.componentInstance;
      debugElement = fixture.debugElement;
      element = debugElement.nativeElement;
    });

    it('should create', inject([MyService], (myService: MyService) => {
      expect(comp).toBeTruthy();
    }));

    it('should set value', async(inject([MyService], (myService: MyService) => {
      spyOn(myService, 'getObservable').and.returnValue(Observable.of(1));

      fixture.detectChanges();

      fixture.whenStable().then(() => {
        expect(comp.x).toEqual(1);
      });
    })));
  });
Run Code Online (Sandbox Code Playgroud)