Skip to content

Instantly share code, notes, and snippets.

@chaance
Created April 7, 2021 21:03
Show Gist options
  • Save chaance/00638b16a46f0be926506f83b4e6ff82 to your computer and use it in GitHub Desktop.
Save chaance/00638b16a46f0be926506f83b4e6ff82 to your computer and use it in GitHub Desktop.
Focusing in tests is frustrating
describe("when navigating between focused buttons", () => {
let buttons: HTMLElement[];
beforeAll(() => {
let rendered = renderTestAccordion();
buttons = rendered.buttons;
});
it("should move focus to the next focusable button on `ArrowDown` press", () => {
// document.activeElement is the body here, cool
buttons[0].focus();
// document.activeElement is the button here, yay! 🥳
fireEvent.keyDown(document.activeElement, { key: "ArrowDown" });
// Test passes!
expect(buttons[1]).toHaveFocus();
});
it("should move focus to the previous focusable button on `ArrowUp` press", () => {
// document.activeElement is the body here, cool
buttons[1].focus();
// document.activeElement is ... still the body here 🧐
fireEvent.keyDown(document.activeElement, { key: "ArrowDown" });
// Test fails, no good
expect(buttons[0]).toHaveFocus();
});
it("should move focus to the previous focusable button on `ArrowUp` press", () => {
// document.activeElement is the body here, cool
buttons[1].focus();
// If I wait a tick, this works. But this seems ... not right.
// Element.focus() is sync, so what gives?
setTimeout(() => {
fireEvent.keyDown(document.activeElement, { key: "ArrowDown" });
expect(buttons[0]).toHaveFocus();
});
});
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment