angularjasminedispatchevent

dispatchEvent syntax for selectItem($event) in angular unit testing


I am using NgbTypeAhead to show search results. According to the Angular docs I am using selectedItem($event) to get hold on selected value and calling my handler method to catch the event.

Everything works fine from UI. Now I'm having trouble unit testing the same.

Below is the code snippet for the same, I'm creating a fixture for my input tag and calling the dispatchEvent method with event name and the params it is expecting. But this is not working as expected, as the handler method is not getting the param ($event).

html file

<div class="input-group">
  <input #teamInput teamInput.value='' type="text" class="form-control" name="teamNameInput" formControlName="teamNameInput" id="teamNameInput" placeholder="Search Team Name" i18n-placeholder="@@TeamPlaceholder"
      [ngbTypeahead]="teamFilter" #teamTypeahead="ngbTypeahead" (selectItem)="addTeam($event)">
 </div>

typescript file

   /**
   * Adds an available team to the boardTeam class variable
   *
   * @param teamName the name of the team
   */
  addTeam(teamNameEvent: any) {
    teamNameEvent.preventDefault();
    console.log("in addTeam:: " + teamNameEvent.item);
    this.boardTeam = this.availableTeams.find(team => team.name === teamNameEvent.item);
    // hidden business logic
  }

test file

it("has 2 rows in the table after calling add Team", () => {
  const expectedTableRowLength = 2;
  const expectedHeaderRowLength = 1;
  const expectedLength = expectedHeaderRowLength + expectedTableRowLength;
  teamInput.dispatchEvent(new Event('selectItem'),{   //this particular event is not working.
     "item": "testTeam" - 
  fixtureUnderTest.detectChanges();
  const tableRows = fixtureUnderTest.nativeElement.querySelectorAll("tr");
      expect(tableRows.length).toBe(expectedLength);

});

Solution

  • It will be difficult in dispatching the event. You have to either provide the imports and declarations to get ngbTypeahead to work and then get it to work in your unit tests OR just call addTeam directly with a mocked event and then do your assertions.