【问题标题】:Dispatch keyboard event for HTML input is not updating the valueHTML 输入的调度键盘事件未更新值
【发布时间】:2021-04-22 16:45:06
【问题描述】:

我正在尝试对 Angular 组件上的光标位置进行单元测试,该组件会自动格式化用户输入。 组件本身使用普通的 HTML 输入字段,然后需要插入空格来格式化文本以提高可读性。

当我将 EventHandler 附加到 HTML 元素并注销某些内容时,该事件正在注册。但是输入字段中的值没有被注册,SelectionStart/SelectionEnd 属性也没有更新。

这是我的单元测试:

const inputElement = fixture.debugElement.query(By.css('input'));
const event = new KeyboardEvent('keydown', {
  key: 'e',
  code: 'KeyE',
  bubbles: true
});
inputElement.nativeElement.dispatchEvent(event);
fixture.detectChanges();
expect(inputElement.nativeElement.value).toEqual('e');

我的组件:

@Component({
    template: `
        <input [formControl]="formControl" />
    `
})
class InputComponent {
    formControl = new FormControl();
}

我的测试床:

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

beforeEach(async(() => {
  TestBed.configureTestingModule({
    declarations: [InputComponent],
    imports: [ReactiveFormsModule]
  }).compileComponents();
}));

beforeEach(() => {
  fixture = TestBed.createComponent(InputComponent);
  fixture.detectChanges();

  component = fixture.componentInstance;
});

【问题讨论】:

    标签: html angular unit-testing jasmine


    【解决方案1】:

    我认为在声明值之前需要完成表单的一些异步方面。签出this

    试试这个:

    it('should do xyz', async () => { // add async to get await
      const inputElement = fixture.debugElement.query(By.css('input'));
      const event = new KeyboardEvent('keydown', {
        key: 'e',
        code: 'KeyE',
        bubbles: true
      });
      inputElement.nativeElement.dispatchEvent(event);
      fixture.detectChanges();
      await fixture.whenStable(); // await for the promises to finish before asserting
      fixture.detectChange();
      expect(inputElement.nativeElement.value).toEqual('e');
    });
    
    

    【讨论】:

    • 不幸的是,这与异步行为无关。 fixture.detectChanges() 应该够用了,不过我也用fixture.whenStable() 测试过。我认为这是关于可信事件:/
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-11-24
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多