I am trying to unit test the cursor position on an Angular component, which is automatically formatting user input. The component itself uses a normal HTML input field and then needs to insert spaces to format the text for better readability.
The event is getting registered when I attach an EventHandler to the HTML element and log something out. But the value in the input field is not getting registered and also the SelectionStart/SelectionEnd
attributes are not updated.
Here is my unit test:
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');
My component:
@Component({
template: `
<input [formControl]="formControl" />
`
})
class InputComponent {
formControl = new FormControl();
}
My TestBed:
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;
});