首页 > 解决方案 > 在处理组件中的 nativeElement.setAttribute 的函数中升级到 Angular6 后出现 TypeError

问题描述

问题!

我有一个搜索栏组件,它有一个 textarea 作为搜索字段。根据我搜索的文本数量,我增加或减少 textarea 本身的行数。所以我有一些处理文本区域的本机元素的操作。例如这个函数

搜索栏.ts

focus() {
  if (this.textArea) {
    this.focussed = true;
    this.textArea.nativeElement.setAttribute('rows', this.calcRows());

    // extra part ...
  }
}

搜索栏.spec.ts

describe('focus', () => {
  it('should set focussed to true', () => {
    component.focussed = false;
    component.focus();
    expect(component.focussed).toBe(true);
  });

  it('should set the height of the textArea by setting the row to the correct amount', () => {
    spyOn(component.textArea.nativeElement, 'setAttribute');
    spyOn(component, 'calcRows').and.returnValue(2);

    component.focus();
    expect(component.textArea.nativeElement.setAttribute).toHaveBeenCalledWith('rows', 2);
  });
});

测试实际上并没有失败。但是我显示了这个错误,并且提到我假设它们不是指测试本身,而是指组件。

错误:'ERROR',TypeError:未定义不是函数(评估'this.textArea.nativeElement.setAttribute('rows',this.calcRows())')

任何想法如何解决它?提前致谢

标签: angularunit-testingerror-handlingtypeerrorangular6

解决方案


尝试this.textArea.nativeElement.rows = this.calcRows()


推荐阅读