1

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);
});

1 Answer 1

1

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.

Sign up to request clarification or add additional context in comments.

5 Comments

ok, but shouldn't it run expect right after click and then selectedHero = hero; ?
Your error is an IDE warning I think, you can fix this by adding = null; at selectedHero declaration. The expectation is after the event trigger because the subscribe does not actually trigger the event, it's here to receive data when this event gets triggered. Which is what is done using heroEl.triggerEventHandler('click', null); once the sobscription is created.
yeah, I figured that one too. Error was cause by strictNullChecks. But the part I don't get it is when we run the code, if we run expect first, how can we get selectedHero = hero. Shouldn't it be async ? Let's say there is a debounceTime in event handler in component for 500. It will always run expect first then run ` selectedHero = hero;`
No because the subscribe call is equivalent to "When selected will emit something, set it in my selectedHero variable", it's not an actual assignment.
I think it is an actual assignment. I just tested it with debounceTime set as 500. I need to wrap it with fakeAsync and use tick(500), so the expect will run correctly.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.