Angular(9)中的测试键指令

问题描述 投票:0回答:1

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

我在做什么错?

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

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

angular unit-testing angularjs-directive jasmine keyup
1个回答
1
投票

您能否尝试使用未注释的行而不是指令中的注释行?该指令在提供代码但在单元测试中不起作用吗?这是我第一次看到valueOf()

// const len = this.el.nativeElement.valueOf().length;
const len = this.el.nativeElement.value.length;
© www.soinside.com 2019 - 2024. All rights reserved.