简体   繁体   English

在 Angular (9) 中测试关键指令

[英]testing key directive in Angular (9)

I have a directive that I am trying to test.我有一个要测试的指令。 But the length of the value in the directive is always undefined.但是指令中值的长度总是未定义的。

What am I doing wrong?我究竟做错了什么?

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

The test component:测试组件:

@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() {
  }
}

And the test和测试

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

I have tried trigger n input event before the key also, but the valueof statement always returns undefined我也试过在键之前触发 n 输入事件,但 valueof 语句总是返回 undefined

Can you try the uncommented line instead of the commented one in your directive?您可以尝试使用未注释的行而不是指令中的注释行吗? Does the directive work when code is served but not in unit test?当提供代码但不在单元测试中时,指令是否有效? It is the first time I am seeing valueOf() .这是我第一次看到valueOf()

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM