如何在事件发生后更新包装器
我正在使用 jest 和酶来测试我的 React 组件。
我面临一个问题,在更改 dom 的事件之后我无法获取最新的 DOM 树。
Home 组件:
export class Home extends React.Component {
render() {
return <RadioFieldClass />
}
}
RadioField 组件:
const RadioField = props => {
const [option, setOption] = useState({});
const handleChange = (e) => {
const { name, value } = e.target;
setOption({...option, [name]: value});
}
return (
<>
<p>Select an option</p>
<div onChange={handleChange}>
<input type="radio" value="male" name="gender" />Male
<input type="radio" value="female" name="gender" />Female
{option.gender && option.gender === 'male' &&
<b>You are a male</b>
}
{option.gender && option.gender === 'female' &&
<i>You are a female</i>
}
</div>
</>
)
}
测试套件:
describe('testing events', () => {
it('should render b or i tag onChange', () => {
let wrapper = shallow(<Home />);
const Radio = wrapper.find('RadioField').dive();
const event = {target: {value: 'male'}}
Radio.find('div').props().onChange(event);
wrapper.update();
expect(wrapper.find('RadioField').dive().find('div').find('b').exists()).toBe(true);
})
})
上述测试套件失败。
I am using jest and enzyme to test my React component.
I am facing an issue where I don't get the most recent DOM tree after an event which changes the dom.
Home Component:
export class Home extends React.Component {
render() {
return <RadioFieldClass />
}
}
RadioField Component:
const RadioField = props => {
const [option, setOption] = useState({});
const handleChange = (e) => {
const { name, value } = e.target;
setOption({...option, [name]: value});
}
return (
<>
<p>Select an option</p>
<div onChange={handleChange}>
<input type="radio" value="male" name="gender" />Male
<input type="radio" value="female" name="gender" />Female
{option.gender && option.gender === 'male' &&
<b>You are a male</b>
}
{option.gender && option.gender === 'female' &&
<i>You are a female</i>
}
</div>
</>
)
}
Test Suit:
describe('testing events', () => {
it('should render b or i tag onChange', () => {
let wrapper = shallow(<Home />);
const Radio = wrapper.find('RadioField').dive();
const event = {target: {value: 'male'}}
Radio.find('div').props().onChange(event);
wrapper.update();
expect(wrapper.find('RadioField').dive().find('div').find('b').exists()).toBe(true);
})
})
The above test suit is failing.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论