Evaluating Material UI Radio Checked Value

  • I have created a functional component in React that utilizes Redux with React Hooks.
  • For testing, I am using Jest along with Enzyme.
  • The component contains Material UI Radio buttons which are rendered as shown in the code snippet below:
<RadioGroup>
  <FormControlLabel
    value="batchName"
    label="Batch Name"
    name="batchName"
    control={
      <Radio
        disableRipple
        name="batchName"
        color="primary"
        checked={searchBy === 'batchName'}
        onClick={() => {dispatch(actions.setBatchSearchBy('batchName'))}}
      />
    }
  />
  <FormControlLabel
    value="firstPaymentDate"
    label="First Payment Date"
    name="firstPaymentDate"
    control={
      <Radio:
        disableRipple
        name="firstPaymentDate"
        color="primary"
        checked={searchBy === 'firstPaymentDate'}
        onClick={() => {dispatch(actions.setBatchSearchBy('firstPaymentDate'))}}
      />
    }
  />
</RadioGroup>

Test file:

import React from 'react';
import { BatchHeaderComponent } from '../../../components/batchManagement/BatchHeaderComponent';
import configureStore from '../../../store';
import {Provider} from "react-redux";
import Enzyme, { mount } from "enzyme";
import Adapter from "enzyme-adapter-react-16";
import Radio from "@material-ui/core/Radio";

Enzyme.configure({ adapter: new Adapter() });

describe('BatchHeaderComponent', () => {
  it('mounts to the DOM with its sub-components', () => {
    const wrapper = mount(<Provider store={configureStore()}>
      <BatchHeaderComponent/>
    </Provider>);
    expect(wrapper.find(BatchHeaderComponent)).toBeDefined();
  });

  it('changes searchBy when a new option has been selected', () => {
    const wrapper = mount(<Provider store={configureStore()}>
      <BatchHeaderComponent />
    </Provider>);
    const radio = wrapper.find(Radio).last();
    console.log(radio.debug());
    // radio.simulate('change', {target: {name: 'firstPaymentDate', checked: true}});
    // radio.prop('onChange', {target: { name: 'firstPaymentDate', checked: true}});
    radio.simulate('click');
    console.log(radio.debug());
    expect(radio.props().checked).toEqual(true);
  });
});

The issue I am facing is that I cannot seem to change the 'checked' value when simulating a 'click' or 'change' event.

No matter what approach I try, the checked value remains false.

If anyone has any suggestions or advice on how to resolve this, it would be greatly appreciated. Thank you!

Answer №1

I finally figured it out. All I had to do was run the wrapper.find method again in order to see the updated change.

  it('verifies that the searchBy value changes when a new option is selected', () => {
    const wrapper = mount(<Provider store={configureStore()}>
      <BatchHeaderComponent />
    </Provider>);
    const radio = wrapper.find(Radio).last();
    radio.simulate('click');
    expect(wrapper.find(Radio).last().props().checked).toEqual(true);
  });

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

Activate the useEffect function in react

I am retrieving data from a Firebase database and it works when the component initially renders. However, I am struggling to make it fetch again whenever there is a new entry in the database. Here is what I've attempted: I tried passing a state var ...

Obtaining User Input in React JS within the Fetch Statement

I've written a code to fetch weather data from an API. Currently, the location is set to "chennai" in the link provided. I'd like to make this location user-dependent. How can I achieve this using React? import React,{useState,useEffect} from ...

Changing from system mode to dark mode or light mode

Within my Next.js web application, I am implementing MUI to facilitate the transition between system, light, and dark modes. Persistence between sessions is achieved by storing the selected theme in local storage. The user has the option to change the them ...

Exploring the transparency of material lab autocomplete drop-down text for enabling multiple selections

Check out this demo for checkboxes and tags in Material UI The code below demonstrates an autocomplete component that functions correctly. However, the drop-down text appears transparent. Is there a way to fix this issue without modifying any libraries? ...

Encountering a Hydration Error with Next.JS and MDX-Bundler when a MDX Component Adds Extra New Lines to its Children

Currently, I am incorporating next.js + mdx-bundler into my project. There is a simple component that I frequently use in my mdx files. Everything runs smoothly with the following code: Mdx is a great <Component>format and I like it a lot</Compon ...

The AnchorEL component becomes unusable once a function has been executed for the first time

I am facing a challenge with anchorRef and struggling to understand how it works as I am new to React and have never used it before. After the onClickAway method is called, Material-UI shows an error stating that the anchorRef is set to null, but this warn ...

The variable 'React' has been declared but appears to be unused, what might be causing this problem?

Currently, I am developing a contact application using Python with React. While utilizing Vite and Flask for development, I encountered an error stating that 'React' is defined but never used. Below is a snippet of my code structure: This sectio ...

The AWS Beanstalk CLI continues to deploy React and npm development builds

I have a React application along with two AWS Beanstalk instances: one for development and the other for production. My goal is to deploy the development build of the React app to the development environment and the production build to the production envir ...

It appears that custom metrics are not being logged in AWS CloudWatch Experiment

After setting up my Evidently project with one feature and a custom metric, I am facing an issue where Evidently is failing to record any events. Despite simplifying the troubleshooting process by using command line evaluation and event sending, the proble ...

How to trigger a function when clicking on a TableRow in React using MaterialUI

Can someone help me understand how to add an onClick listener to my TableRow in React? I noticed that simply giving an onClick prop like this seemed to work: <TableRow onClick = {()=> console.log("clicked")}> <TableCell> Content </Ta ...

Having trouble getting card animations to slide down using React Spring

I am currently learning React and attempting to create a slide-down animation for my div element using react-spring. However, I am facing an issue where the slide-down effect is not functioning as expected even though I followed a tutorial for implementati ...

Creating a dynamic className string in JavaScript with React

In my current project, I'm implementing mobile support by creating separate styles for desktop and mobile. Although most components are the same on both platforms, I have two .scss files dedicated to each. To apply the correct styles, I use a combina ...

Tips for deactivating a single edit button

Is there a way to make it so that when I click on a checkbox, only that specific todo's edit button is disabled? Currently, clicking on a checkbox disables all edit buttons in the todo list. Any suggestions? class App extends Component { state ...

What techniques does the material-ui modal component use to restrict resizing to a minimum width?

I am currently trying to find a way to stop a Chrome browser window from automatically resizing my web application below a specific width when viewed on a desktop. However, I have come across an issue with the material-ui modal component that prevents me f ...

Discovering a solution to extract a value from an Array of objects without explicitly referencing the key has proven to be quite challenging, as my extensive online research has failed to yield any similar or closely related problems

So I had this specific constant value const uniqueObjArr = [ { asdfgfjhjkl:"example 123" }, { qwertyuiop:"example 456" }, { zxcvbnmqwerty:"example 678" }, ] I aim to retrieve the ...

Issue: attempting to push to a stream after reaching the end of the file in React

I am attempting to utilize react-pdf to open a PDF document. const DisplayPDF = () => { const [data, setData] = useState(() => { const storedData = localStorage.getItem('pdfData'); return JSON.parse(storedData); }); useEffec ...

What is the best way to create mock icons for all the React `@material-ui/icons` using Jest?

Can this query be broadened to ask - what is the best way to simulate all attributes on a module that has been imported in order to produce React components? ...

Issue with Server Sent Events: Error message net::ERR_INCOMPLETE_CHUNKED_ENCODING 200 is preventing proper functionality

I've been working on implementing server-sent events using the code below (nodejs+express for backend and React for the frontend). However, I am facing an issue where the onmessage event is not triggering when I try to update the count through the ter ...

Experiencing issues with sending log messages symbolicatedStack on react native and expo

After updating to the latest versions of react (0.62.2) and expo (37.0.12), most things were working fine. However, I kept encountering an error screen that would pop up each time I reloaded the app or shortly after an error occurred. console.error: There ...

Encountering various instances of "There are multiple modules with names that only differ in casing."

I'm currently working on a project using NextJS and Antdesign for the frontend development. As I attempt to create a basic login feature utilizing the Form components provided by AntDesign, I am encountering a barrage of errors. Specifically, I am see ...