首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >如何在Angular单元测试中删除输入字段中的字符

如何在Angular单元测试中删除输入字段中的字符
EN

Stack Overflow用户
提问于 2019-10-11 05:51:35
回答 1查看 414关注 0票数 0

我正在尝试做一个非常基本的单元测试,以测试在文本字段中按退格键是否会删除字符。然而,我尝试了各种触发事件的方法,但它似乎并没有真正删除任何东西。到目前为止,我所得到的是基于来自这个库https://github.com/JsDaddy/ngx-mask/blob/develop/src/app/ngx-mask/test/delete.spec.ts的规范文件

代码语言:javascript
复制
import { ComponentFixture, TestBed } from '@angular/core/testing';
import { ReactiveFormsModule, FormControl } from '@angular/forms';
import { By } from '@angular/platform-browser';
import { DebugElement, Component } from '@angular/core';

@Component({
  template: `
  <input type="text" (keydown)="keydown()"
    (focus)="focus()"
    (blur)="blur()"
    (input)="input()" id="testField" [formControl]="formField" />`,
})
class TestInputComponent {

  public formField: FormControl;

  constructor() {
    this.formField = new FormControl('ABCDE');
  }

  keydown() { console.error('keydown called'); }
  input() { console.error('input called'); }
  focus() { console.error('focus called'); }
  blur() { console.error('blur called'); }
}

describe('Delete Characters', () => {

  let fixture: ComponentFixture<TestInputComponent>;
  let component: TestInputComponent;

  beforeEach(() => {
    TestBed.configureTestingModule({
      declarations: [TestInputComponent],
      imports: [
        ReactiveFormsModule,
      ],
    });
    fixture = TestBed.createComponent(TestInputComponent);
    component = fixture.componentInstance;
    fixture.detectChanges();
  });

  it('should delete a character and move cursor back', () => {
    const debugElement: DebugElement = fixture.debugElement.query(By.css('input'));
    const inputTarget: HTMLInputElement = debugElement.nativeElement as HTMLInputElement;
    spyOnProperty(document, 'activeElement').and.returnValue(inputTarget);
    fixture.detectChanges();

    inputTarget.value = 'ABCDE';
    inputTarget.selectionStart = 3;
    inputTarget.selectionEnd = 3;
    debugElement.triggerEventHandler('keydown', { code: 'Backspace', keyCode: 8, target: inputTarget });
    debugElement.triggerEventHandler('input', { target: inputTarget });

    expect(inputTarget.selectionStart).toEqual(2); // Fails, is still 3
    expect(inputTarget.value).toEqual('ABDE'); // Fails, is still ABCDE
  });

});
EN

回答 1

Stack Overflow用户

发布于 2019-10-11 15:10:25

您的triggerEventHandler未触发事件。请将triggerEventHandler替换为dispatchEvent,然后尝试。

代码语言:javascript
复制
   debugElement.nativeElement.dispatchEvent(new Event('keydown'), { code: 'Backspace', keyCode: 8, target: inputTarget });
    debugElement.nativeElement.dispatchEvent(new Event('input'), { target: inputTarget });

请参考此comment

票数 1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/58331562

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档