【问题标题】:testing key directive in Angular (9)在 Angular 中测试关键指令 (9)
【发布时间】:2020-03-17 01:54:26
【问题描述】:

我有一个要测试的指令。但是指令中值的长度始终是未定义的。

我做错了什么?

@Directive({
  selector: '[evAutoTab]'
})
export class EvAutoTabDirective {

  @Input('evAutoTab') destId: string;

  @HostListener('keyup') onKeyup() {
      this.moveFocus();
  }

  constructor(private el: ElementRef) {
  }

  private moveFocus() {
    const maxLen = this.el.nativeElement.getAttribute('maxlength');
    const len = this.el.nativeElement.valueOf().length;
    console.log(`len ${len} maxLen ${maxLen}`);
    if (len === maxLen) {
      const next: HTMLElement = document.querySelector('#' + this.destId);
      next.focus();
    }
  }
}

测试组件:

@Component({
  template: `
    <div>
      <input evAutoTab="'AutoTab1'" id="AutoTab0" maxlength="4" value=""/>
      <input evAutoTab id="AutoTab1" value=""/>
      <input evAutoTab id="AutoTab2" value=""/>
    </div>
    <div>
      <input evAutoTab id="AutoTab3" value=""/>
      <input evAutoTab id="AutoTab4" value=""/>
      <input evAutoTab id="AutoTab5" value=""/>
    </div>
  `
})
class TestComponent {

  constructor() {
  }
}

还有测试

  it('should move focus from first element if maxlength is reached', async () => {
    const debugEl: HTMLElement = fixture.debugElement.nativeElement;
    const autoTab0: HTMLInputElement = debugEl.querySelector('#AutoTab0');

    // verify setup
    autoTab0.focus();
    expect(document.activeElement.id).toBe('AutoTab0');

    // act
    autoTab0.value = '1999';
    autoTab0.dispatchEvent(new Event('keyup'));
    fixture.detectChanges();
    expect(document.activeElement.id).toBe('AutoTab1');
  });

我也试过在key之前触发n个输入事件,但是valueof语句总是返回undefined

【问题讨论】:

    标签: angular unit-testing angularjs-directive jasmine keyup


    【解决方案1】:

    您可以尝试在指令中使用未注释的行而不是已注释的行吗?提供代码但不在单元测试中时,该指令是否有效?这是我第一次看到valueOf()

    // const len = this.el.nativeElement.valueOf().length;
    const len = this.el.nativeElement.value.length;
    

    【讨论】:

    • 这解决了我的问题。我使用 valueOf 是因为我认为它是一个 HTMLInputElement,而这正是自动完成功能提供的。
    猜你喜欢
    • 2019-12-24
    • 1970-01-01
    • 1970-01-01
    • 2013-10-18
    • 1970-01-01
    • 2019-11-11
    • 1970-01-01
    • 2019-08-12
    • 1970-01-01
    相关资源
    最近更新 更多