maxisam
maxisam

Reputation: 22705

unit test example on angular.io

in document

  it('should raise selected event when clicked', () => {
    let selectedHero: Hero;
    comp.selected.subscribe((hero: Hero) => selectedHero = hero);

    heroEl.triggerEventHandler('click', null);
    expect(selectedHero).toBe(expectedHero);
  });

Shouldn't it be like

comp.selected.subscribe((hero: Hero) => {
  selectedHero = hero;
  expect(selectedHero).toBe(expectedHero);
});

Upvotes: 1

Views: 86

Answers (1)

Supamiu
Supamiu

Reputation: 8731

It can't be like this because of jasmine.

If you do:

it('should raise selected event when clicked', () => {
    let selectedHero: Hero;
    comp.selected.subscribe((hero: Hero) => {
      selectedHero = hero;
      expect(selectedHero).toBe(expectedHero);
    });

    heroEl.triggerEventHandler('click', null);
});

And, because of a bug, the event click is not caught, then your expectation will never be tested, and you don't have a failure.

By testing selectedHero after the click, the tests ensures that if the click event is not handled, the test will fail because selectedHero will be undefined.

Upvotes: 1

Related Questions