vendredi 26 juillet 2019

Isolated testing: how to test callback of an Observable

I have a component which uses a service to open a modal dialog where users can select one of two options {true, false}. I want to write isolated tests (no Testbed creation). My problem is, that the callback does not get executed at all (tests fail, because actions do not get dispatched).

How to test the behavior inside the callback?

bla.component.ts
    onCancelClicked(): void {
    this.unsavedChangesService.openUnsavedChangesModal().subscribe((leaveWithoutSaving: boolean) => {

            if (leaveWithoutSaving) {
                if (!this.savedChangesExisting()) {
                  this.store.dispatch(new DeleteDraft(this.id));
                } else {
                  this.store.dispatch(new ResetUnsavedChanges());
                }
                this.store.dispatch(new DeactivateEditMode());
              }
        });
    }
  }


    let unsavedChangesServiceMock: any  = {
      openUnsavedChangesModal: jasmine.createSpy().and.returnValue({
        subscribe: jasmine.createSpy().and.returnValue(of(true))
      })
    };


....

it('bla', () => {
      const expectedDeactivateEditModeAction: any = new DeactivateEditMode();

      sut['unsavedChanges'] = {[1]: 'something' };
      sut['draftsOfTTB'] = undefined;

      sut.onCancelClicked();

      expect(sut.store.dispatch).toHaveBeenCalledWith(expectedDeactivateEditModeAction);
}
....

Aucun commentaire:

Enregistrer un commentaire