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

1 Answer 1

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

Sign up to request clarification or add additional context in comments.

1 Comment

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 :/

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.