title: Error 'Cannot read property 'triggerEventHandler' of null' in Karma unit testing
body: <p>I am trying to test if a closeModal function in a Modal component is working when clicking a "close button" on the modal, however this test shows my button element as null. I am getting the error "Cannot read property 'triggerEventHandler' of null." How can I resolve this?</p>
  
  <p>modal.component.ts</p>
  
  <pre><code>import { AppComponent } from "./../app.component";
  import { async, ComponentFixture, TestBed } from "@angular/core/testing";
  import { ModalComponent } from "./modal.component";
  import { By } from '@angular/platform-browser';
  
  describe("ModalComponent", () =&gt; {
    let component: ModalComponent;
    let fixture: ComponentFixture&lt;ModalComponent&gt;;
  
    beforeEach(
      async(() =&gt; {
        TestBed.configureTestingModule({
          declarations: [ModalComponent, AppComponent]
        }).compileComponents();
      })
    );
  
    beforeEach(() =&gt; {
      fixture = TestBed.createComponent(ModalComponent);
      component = fixture.componentInstance;
      fixture.detectChanges();
    });
  
    it("should create", () =&gt; {
      expect(component).toBeTruthy();
    });
  
    it("should test closeModal method on close button", () =&gt; {
      spyOn(component, "closeModal")
      let el = fixture.debugElement.query(By.css('#close'))
      el.triggerEventHandler('click', null)
  
      fixture.detectChanges()
  
      fixture.whenStable().then(() =&gt; {
        expect(component.closeModal).toHaveBeenCalled();
      });
    });
  });
  </code></pre>
  
  <p>modal.component.html</p>
  
  <pre><code>&lt;div class="ds-c-dialog-wrap"[ngClass]="hideModal ? 'hide' : 'show'"&gt;
    &lt;div&gt;
      &lt;header role="banner"&gt;
        &lt;h1 id="dialog-title"&gt;{{modalTitle}}&lt;/h1&gt;
        &lt;button
        id="button"
        (click)="closeModal()"
        *ngIf="enableClose"&gt;Close&lt;/button&gt;
      &lt;/header&gt;
      &lt;main&gt;
        &lt;p class="ds-text"&gt;
          {{modalBody}}
      &lt;/main&gt;
      &lt;aside role="complementary"&gt;
        &lt;button&gt;Dialog action&lt;/button&gt;
        &lt;button *ngIf="enableCancel" (click)="closeModal()"&gt;Cancel&lt;/button&gt;
      &lt;/aside&gt;
    &lt;/div&gt;
  &lt;/div&gt;
  </code></pre>