Struggling with testing the checkbox when it changes inside the CardHeader Avatar={} component

I've recently implemented a feature similar to the example showcased on MaterialUI's TransferList. However, I'm encountering difficulties accessing a checkbox within the avatar={}. The project utilizes Jest and Enzyme for testing purposes. To streamline the process, I included IDs to elements I intend to test, aiding in the utilization of the .find function.

export interface IListItem {
   itemId: number;
   itemName: string;
   isChecked: boolean;
}

interface IProps {
   listName: string;
   list: IListItem[];
   setList: any;
}

function checkAllItems(check: boolean, list: IListItem[], setList: any) {
   let tempList = [...list];
   for (var item of tempList) {
      item.isChecked = check;
   }
   setList(tempList);
}

export function ToggleableListComponent({ listName, list, setList }: IProps) {
  return (
    <CardHeader
       id="check-all-card"
       avatar={
         <Checkbox
           id="check-all"
           checked={areAllItemsChecked(list)}
           onChange={(e) => checkAllItems(e.target.checked, list, setList)}
         />
       }
       title={listName}
       subheader={`${numberOfChecked(list)}/${list.length} selected`}
  />)}

I am attempting to access the checkbox using the .find enzyme function to simulate a change event.

it("Tests checking all items in list", () => {
   let defaultProps = {
      listName: "test",
      list: [] as IListItem[],
      setList: jest.fn(),
   }
    const mockedEvent = { target: {checked: true}};
    const wrapper = shallow(
      <ToggleableListComponent {...defaultProps} />
    );
    wrapper.find("#check-all").simulate("change", mockedEvent); 
}

The error message "Method “simulate” is meant to be run on 1 node. 0 found instead." crops up upon executing the above line. How can I successfully access that checkbox to trigger the change event?

Please inform me if further details are required.

Answer №1

I was intrigued and took the opportunity to replicate it myself, so here is the issue at hand.

Firstly, make sure to utilize mount instead of shallow so that all your child components (including the avatar checkbox) are rendered. The reason you encounter an error is due to using shallow.

Method “simulate” is meant to be run on 1 node. 0 found instead.

This error indicates that wrapper.find could not find a specific selector, implying that your checkbox did not render.

However, simply changing from shallow to mount leads to the next error:

Method “simulate” is meant to be run on 1 node. 5 found instead.

This suggests that there are 5 elements with the id="check-all", which initially seems illogical.

Upon inspecting the markup of the rendered component with console.log(wrapper.debug()), you'll notice that Material-UI creates multiple wrappers over your checkbox with IDENTICAL ATTRIBUTES (including the id). Hence, resulting in 5 elements sharing the same id.

To resolve this issue, specify the selector by examining the rendered tree in the console. The following selector proves effective:

".MuiIconButton-label > #check-all"

Your test should be structured as follows:

it("Tests checking all items in list", () => {
   let defaultProps = {
      listName: "test",
      list: [] as IListItem[],
      setList: jest.fn(),
   }
    const mockedEvent = { target: {checked: true}};
    
    // utilizing mount instead of shallow
    const wrapper = mount(
      <ToggleableListComponent {...defaultProps} />
    );

    // employing the new selector .MuiIconButton-label > #check-all
    wrapper.find(".MuiIconButton-label > #check-all").simulate("change", mockedEvent); 
    ...
}

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

Sorting a function with two parameters in descending order is possible even when dealing with an empty array and no initial value for reduction

My npm test is not passing the third out of six tests. I have attempted to sort it using the following code snippet: sumAll.sort(function(min,max)) { return max - min; } However, this approach did not work. I also tried incorporating conditionals in t ...

Incorporate a JavaScript script into an Angular 9 application

I have been experiencing issues trying to add a script.js file to angular.json and use it in one component. Adding a script tag directly to my HTML file is not the ideal solution. Can someone suggest an alternative approach or point out what I may be missi ...

Utilizing properties from the same object based on certain conditions

Here's a perplexing query that's been on my mind lately. I have this object with all the styles I need to apply to an element in my React app. const LinkStyle = { textDecoration : 'none', color : 'rgba(58, 62, 65, 1)', ...

Designing an interactive header interface using React and Material UI

My header.jsx file contains the following code: // Default Import Statements var Login = require(login.jsx) const HeaderComponent = React.createClass({ getInitialState () { return { loggedIn: false, }; }, render() { return ( ...

The value entered for creating a payment method is invalid: the card must be in the form of an object

I am in the process of setting up a payment method using the Next.js library from Stripe. Here is the code snippet: import React, { FunctionComponent } from 'react'; import type { DisplaySettingsProps } from '@company/frontoffice/types' ...

Every time I navigate to a new page in NextJs, the useEffect hook

I am working on developing a new blog app with Next.js. In the current layout of the blog, I have successfully fetched data for my sidebar (to display "recent posts") using the useEffect/fetch method, as getInitialProps only works on Pages. However, this ...

How do I incorporate scrolling into Material-UI Tabs?

I am currently incorporating Material-ui Tablist into my AppBar component. However, I am facing an issue with the responsiveness of the tabs. When there are too many tabs, some of them become hidden on smaller screens. For more information on the componen ...

When invoking a function, a React Component utilizes the props from the first element instead of its own

Whenever I try to invoke a function of a component, it seems to be replacing the parameters and passing the props of the first array element instead of the selected one. To illustrate this issue, let's take a look at some code: Firstly, here is how ...

Issue with React Routes only occurring in the production website

I'm encountering an issue on my personal website that only occurs in production, but not in my local environment. Here's the situation: I have set up the routes as follows const Routes = () => ( <Router> <Route exact path=&quo ...

Issue with `styles` argument after updating from Material version 4 to 5: MUI

After recently upgrading from Material V4 to V5, I encountered the following error message: MUI: The `styles` argument provided is invalid. You are providing a function without a theme in the context. One of the parent elements needs to use a ThemeProvider ...

Encountered an issue while attempting npm install, with the error message "Error: Undefined variable standalone_static_library in binding.gyp" and node-sass chokidar error

I've been working on updating a Ruby on Rails and React project from 3 years ago. However, I encountered an issue while trying to npm install. $ npm install gyp: Undefined variable standalone_static_library in binding.gyp while trying to load binding ...

How can the required flag be integrated with rules validation in react-hook-form and material-ui (mui) for inputs?

Currently, I have implemented react-hook-forms for handling form functionality and validation in our application. On the other hand, we are utilizing MUI/Material-UI as our component library. One issue that arises is that MUI automatically adds a * to inpu ...

What is the best way to assign a unique background color to each individual card in my card list?

I have a list of cards and I want to assign a unique color to each card in the list. I attempted to do this on my own, but it ended up being more complex than I anticipated. Here is the list of cards: return ( <Container> <Row className=&qu ...

Using the DatePicker component with non-escaped Latin alphabet characters in date-fns for ReactJS

While attempting to integrate the DatePicker component from Material UI into my React project, I encountered an error. Although many attributed the issue to a version discrepancy, what ultimately resolved the problem for me was assigning a value to the Da ...

typescript defining callback parameter type based on callback arguments

function funcOneCustom<T extends boolean = false>(isTrue: T) { type RETURN = T extends true ? string : number; return (isTrue ? "Nice" : 20) as RETURN; } function funcCbCustom<T>(cb: (isTrue: boolean) => T) { const getFirst = () => ...

"Troubleshooting issue: Popup in react-leaflet fails to display upon clicking

Currently, I have integrated react-leaflet into my ReactJS application to dynamically create markers with popups. However, when implementing the code as shown below, the popup box fails to display and an error message appears in the web developer console. ...

Is it possible to use both material-ui@next and the previous version concurrently?

I need some advice on a project I am working on that utilizes material-ui@next (v1). While I appreciate the new features in the latest autocomplete, I find it too complex for my needs. Instead, I would like to revert back to the older version of the autoco ...

Can you explain the concept of F-Bounded Polymorphism in TypeScript?

Version 1.8 of TypeScript caught my attention because it now supports F-Bounded Polymorphism. Can you help me understand what this feature is in simple terms and how it can be beneficial? I assume that its early inclusion signifies its significance. ...

The TypeScript error message states that a value of 'undefined' cannot be assigned to a type that expects either a boolean, Connection

I've been grappling with this code snippet for a while now. It was originally written in JavaScript a few months back, but recently I decided to delve into TypeScript. However, I'm struggling to understand how data types are properly defined in T ...

Unique rephrased text: "Varied wrapping styles in both

Feeling frustrated with a seemingly commonplace issue. Despite the thousands of times it has been asked before, I can't seem to find an answer on Google. I wanted to neatly display my text within one of my cards, but so far I've only achieved th ...