Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

SpyOn Service function call in constructor

I am running into an issue of trying to spy on a service function call that gets called in the constructor. The test is basic, just verifying that the function call actually gets called.

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

As for AppComponent , in the constructor it is simply calling service.start() What I think the issue is that the spyOn gets called after the component is created but how would I spy on the service before injecting it? ie:

fixture = TestBed.createComponent(AppComponent);
let service = fixture.debugElement.injector.get(TestService);
like image 258
Kenny Avatar asked Jan 12 '18 22:01

Kenny


1 Answers

It seems to me the component's constructor has been called by the time you set up the spy, so need to change the sequence a bit.

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

Ref Angular Test Bed

like image 128
Richard Matsen Avatar answered Oct 13 '22 02:10

Richard Matsen