fireEvent - mouseEnter/mouseLeave not working with addEventListener
See original GitHub issuereact-testing-libraryversion: 9.4.0reactversion: 16.12.0nodeversion: 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.
Issue Analytics
- State:
- Created 4 years ago
- Reactions:4
- Comments:9 (3 by maintainers)
Top Related StackOverflow Question
Upon further testing, I noticed by creating the event myself and passing it to
fireEvent, DOES pass ✅ :So there are the four cases we want to work with the fireEvent utility.
Currently, number 1 does not work.
We want to make a change to fix 1, without breaking the others. Here’s a test people we can use to ensure we have done that. So as long as the following tests pass, I’m assuming there shouldn’t be any issues getting this change in.
(Like others, I unfortunately don’t have time to look into this right now, but maybe in a couple months)