调度键盘事件的HTML输入没有更新值



我试图对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;
});

我认为表单的一些异步方面需要在断言值之前完成。看看这个

试试这个:

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

最新更新