首页 > 解决方案 > 角度单元测试中 selectItem($event) 的 dispatchEvent 语法

问题描述

NgbTypeAhead用来显示搜索结果。根据我用来获取选定值并调用我的处理程序方法来捕获事件的Angular 文档。selectedItem($event)

从 UI 一切正常。现在我在进行相同的单元测试时遇到了麻烦。

下面是相同的代码片段,我正在为我的输入标签创建一个固定装置,并dispatchEvent使用事件名称和它所期望的参数调用该方法。但这并没有按预期工作,因为处理程序方法没有获得 param ($event)

.html 文件

<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>

打字稿文件

   /**
   * 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
  }

测试文件

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);

});

标签: angularjasminedispatchevent

解决方案


调度事件会很困难。您必须提供importsanddeclarations才能开始ngbTypeahead工作,然后让它在您的单元测试中工作,或者addTeam直接使用模拟事件调用,然后进行断言。


推荐阅读