I'm trying to test a button event component call through the html. The button works when run manually. I can successfully test the component directly. I can also successfully test the button renders, But the test is not seeing the function call when executed through the html.
Html:
<div class="row">
<button id="homeBtn" class="btn btn-primary" [routerLink]="['home']">Home</button>
</div>
Component Code:
export class AppComponent {
title = 'My app';
constructor(private router: Router) {}
goHome() {
this.router.navigate(['./']);
}
Test Spec:
beforeEach(async(() => {
TestBed.configureTestingModule({
declarations: [
AppComponent,
HomeComponent,
],
imports: [
FormsModule,
RouterModule.forRoot(ROUTES),
RouterTestingModule.withRoutes([])
],
providers: [
{ provide: APP_BASE_HREF, useValue: '/' }
]
}).compileComponents();
fixture = TestBed.createComponent(AppComponent);
component = fixture.debugElement.componentInstance;
instance = fixture.debugElement.nativeElement;
}));
// this test works
it('home button should work', () => {
spyOn(component, 'goHome');
component.goHome();
expect(component.goHome).toHaveBeenCalled();
});
// this test works
it('should render the HOME button', async(() => {
spyOn(component, 'goHome');
fixture.detectChanges();
let button = instance.querySelector('#homeBtn');
expect(button.textContent).toContain('Home', 'button renders');
}));
// this test fails
it('should call goHome function', async(() => {
spyOn(component, 'goHome');
fixture.detectChanges();
let button = instance.querySelector('#homeBtn');
button.click();
fixture.detectChanges();
expect(component.goHome).toHaveBeenCalled();
}));
The test result is "Expected spy goHome to have been called." Any thoughts on how to get this to work?