'Test: Focussing an element doesn't trigger the CSS update based on the :focus pseudo class
What do I want to do?
Using the CSS pseudo class :focus to determine whether an element has the style display: block or none.
It works perfectly fine in the browser!
What is not working ?
I'm running a Test with @testing-library/react to check whether or not the element is visible, based on the focused element. I can focus the element, but the other ones styling still hasn't changed.
I created the same example using the :checked pseudo class. This is working!
What are my questions?
- How do I make it work?
- Is it an issue with jsdom (my guess), or jest, or testing-library?
Example
You can use the following https://codesandbox.io/s/trusting-leavitt-odukyk to check it out. Both examples (:focus and :checked) are present. Both work fine in the browser. But only the :checked test case is successful. (The css is manually added to the tests, because CSS that is imported in React components, isn't automatically added to jsdom.)
// App.js
<input
id="focus_input"
data-testid="focus_input"
type="text"
defaultValue="Focus me"
/>{" "}
<label id="focus_label" data-testid="focus_label">
Focus input to hide
</label>
//styles.css
#focus_input:focus + #focus_label {
display: none;
}
//App.test.js
test("Hide on focus", () => {
renderWithStyle("#focus_input:focus + #focus_label { display: none; }");
expect(screen.getByTestId("focus_label")).toBeVisible();
act(() => {
screen.getByTestId("focus_input").focus();
});
expect(screen.getByTestId("focus_input")).toHaveFocus();
expect(screen.getByTestId("focus_label")).toHaveStyle({ display: "none" });
expect(screen.getByTestId("focus_label")).not.toBeVisible();
});
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|
