Description
react-testing-library
version: 9.4.0react
version: 16.12.0node
version: 10.16.0npm
(oryarn
) version: 1.21.1
Relevant code or config:
import React, { useEffect, useState, useRef } from "react";
import { render, fireEvent } from "@testing-library/react";
const HoverMe = () => {
const ref = useRef();
const [isMouseEntered, setIsMouseEntered] = useState(false);
useEffect(() => {
const setYes = () => setIsMouseEntered(true);
const button = ref.current;
// If you change the event to "mouseover"
// the test passes, even if you don't update the test
button.addEventListener("mouseenter", setYes);
return () => {
button.removeEventListener("mouseenter", setYes);
};
});
return <button ref={ref}>{isMouseEntered ? "yes" : "no"}</button>;
};
describe("mouseenter/mouseleave bug", () => {
test("mouseenter should update text to 'yes'", () => {
const { getByText } = render(<HoverMe />);
fireEvent.mouseEnter(getByText("no"));
expect(getByText("yes")).toBeTruthy();
});
});
What you did:
I'm using a third party library that attaches mouseenter
and mouseleave
events to a DOM element accessed via a React ref
via HTMLElement.addEventListener
. Was testing this behavior.
What happened:
Works fine in the browser, but when writing my tests, I noticed that fireEvent.mouseEnter
and fireEvent.mouseLeave
have no effect. What's weird is if I leave the test alone, but change the event in the component to mouseover/mouseout
, it works. If I attach the events the react way, via onMouseEnter
and onMouseLeave
, it also works.
Reproduction:
https://codesandbox.io/s/react-testing-library-demo-37yqv?fontsize=14&hidenavigation=1&theme=dark
Problem description:
fireEvent.mouseLeave
and fireEvent.mouseOver
do not work when the events are added via addEventListener
.
Suggested solution:
It may have something to do with this: https://reactjs.org/docs/events.html#mouse-events
If this is a React limitation, or if there's a workaround, it would be great to add it to the FAQ.