How to unit test a button click event in Angular?

Viewed 1685

I am trying to test a button click event. The official Angular manual says there are two ways to do this.

1.

it('should raise selected event when clicked (triggerEventHandler)', () => {
  let selectedHero: Hero;
  const heroDe = fixture.debugElement.query(By.css('dashboard-hero'));
  comp.selected.subscribe((hero: Hero) => selectedHero = hero);
  heroDe.triggerEventHandler('click', null);
  expect(selectedHero).toBe(expectedHero);
});
it('should raise selected event when clicked (element.click)', () => {
  let selectedHero: Hero;
  const heroEl: HTMLElement = fixture.nativeElement.querySelector('.hero');
  comp.selected.subscribe((hero: Hero) => selectedHero = hero);
  heroEl.click();
  expect(selectedHero).toBe(expectedHero);
});

The first method worked well for me. But when I tried the second option, the test ran without errors, but Karma started running tests in an infinite loop.

enter image description here

Here is my implementation of both ways.

it('test1', () => {
  fixture.detectChanges();
  let treeNodeElement = fixture.debugElement.query(By.css('#buttonSend'));
  treeNodeElement.triggerEventHandler('click', null);
  expect(component.tabService.tabs.length).toBe(1);
  expect(component.tabService.tabs[0].title).toBe('Test1');
});

it('test2', () => {
  fixture.detectChanges();
  const treeNodeElement: HTMLElement = fixture.nativeElement.querySelector('#buttonSend');
  treeNodeElement.click();
  expect(component.tabService.tabs.length).toBe(1);
  expect(component.tabService.tabs[0].title).toBe('Test1');
});

Can you please tell me where is the error in the second option?

1 Answers

The solution here for me was importing FormsModule and ReactiveFormsModule in beforeEach(). The problem was that clicking on the button ( Which was a submit button ) engendred a browser behaviour which is refreshing the page. Even if the FormsModule and ReactiveFormsModule are imported in the component where the form is created, they have also to be imported in the .spec file where you are running the test case

beforeEach(async () => {
 await TestBed.configureTestingModule({
  imports: [
    RouterTestingModule,
    RouterModule.forRoot([]),
    NgbModule,
    FormsModule,  <----
    ReactiveFormsModule,  <----
  ],
  declarations: [  
   ...

both module should be imported from @angular/forms

import { FormsModule, ReactiveFormsModule } from '@angular/forms';
Related