title: angular unit test button click through html
body: <p>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.</p>
  
  <p><strong>Html:</strong></p>
  
  <pre><code>&lt;div class="row"&gt;
      &lt;button id="homeBtn" class="btn btn-primary" [routerLink]="['home']"&gt;Home&lt;/button&gt;
    &lt;/div&gt;
  </code></pre>
  
  <p><strong>Component Code:</strong></p>
  
  <pre><code>export class AppComponent {
    title = 'My app';
    constructor(private router: Router) {}
  
    goHome() {
      this.router.navigate(['./']);
    }
  </code></pre>
  
  <p><strong>Test Spec:</strong></p>
  
  <pre><code> beforeEach(async(() =&gt; {
          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', () =&gt; {
      spyOn(component, 'goHome');
      component.goHome();
      expect(component.goHome).toHaveBeenCalled();
    });
  
    // this test works
    it('should render the HOME button', async(() =&gt; {
      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(() =&gt; {
      spyOn(component, 'goHome');
      fixture.detectChanges();
      let button = instance.querySelector('#homeBtn');
      button.click();
      fixture.detectChanges();
      expect(component.goHome).toHaveBeenCalled();
    }));
  </code></pre>
  
  <p>The test result is "<em>Expected spy goHome to have been called.</em>" 
  Any thoughts on how to get this to work?</p>