mercredi 30 septembre 2020

How to make spy return an object when a function has been called?

Basically, what I want to do is letting the open function return a MatDialogRef object which should have a method afterClosed to spy on.

code.ts

private myFunction(){
    const dialogRef = this.dialog.open(***);
    this.dialogCloseSubscription$ = dialogRef
      .afterClosed()
      .subscribe(result => {
        if (result) {
          this.loadedTimeframe = new MonthInfo(
            moment()
              .year(result.year)
              .month(result.month)
              .startOf('month')
          );
          this.setLabel();
        }
      });
}

I accomplished having a spy object for the dialog, but I am not sure how to continue.

code.spec.ts

describe('code test', () => {
  const dialogSpy = jasmine.createSpyObj('MatDialog', ['close', 'open']);

  beforeEach(async(() => {
    TestBed.configureTestingModule({
      declarations: [MonthSelectorComponent],
      imports: [BrowserAnimationsModule],
      providers: [
        {
          provide: MatDialog,
          useValue: dialogSpy,
        },
      ],
    }).compileComponents();

  }));

  it('should open dialog', () => {
    spyOn(component.dialog, 'open').and.returnValue(
      jasmine.createSpyObj('MatDialogRef', ['afterClosed'])
    );
    component.openDateDialog();
  });
});

How to let my dialogSpy return a MatDialogRef object containing the afterClosed method when the open function is called?

Aucun commentaire:

Enregistrer un commentaire