【问题标题】:dispatchEvent syntax for selectItem($event) in angular unit testing角度单元测试中 selectItem($event) 的 dispatchEvent 语法
【发布时间】:2020-03-13 19:24:43
【问题描述】:

我正在使用NgbTypeAhead 来显示搜索结果。根据Angular docs,我正在使用selectedItem($event) 来保持选定的值并调用我的处理程序方法来捕获事件。

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

下面是相同的代码 sn-p,我正在为我的输入标签创建一个夹具,并使用事件名称和它所期望的参数调用 dispatchEvent 方法。但这并没有按预期工作,因为处理程序方法没有获得参数($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);

});

【问题讨论】:

    标签: angular jasmine dispatchevent


    【解决方案1】:

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

    【讨论】:

    • 感谢这个想法。我将模拟事件对象传递给 addTeam(),这有助于我继续我的测试用例。 mockSelectItemEvent = {item: "testTeam"} teamInput.dispatchEvent(new Event('selectItem')); componentUnderTest.addTeam(mockSelectItemEvent);
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2016-02-04
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-09-24
    • 2018-01-03
    • 1970-01-01
    相关资源
    最近更新 更多