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

Is there a more efficient method to execute this AJAX request?

$('#request_song').autocomplete({ serviceUrl: '<%= ajax_path("trackName") %>', minChars:1, width: 300, delimiter: /(,|;)\s*/, deferRequestBy: 0, //miliseconds params: { artists: 'Yes' }, onSelect: functi ...

Finalizing an item's status

I am quite puzzled about the workings of closures in this particular code snippet: function Spy(target, method) { var result = {count: 0}, oldFn = target[method]; target[method] = function(input) { result.count++; return ol ...

Data from HTML not being transferred by Angular Forms

I am facing an issue with transferring input data from HTML's <select> element to Angular Forms. Let's take a look at my code first. File Name: home-page.component.html <form [formGroup]="rForm" (ngSubmit)="addPaste(rForm.value)"> ...

The object in three.js disappears from the scene but remains visible

I am attempting to showcase text as a sprite in three.js and aim to move the sprite along with an object. I achieve this by utilizing a canvas to generate a texture, which is then mapped using SpriteMaterial to create a sprite from it. However, when I remo ...

Javascript handling scrolling and repositioning

When using the scrollBy() method in the window object of JavaScript, there are two arguments required. But what do these arguments actually represent? The resource I am currently studying from states that it is "the number of pixels to scroll by," but I am ...

Is there a way to detect and intercept M-SEARCH requests in Express?

Here is my Express program designed to capture M-SEARCH requests: router['m-search']('/', function(req, res, next) { res.send('Received an M-SEARCH request\n'); }); This code specifically responds to the following r ...

Display a custom error message containing a string in an Angular error alert

How can I extract a specific string from an error message? I'm trying to retrieve the phrase "Bad Request" from this particular error message "400 - Bad Request URL: put: Message: Http failure response for : 400 Bad Request Details: "Bad Request ...

Recover files from the latest commit in Git, with files having no data inside them

Hello there! I encountered an issue with Git recently. I was attempting to clone a repository in order to push my project code, but I ran into an upstream error. I tried doing a git pull without success, then attempted to revert back to my initial commit ...

What is the best way to dynamically hide a textbox in JSP based on the selection of a

On my JSP page, I have a textbox and a checkbox. I attempted to use jQuery and JavaScript to hide the textbox when the checkbox is checked, but it doesn't seem to be working. Below is the code snippet: <p class="contact"> <input id="check" n ...

Revise class name attribute

When it comes to selecting a color for the avatar, I opt for a random color known as "randomColor." render() { const { classes } = this.props; let colorArr = [classes.redAvatar, classes.greenAvatar, classes.blueAvatar, classes.redAvatar]; co ...

Utilizing the ng-required directive with the model's value in AngularJS

I need to validate a form field for both null and its value. Can anyone suggest how I can achieve this without writing a function on the controller? <form name="frm"> <input type="text" ng-model="myModel" ng-required="myModel != '' || m ...

Executing Bower installation within a corporate proxy network

Encountering Error : ECONNREFUSED Request to https://bower.herokuapp.com/packages/bootstrap-datepicker failed: connect ECONNREFUSED while attempting Bower Install from Package Manager Console. I came across suggestions in a different discussion on how to ...

Transform Ajax response into dropdown menu option

I have made an ajax call and received HTML as a response. Now, I need to convert this output into options and add them to select tags on my webpage. <div class="views-element-container"> <div class="view view-contact-view-id-conta ...

Adjust the style of cursor - User Interface Expansion Panel Material Design

Using the MiU component "Expansion panel", I encountered an issue. By default, when the user hovers over the panel, the cursor is set to pointer. I attempted to change it to a default cursor, but my modification did not work. The code for my component is ...

The video is not appearing on mobile devices using Safari, Firefox, and Chrome, but it is displaying properly on desktop computers

My website has a video in the header that works fine on desktop but not on mobile. I am using next.js 13.4 and here is my code: <video id="background-video" autoPlay playsInline loop muted classN ...

Why won't Node.js let me redirect to my error page?

I've been putting together my newsletter project with the Mailchimp API, everything seems to be working fine except for when I try to redirect to a failure page if the status code is not 200. The browser shows an error message saying 'localhost r ...

ReactJS Components failing to load on initial site visit, only appearing after refreshing for the second time

var img; var dateFormat = require('dateformat'); var count; let arrayIMG = [] var storage = firebase.storage(); var storeRef = storage.ref('images/') const config = { ... }; if (!firebase.apps. ...

Completing a submission on a bootstrap form, using innerHTML and displaying an alert

I am currently having an issue with navigating to the home page after submitting a form in Bootstrap. Although I have successfully implemented an alert message upon submission, the page does not redirect to the home page as expected. Instead, it redirects ...

Angular and JavaScript Performing Slide-Up Animation

Currently, I am working on creating a menu using Angular and JavaScript. My goal is to have this menu toggle between showing and hiding when a button is clicked. If you would like to view the code that I have written so far, you can check out the demo her ...

"Ensure that all necessary fonts and assets are included in the development of your Vue component

At the moment, I am utilizing vue-cli-service build --target lib --name myLib [entry] to compile Vue into a component library for integration into other projects. Nevertheless, it only produces four files which are: dist/myLib.umd.min.js dist/myLib.umd. ...