angular - 角度单元测试中 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);
});
解决方案
调度事件会很困难。您必须提供imports
anddeclarations
才能开始ngbTypeahead
工作,然后让它在您的单元测试中工作,或者addTeam
直接使用模拟事件调用,然后进行断言。
推荐阅读
- javascript - 如何知道在amcharts的堆积条形图上点击了哪个类别?
- php - 通过验证或使用 php 中的 6 位代码字符串来显示来自数组列表的学生详细信息?
- javascript - Vue.js 渲染多个插槽
- javascript - KML 和谷歌地图:加载值的问题
进入弹出窗口 - android - 如何使用intent在android中打开后置/后置摄像头
- xpages - 编译 Xpages 的 java 脚本库中的错误
- javascript - 遍历 JSON 并获取每个数据键的图像
- javascript - 使用 replace 和 pathArray[0],我似乎是在添加而不是用我的 JavaScript 替换
- vba - 如何传递电子邮件地址和密码以在 GMail 中创建电子邮件?
- regex - Pyspark - 正则表达式 - 从最后一个括号中提取值