构造函数

时间:2018-01-12 22:18:17

标签: angular unit-testing jasmine karma-jasmine

我遇到了一个试图窥探在构造函数中调用的服务函数调用的问题。测试是基本的,只是验证函数调用实际被调用。

 beforeEach(async(() => {
    TestBed.configureTestingModule({
      declarations: [
        AppComponent
      ],
      providers: [TestService]
    }).compileComponents();
  }));

beforeEach(() => {

    fixture = TestBed.createComponent(AppComponent);
    let service = fixture.debugElement.injector.get(TestService);

    component = fixture.componentInstance;
    spyOn(service , "start").and.callThrough();

    fixture.detectChanges();
  });

 it('start gets called', () => {

    expect(service .start).toHaveBeenCalled();
  })

对于AppComponent,在构造函数中它只是调用service.start() 我认为问题是spyOn在创建组件后被调用但是在注入之前我会如何监视服务呢?即:

fixture = TestBed.createComponent(AppComponent);
let service = fixture.debugElement.injector.get(TestService);

1 个答案:

答案 0 :(得分:5)

在我看来,在你设置间谍时已经调用了组件的构造函数,所以需要稍微更改一下序列。

beforeEach(() => {
  let service = TestBed.get(TestService);
  spyOn(service , "start").and.callThrough();
  fixture = TestBed.createComponent(AppComponent);
  component = fixture.componentInstance;
  fixture.detectChanges();
});

参考Angular Test Bed