angular - 如何对以 HTMLInputElement 作为参数的角度方法进行单元测试?
问题描述
下面是我的代码片段
代码
applyFilter(event: Event): void {
const filterValue = (event.target as HTMLInputElement).value;
this.filterBy = filterValue.trim().toLowerCase();
this.dataSource.filter = filterValue.trim().toLowerCase();
}
测试用例
fit('applyFilter', () => {
const event = new Event('click');
component.applyFilter(event);
});
我得到的错误是“TypeError:无法读取null的属性'值'”,而此转换“(event.target as HTMLInputElement).value;” 发生提到的错误
解决方案
I would just mock the object.
it('should change filterBy and dataSource.filter', () => {
const event = { target: { value: 'hello' } } as any;
component.applyFilter(event);
expect(component.filterBy).toBe('hello');
expect(component.dataSource.filter).toBe('hello');
});
推荐阅读
- c# - Microsoft.JSInterop.JSException:当前没有元素与组件关联
- python - 如何打印python品脱数量及其含义
- google-sheets - 如何从 Google 表格的下拉菜单中交替查询
- java - 是否有访问 recyclerView 中第一项的解决方案
- android - 在发布模式下颤振构建 appbundle
- android - 关闭gps时粉碎
- c - 如何将字符串和浮点数从文件存储到结构?
- amazon-web-services - 通过 Terraform 生成的 SQS FIFO 队列的消息停留在 In-Flight 状态
- javascript - Promise.all() 与使用 await 的动态大小的请求数组
- css - 我怎样才能使曲线模糊的背景图像叠加