如何在ng2中测试使用karma订阅

时间:2017-03-16 12:02:37

标签: angular karma-runner

从服务我得到一些流,所以在我的组件中我得到这样:

this.service.getSome().subscribe(x => this.invokeHere(x));

在我的spec文件中,我有类似的东西

beforeEach(() => {
    fixture = TestBed.createComponent(SomeComponent);
    component = fixture.componentInstance;

    service = fixture.debugElement.injector.get(Service);
    spy = spyOn(service, 'getSome')
        .and.returnValue(Observable.of(serviceStub));

    fixture.detectChanges();
});

1 个答案:

答案 0 :(得分:1)

it('test observable', inject([MockBackend], (mockBackend: MockBackend) => {
    mockBackend.connections.subscribe((connection: MockConnection) => {
      connection.mockError(new Error());
    });
    service.someRequest()
      .subscribe(() => { },(err) => {
        // your test
      });
  }));