Stopping event's propagation does not work in angular 2+ unit tests

277 Views Asked by At

I am trying to write a unit test for Angular 4 that uses event propagation stopping.

Here is a simple scenario - we register 3 listeners and call event.stopImmediatePropagation() in the first listener. Then we fire an event and expect two last listeners not to be called. But they are called.

describe('Events Testing Demo', () => {
  let count = 0;

  it('should test listeners', () => {
    document.body.addEventListener('click', (event: MouseEvent) => {
      event.stopImmediatePropagation();
      console.log('listener 1 running');
      count++;
      event.stopImmediatePropagation();
    });

    document.body.addEventListener('click', (event: MouseEvent) => {
      console.log('listener 2 running');
      count++;
    });

    document.body.addEventListener('click', (event: MouseEvent) => {
      console.log('listener 3 running');
      count++;
    });

    document.body.dispatchEvent(new Event('click'));

    expect(count).toEqual(1); // because of event.stopImmediatePropagation() in the 1st listener
  });
});

This describe block can be added to any "hello world" app generated by Angular CLI, to see it in action.

But everything works fine in Jasmine Standalone test (directly in browser, without Angular), so it seem to be Angular-specific issue.

Or maybe this is not a correct way to test DOM events in Angular?

0

There are 0 best solutions below