我到处都搜索了它,但是找不到该问题的答案。我有React功能组件,它从给定选项的数组中选择选项。 1. Main Home组件具有第一个选项的初始状态,并设置为: 2. OptionComponent中的代码 3.到目前为止,我的测试代码。我想为所有选项添加测试:
const [optionState, setOption] = React.useState('option1'); // set as the first Array Element
const handleSelectOption = selectedValue => {
setOption(selectedValue);
};
return(
<OptionComponent onSelectOption={handleSelectOption} />
);
//2:
const handleChange = event => {
props.onSelectOption(event.target.value);
}; //this i used to pass props from child to parent
const optionsArray = [
'option1',
'option2',
'option3'];
return (
<select
onChange={handleChange}
>
{optionsArray.map(opt => (
<option key={opt}>{opt}</option>
))}
</select>
);
//3:
describe('Option Component', () => {
const values = [
'option1',
'option2',
'option3'];
const secondValue = values[0];
const onChange = jest.fn();
let wrapper;
it('first test', () => {
wrapper = shallow(<OptionComponent />);
expect(wrapper).toMatchSnapshot();
wrapper.update();
wrapper.find('select').props().props.onChange({target:{value: undefined}});
//I changed simulate to props.onChange because simulate did NOT work
// .props().props.onChange exists beacause without
//props onSelectOption could not bw found.
expect(onChange).toBe({secondValue});
});
});```