vendredi 19 janvier 2018

Test a function which body is inside subscription

sub: Subject = new Subject();

function funToTest() {
  const localSubscription = this.sub.subscribe(() => {
    this.otherFunctionToBeCalled();
    localSubscription.unsubscribe();
  });
}

How can I test whether otherFunctionToBeCalled() has been called?

it('should otherFunctionToBeCalled be called', () => {
  theComponent.funToTest();

  // doesn't work
  expect(theComponent.otherFunctionToBeCalled).toHaveBeenCalled();
  ----------------------------------------------------------------
  theComponent.sub.next('something');

  theComponent.funToTest();

  // doesn't work
  expect(theComponent.otherFunctionToBeCalled).toHaveBeenCalled();
  ----------------------------------------------------------------
  theComponent.funToTest();

  // doesn't work
  theComponent.sub.subscribe(() => {
    expect(theComponent.otherFunctionToBeCalled).toHaveBeenCalled();
  });
  ----------------------------------------------------------------
  spyOn(theComponent.sub, 'subscribe').and.callFake(() => {});

  theComponent.funToTest();
  // doesn't work
  expect(theComponent.otherFunctionToBeCalled).toHaveBeenCalled();
});

Aucun commentaire:

Enregistrer un commentaire