无法阅读财产'订阅'角度测试模拟

时间:2017-05-05 04:49:13

标签: angular dependency-injection jasmine mocking rxjs

我试图对具有注入服务的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();
});

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

更新

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

组件的构造函数如下所示:

private _subscription: Subscription;

constructor(private _service: MyService) {
  this._subscription = _service.getObservable().subscribe(console.log);
}

1 个答案:

答案 0 :(得分:3)

使用inject注入服务并模拟它而不是存根

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

这是完整版:

成分:

@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;
      });
  }
}

试验:

   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);
      });
    })));
  });