我如何测试Material-ui RadioGroup按钮的更改以及RadioGroup prop'value'的后续更改(将其设置为本地状态(useState)值)
在更改事件上应该触发我嘲笑的handleChange
describe("test", () => {
test(`radio`, () => {
const handleChange = jest.fn();
const component = shallow(
<App />
);
const radioGroup = component.find(`[data-test="colorGroup"]`).at(0);
const blueRadio = radioGroup.find(`[label="blue"]`).at(0);
blueRadio.simulate(`click`, { checked: true });
expect(handleChange.mock.calls.length).toBe(1);
});
});
应用程序组件
export const App = () => {
const [color, setColor] = useState(`default`);
const handleOnChange = (event) => setColor(event.target.value);
return (
<Accordion elevation={0}>
<AccordionSummary
expandIcon={<ExpandMoreIcon />}
aria-controls="panel1a-content"
id="panel1a-header"
>
<Typography>choose color</Typography>
</AccordionSummary>
<AccordionDetails>
<FormControl component="fieldset">
<RadioGroup
row
onChange={handleOnChange}
value={color}
name="position"
data-test={`colorGroup`}
>
<FormControlLabel
value="default"
control={<Radio color="primary" />}
/>
<FormControlLabel
value="blue"
control={<Radio color="primary" />}
label="blue"
/>
</RadioGroup>
</FormControl>
</AccordionDetails>
</Accordion>
);
};
测试文件在component / home.spect.js中 https://codesandbox.io/s/sample-testing-in-react-using-jest-and-enzyme-forked-rrrct?fontsize=14&hidenavigation=1&theme=dark
答案 0 :(得分:0)
尝试这种方法,
describe("test", () => {
test(`radio`, () => {
// const handleChange = jest.fn();
const component = shallow(
<App />
);
const radioGroup = component.find(`[data-test="colorGroup"]`).at(0);
const blueRadio = radioGroup.find(`[label="blue"]`).at(0);
expect(radioGroup.props().value).toEqual('default'); //Initial value
radioGroup.props().onChange({target: {value: true}});
component.update();
expect(radioGroup.props().value).toEqual('blue'); //After onChange
});
});
让我知道您是否仍然面临同样的问题。