I'm facing a seemingly simple issue where I am unable to confirm that a click handler is being triggered on my component.
header.component.ts
import { Component, EventEmitter, OnInit, Output } from '@angular/core';
@Component({
selector: 'app-header',
templateUrl: './header.component.html',
styleUrls: ['./header.component.scss']
})
export class HeaderComponent implements OnInit {
@Output() hamburgerToggle = new EventEmitter<void>();
constructor() {}
ngOnInit(): void {}
hamburgerClicked(): void {
this.hamburgerToggle.emit();
}
}
header.component.html
<nav class="sb-topnav navbar navbar-expand navbar-dark bg-dark">
<div class="hamburger header-toggle">
<button (click)="hamburgerClicked()" class="btn btn-link btn-sm order-first order-first header-toggle" id="sidebarToggle" href="/">
<i class="material-icons header-toggle">menu</i>
</button>
</div>
</nav>
header.component.spec.ts
import { ComponentFixture, TestBed } from '@angular/core/testing';
import { By } from '@angular/platform-browser';
import { HeaderComponent } from './header.component';
describe('HeaderComponent', () => {
let component: HeaderComponent;
let fixture: ComponentFixture<HeaderComponent>;
beforeEach(async () => {
await TestBed.configureTestingModule({
declarations: [HeaderComponent]
}).compileComponents();
});
beforeEach(() => {
fixture = TestBed.createComponent(HeaderComponent);
component = fixture.componentInstance;
fixture.detectChanges();
});
it('verifying if the toggle button triggers the click handler', () => {
const fixture = TestBed.createComponent(HeaderComponent);
const clickSpy = spyOn(component, 'hamburgerClicked');
const toggleButton = fixture.debugElement.query(By.css('#sidebarToggle'));
toggleButton.triggerEventHandler('click', toggleButton);
fixture.detectChanges();
expect(clickSpy).toHaveBeenCalledTimes(1);
});
});
The error message states:
Expected spy hamburgerClicked to have been called once. It was called 0 times.
Even within an async block, the result remains the same:
fit('verifying if the toggle button triggers the click handler', fakeAsync(() => {
const fixture = TestBed.createComponent(HeaderComponent);
const clickSpy = spyOn(component, 'hamburgerClicked');
const toggleButton = fixture.nativeElement.querySelector('#sidebarToggle');
toggleButton.click();
tick();
fixture.detectChanges();
fixture.whenStable().then(() => {
expect(clickSpy).toHaveBeenCalledTimes(1);
});
}));
I've spent hours trying to resolve this issue and any assistance would be greatly appreciated.