title: Angular Jasmine Expected spy onButtonClick to have been called
body: <p>I am writing unit test for my Angular 6 project. 
  However, I encounter a problem. I want to test a button with click function called, but the test file always shows me this error.</p>
  
  <p>The following are my code:</p>
  
  <p>HTML:</p>
  
  <pre><code>&lt;div&gt;
   &lt;button (click)="onButtonClick(1)"&gt;&lt;button&gt;
   &lt;button (click)="onButtonClick(2)"&gt;&lt;button&gt;
   &lt;button (click)="onButtonClick(3)"&gt;&lt;button&gt;
  &lt;/div&gt;
  </code></pre>
  
  <p>comp.ts:</p>
  
  <pre><code>onButtonClick(key: number) {
    do something
  }
  </code></pre>
  
  <p>spec.ts</p>
  
  <pre><code>import { async, ComponentFixture, TestBed, fakeAsync } from '@angular/core/testing';
  
  import { PanelButtonsComponent } from './panel-buttons.component';
  import { By } from "@angular/platform-browser";
  
  describe('PanelButtonsComponent', () =&gt; {
  let component: PanelButtonsComponent;
  let fixture: ComponentFixture&lt;PanelButtonsComponent&gt;;
  
  beforeEach(async(() =&gt; {
    TestBed.configureTestingModule({
      declarations: [PanelButtonsComponent]
    })
      .compileComponents();
  }));
  
  beforeEach(() =&gt; {
    fixture = TestBed.createComponent(PanelButtonsComponent);
    component = fixture.componentInstance;
    fixture.detectChanges();
  });
  
  
  
  it("should call onButtonClick ", fakeAsync(() =&gt; {
    const onClickMock = spyOn(component, 'onButtonClick');
  
   fixture.debugElement.query(By.css('button')).triggerEventHandler('click', null);
    expect(onClickMock).toHaveBeenCalled();
  }));
  
  
  });
  </code></pre>
  
  <p>Test Result:</p>
  
  <blockquote>
    <p>Expected spy onButtonClick to have been called.</p>
  </blockquote>
  
  <p>Any suggestion to correct it? Thank you</p>
  
  <p><strong>Update</strong></p>
  
  <p>I have refer another <a href="https://stackoverflow.com/questions/40093013/unit-testing-click-event-in-angular">article</a>, and follow the code:</p>
  
  <pre><code>it('should', async(() =&gt; {
    spyOn(component, 'onButtonClick');
  
    let button = 
    fixture.debugElement.nativeElement.querySelector('button');
    button.click();
  
    fixture.whenStable().then(() =&gt; {
      expect(component.onButtonClick).toHaveBeenCalled();
    })
  }));
  </code></pre>
  
  <p>The test case can not pass too.</p>
  
  <p><strong>UPDATE 2:</strong></p>
  
  <p>In my html, there are two kind of click function will be called, so this  will cause the error</p>
  
  <pre><code>&lt;div&gt;
   &lt;button (click)="onButtonClick(1)"&gt;&lt;button&gt;
   &lt;button (click)="onButtonClick(2)"&gt;&lt;button&gt;
   &lt;button (click)="onButtonClick(3)"&gt;&lt;button&gt;
   &lt;button (click)="onResetClick()"&gt;&lt;button&gt;
  &lt;/div&gt;
  </code></pre>