2

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;
});
Florian Leitgeb
  • 15,657
  • 6
  • 31
  • 40

1 Answers1

1

I think there are some asynchronous aspects of the form that needs to complete before asserting for the value. Check this out.

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

AliF50
  • 16,947
  • 1
  • 21
  • 37
  • Unfortunately it is not about the async behaviour. `fixture.detectChanges()` should be enough, but I also tested it with `fixture.whenStable()`. I think it is about trusted events :/ – Florian Leitgeb Jan 19 '21 at 12:35