0
votes

I need to test if a focus is set correctly, after pressing the TAB button.
The test must be done with karma/jasmine.
I looked already to this answers here, but it didnt help.

StackOverflow - Unable to simulate keypress event in Angular 2 unit test (Jasmine)
StackOverflow - how-do-i-trigger-a-keyup-keydown-event-in-an-angularjs-unit-test

When pressing Tab, the focus should be on the second button element.

Here is a Stackblitz Demo

<div>
  <button>1</button>
  <button>2</button>
</div>

unit Test

 fit('press TAB: should select button "2"', () => {
    const firstButton = el.queryAll(By.css('button'))[0].nativeElement;
    const secondButton = el.queryAll(By.css('button'))[1].nativeElement;
    spyOn(secondButton, "focus");
    const pressTAB = new KeyboardEvent("keypress",{"key": "Tab"});
    firstButton.dispatchEvent(pressTAB);
    fixture.detectChanges();
    
    expect(secondButton.focus).toHaveBeenCalled();
  });
1

1 Answers

0
votes

Maybe you can look at document.activeElement to see which element has the focus.

fit('press TAB: should select button "2"', () => {
    const firstButton = el.queryAll(By.css('button'))[0].nativeElement;
    const secondButton = el.queryAll(By.css('button'))[1].nativeElement;
    spyOn(secondButton, "focus");
    const pressTAB = new KeyboardEvent("keypress",{"key": "Tab"});
    firstButton.dispatchEvent(pressTAB);
    fixture.detectChanges();
    
    console.log(document.activeElement);
    // not sure about below expectation
    expect(document.activeElement).toEqual(secondButton);
  });

That being said, it seems pressing tab on an element goes to the next one and this is a stock HTML behavior. Therefore, you should only be unit testing your code and not HTML behavior (it is already tested).