title: Testing window click and contextmenu events in Angular service with Karma
body: <p>I am working on my library <a href="https://github.com/kayvanbree/contexr" rel="nofollow noreferrer">Contexr</a> and I need to test the window's click and contextmenu events. I want to spy on one of my services and check if some methods are called using a spyOn. I tried several ways using fakeAsync, tick and fixture.detectChanges, but my methods are never called. I know that my events are added, because the method that adds the event listeners is being called. My initialize method looks like this:</p>
  
  <pre><code>public initialize() {
    window.addEventListener('click', (event: MouseEvent) =&gt; {
      this.close();
    });
    window.addEventListener('contextmenu', (event: MouseEvent) =&gt; {
      this.contexr.addCurrentContext('all', null);
      this.open(event, {
        context: this.contexr.getCurrentContext(),
        top: event.clientY,
        left: event.clientX
      });
    });
  }
  </code></pre>
  
  <p>The spec file looks like this:</p>
  
  <pre><code>describe('ContextMenuService', () =&gt; {
    let contextMenuService: ContextMenuService;
    let fixture: ComponentFixture&lt;ContextDirectiveTestComponent&gt;;
    let element: DebugElement;
    let contexr: ContexrMockService;
  
    beforeEach(() =&gt; {
      contexr = new ContexrMockService();
  
      TestBed.configureTestingModule({
        declarations: [ ContextDirectiveTestComponent ],
        providers: [
          ContextMenuService,
          { provide: Overlay, useClass: OverlayMock },
          { provide: ContexrService, useValue: contexr }
        ]
      });
  
      fixture = TestBed.createComponent(ContextDirectiveTestComponent);
      contexr = TestBed.get(ContexrService);
      element = fixture.debugElement.query(By.css('div'));
      contextMenuService = TestBed.get(ContextMenuService);
      contextMenuService.initialize();
    });
  
    it('should react to window clicks', fakeAsync(() =&gt; {
      spyOn(contexr, 'addCurrentContext').and.callThrough();
      element.triggerEventHandler('click', null);
      tick(1000);
      fixture.detectChanges();
      expect(contexr.addCurrentContext).toHaveBeenCalled();
    }));
  });
  </code></pre>
  
  <p>So, once again I'm asking smarter people on the internet. What is wrong with this test? The click handlers work in the actual application, but I really want to get my code coverage up to ~100% before I will even think of releasing 2.0.0. </p>