首页 > 解决方案 > 如何对以 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;” 发生提到的错误

标签: angularunit-testingjasmine

解决方案


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

推荐阅读