Angular 2:测试http observables和fixture

时间:2016-11-25 08:57:50

标签: http angular

组件:

export class Component implements OnInit {
  private element: any;
  private data: any;

  constructor(@Inject(ElementRef) private elementRef: ElementRef, private service: Service) {}

  ngOnInit() {
    this.element = select(this.elementRef.nativeElement);
    this.service.getData().subscribe((data: Data) => {
      this.data = data;
    });
  }
}

组件测试:

describe('Component', () => {
  let component;
  beforeEach(() => {
    TestBed.configureTestingModule({
      providers: [Component, Service],
      imports: [TestModule]
    });

    let fixture = TestBed.createComponent(Component);
    component = fixture.componentInstance;
    fixture.detectChanges();
  });

  let data = {};
  it('should get data',
     async(inject([MockBackend], (backend) => {
       backend.connections.subscribe((connection) => {
         connection.mockRespond(new Response(new ResponseOptions({status: 200, body: data})));
       });
       component.ngOnInit();
       expect(component.data).toHaveEqualContent(data);
     })));
});

getData() observable无法解析,测试将失败,并显示以下错误:

  

TypeError:无法读取未定义的属性'json'

当我丢失夹具并将Component注入测试时,测试将无法处理ElementRef并失败并显示:

  

失败:this.querySelector不是函数

如何测试http observable与灯具的组合?

0 个答案:

没有答案