mercredi 12 février 2020

How to test if subscriber is called in angular?

I have a component which is subscribing to a global fanout created by a service, and I wish to test if the fanout indeed is being correctly received. So, looking at code below, I wish to test if eventStartFanout$ is being called within the TestableComponent.

I know the code is actually working by doing 'manual tests' = using my eyes, but I don't know how to translate it to automated tests.

Minimized example of my current problem;

service:

eventStartSubject = new Subject<any>();
eventStartFanout$ = this.eventStartSubject.asObservable();
function startEvent() {
  this.eventStartSubject.next();
}

testable-component:

ngOnInit() {
  this.unchanged = true;
  this.fanoutService.eventStartFanout$.subscribe(
    _ => {
      // Test that it reaches here when service triggers
      this.changeVariable();
    }
  );
}

// Extra (unneeded) function to potentially help testing
function changeVariable(){
  this.unchanged = false;
}

My current attempt of test:

beforeEach(() => {
    fixture = TestBed.createComponent(TestableComponent);
    component = fixture.componentInstance;
    fixture.detectChanges();
  });

it('should do something when fanout happens', async(() => {
    const fanoutService: FanoutService = TestBed.get(FanoutService);
    component.unchanged = true;
    spyOn(component, 'changeVariable');
    // It should trigger the subscriber here and change component.unchanged
    fanoutService.startEvent();
    fixture.detectChanges();
    expect(component.unchanged).toBeFalsy();
  }));

Aucun commentaire:

Enregistrer un commentaire