Trying to write unit tests for my Angular 6 project has presented me with a challenge. Specifically, I am attempting to test a button with a click function, but every time I run the test file, an error is displayed.
Below is the code snippet:
HTML:
<div>
<button (click)="onButtonClick(1)"><button>
<button (click)="onButtonClick(2)"><button>
<button (click)="onButtonClick(3)"><button>
</div>
comp.ts:
onButtonClick(key: number) {
do something
}
spec.ts
import { async, ComponentFixture, TestBed, fakeAsync } from '@angular/core/testing';
import { PanelButtonsComponent } from './panel-buttons.component';
import { By } from "@angular/platform-browser";
describe('PanelButtonsComponent', () => {
let component: PanelButtonsComponent;
let fixture: ComponentFixture<PanelButtonsComponent>;
beforeEach(async(() => {
TestBed.configureTestingModule({
declarations: [PanelButtonsComponent]
})
.compileComponents();
}));
beforeEach(() => {
fixture = TestBed.createComponent(PanelButtonsComponent);
component = fixture.componentInstance;
fixture.detectChanges();
});
it("should call onButtonClick ", fakeAsync(() => {
const onClickMock = spyOn(component, 'onButtonClick');
fixture.debugElement.query(By.css('button')).triggerEventHandler('click', null);
expect(onClickMock).toHaveBeenCalled();
}));
});
Test Result:
Expected spy onButtonClick to have been called.
Any ideas on how to address this issue? Your input is greatly appreciated.
Update
I came across another helpful article, and tried the following code:
it('should', async(() => {
spyOn(component, 'onButtonClick');
let button =
fixture.debugElement.nativeElement.querySelector('button');
button.click();
fixture.whenStable().then(() => {
expect(component.onButtonClick).toHaveBeenCalled();
})
}));
Unfortunately, this test case also failed to pass.
UPDATE 2:
In my HTML, there are two different click functions being called, which seems to be causing the error
<div>
<button (click)="onButtonClick(1)"><button>
<button (click)="onButtonClick(2)"><button>
<button (click)="onButtonClick(3)"><button>
<button (click)="onResetClick()"><button>
</div>