What could be the reason for the failure of .simulate("mouseover") in a Jest / Enzyme test?

I have a scenario where a material-ui ListItem triggers the display of a material-ui Popper containing another ListItem on mouse over using the onMouseOver event. While this functionality works as expected, I am facing difficulties replicating the behavior in Jest/Enzyme Tests.

Below is a simplified example along with the failing test:

https://codesandbox.io/s/priceless-bose-6hi04?fontsize=14&hidenavigation=1&theme=dark

Component Snippet

export default function MyPopoutMenu() {
  const [popoverAnchorElement, setPopoverAnchorElement] = useState(null);
  const handleMouseEnter = (event) => {
    console.log("onMouseEnter - " + event.currentTarget.textContent);
    setPopoverAnchorElement(event.currentTarget);
  };

  const handleClose = (event, index) => {
    console.log("closing");
    setPopoverAnchorElement(null);
  };

  let isPopoverOpen = Boolean(popoverAnchorElement);
  return (
    <div className="App">
      <List style={{ maxWidth: "250px" }}>
        <ListItem button>
          <ListItemIcon>
            <FolderIcon />
          </ListItemIcon>
          <ListItemText onMouseEnter={handleMouseEnter}>
            Hover on me
          </ListItemText>
        </ListItem>
      </List>
      <Popper
        open={isPopoverOpen}
        onClose={handleClose}
        anchorEl={popoverAnchorElement}
        className="popper-item"
      >
        <ListItem button>
          <ListItemIcon>
            <KeyboardArrowRightIcon />
          </ListItemIcon>
          <ListItemText>I Appear</ListItemText>
        </ListItem>
      </Popper>
    </div>
  );
}

Test Snippet

/** Interaction tests testing user interaction with PilzButton */
test("Check that popover appears on hover", () => {
  const wrapper = mount(<MyPopoutMenu />);
  console.log("wrapper DEBUG - " + wrapper.debug());

  //1. Find the menu item to hover on
  const foundListItem = wrapper
    .find(".MuiListItemText-root")
    .filterWhere(item => item.contains("Hover on me"));
  expect(foundListItem).toHaveLength(1);

  //2. Hover on the item
  foundListItem.prop("onMouseEnter")({
    currentTarget: {
      textContent: "Hover on me"
    }
  });
  act(() => {
    //Now try to find the Popover
    const foundPopoverListItem = wrapper
      .find(".MuiListItemText-root")
      .filterWhere(item => item.contains("I Appear"));

    expect(foundPopoverListItem).toHaveLength(1);
  });
});

Answer №2

Take a look at this interesting discussion regarding the usage of simulate:

https://github.com/airbnb/enzyme/issues/1606

In summary, the advice is to avoid using it altogether and instead try the following approach:

foundListItem.prop('onMouseEnter')();

If you need to, you can also provide a mock event to the handleMouseEnter function like this:

foundListItem.prop('onMouseEnter')({
  currentTarget: {
    textContent: 'I Appear'
  }
});

I hope this information proves helpful!

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Clicking does not trigger scrollIntoView to work properly

I'm facing an issue with a button that is supposed to scroll the page down to a specific div when clicked. I implemented a scrollIntoView function in JavaScript and attached it to the button using onClick. Although the onClick event is functioning as ...

PHP script failing to execute if/else statement during AJAX request

I am currently developing a website that heavily relies on Ajax, and I have chosen to use codeigniter for its construction. On the site, there is a form with the post method, and this form is submitted using an Ajax request that calls a function containi ...

Encountering a bug in my JSON or object tree viewer in Vue.js 3 where duplicate keys are present when there are multiple similar values

Encountering an issue with the following code: Attempting to create a tree viewer from an object, it works well until encountering identical values which cause key duplication and replacement. View on CodePen: https://codepen.io/onigetoc/pen/rNPeQag?edito ...

What is the best way to display a removed item from the Redux state?

Display nothing when the delete button is clicked. The issue seems to be with arr.find, as it only renders the first item regardless of which button is pressed, while arr.filter renders an empty list. reducer: export default function reducer(state = initi ...

What is the best way to effectively carry out a partial update using ReactJS?

During a recent job interview, the recruiter discussed the importance of handling partial updates and managing application size. As an example, he presented a Single Page Application (SPA) with a size of 8MB, which he deemed less than ideal. He emphasize ...

Retrieve returned data using jQuery

How can I retrieve data when using the jQuery.get method? function send_data(pgId) { for(var i = 0; i < pgId.length; i++) { // $.get(url, data, success(data, textStatus, jqXHR)) $.get('index.php?page=' + pgId[i], pgId[ ...

Generating a chart using solely the existing data components (values)

I have the following arrays: const elements = ['12345', '12346', '12347', '12348', '12349', '12350']; const fruits = ['Apple', 'Ball']; I want to create a Map using array ele ...

Setting the value for datepicker and timepicker in ReactJS for individual rows

Can you please explain how to set a default value for the datepicker and timepicker in each row? I have successfully implemented the datepicker and timepicker functionalities in my code. In the home.js file, there is a state called additionalFields which ...

Encountering the error "Cannot read property 'header' of undefined" while conducting tests on Nodejs using supertest

In my server.js file, I have set up my express app. I tried to run a demo test in my test file using express, but unfortunately, the test did not run successfully. const request = require('supertest'); const express = require('express' ...

How can I insert my URL into the webPDFLoader feature of LangChain platform?

I need help figuring out how to load a PDF from a URL using the webPDFLoader. Can someone explain how to implement this? Any assistance would be greatly appreciated. I am working on this task in nextjs. Where should I place the pdfUrl variable within the ...

Error received - CORS request denied on Firefox browser (Ubuntu)

I encountered a CORS error (CORS request rejected: https://localhost:3000/users) while attempting to register a new user. This issue arose from content in the book Building APIs with node.js, Chapter 12. I am currently using Firefox on Ubuntu and have tr ...

What is the best way to clear radio button selections in a form using reactjs?

I designed a survey form with 4 radio buttons for a single question. I also included buttons to submit the form and clear input fields. However, when I click on "Clear Input," the checked radio buttons do not get cleared. How can I achieve this using the r ...

Exploring the latest updates in MUI modern version

The MUI documentation suggests using a modern folder with components designed for modern browsers. Is there a way to configure webpack to automatically rewrite imports like import {Box} from "@mui/material" to use the modern version without manually changi ...

Javascript - issue with accurately retrieving element offset value while scrolling

My goal is to dynamically change classes for elements based on their position during scrolling. I am trying to calculate the top offset element value and adjust the classes accordingly. Here is the function I am using: handleScroll () { const header = ...

The Wave tool is experiencing an accessibility issue related to the absence of a form label in TablePagination-MUI

"How can I resolve the accessibility issue of 'Missing form label' in the Wave tool when utilizing Table pagination?" <TablePagination ref={paginationComponentRef} ActionsComponent={PaginationActionsComponent} compo ...

Add a parameter to the iframe that is dynamically loaded into the DOM after a user clicks on

I am attempting to automatically play a YouTube video within an iframe. The iframe is only loaded into the DOM when I activate a trigger element: a.colorbox.cboxElement How can I add the parameter ?autoplay=1 to the end of the iframe URL upon click, consi ...

Preview multiple images while uploading in a React JS application

In order to achieve multiple image upload with preview using React JS, I attempted the code below. However, I encountered an error in the console: Uncaught DOMException: Failed to set the 'value' property on 'HTMLInputElement': This ...

Is there a compelling case for implementing Meteor in 2017?

Back in the day, Meteor was expected to revolutionize web development on node by simplifying the process of creating interactive applications. Though I'm not well-versed in its history, it seems like most of the development effort has shifted elsewher ...

"Troubleshooting the slow loading of PDF files when using React's render-pdf feature

After creating a table with the ability for each row to generate and download a PDF using render-pdf npm, I encountered an issue. When the user clicks the download button, the PDF preview opens on a new page. However, there are problems with rendering as a ...

What is the best way to implement an AppBar that fades in and out when scrolling within a div?

I'm trying to implement a Scrollable AppBar that hides on scroll down and reappears when scrolling up. Check out this image for reference To achieve this functionality, I am following the guidelines provided by Material-UI documentation export defa ...