Seb*_*ian 13 javascript testing unit-testing reactjs jestjs
大家好,我如何从 useState 挂钩测试功能组件的状态?这是我的组件:
const Container = styled.div
display: flex;
flex: 1;
flex-direction: row;
align-items: ${props => props.hasSubtitle ? 'flex-start' : 'center'};
opacity: ${props => props.disabled ? 0.5 : 1.0};
${props => props.style}
const Button = styled.button
padding: 0;
border: none;
background: none;
cursor: pointer;
outline: none;
const TextContainer = styled.div
display: flex;
flex: 1;
flex-direction: column;
margin-left: 12px;
const CheckBox = props => {
const [selected, setSelected] = useState(false);
useEffect(() => {
setSelected(props.selected);
}, [props.selected]);
return (
<Container data-testid={'checkbox'} style={props.style} hasSubtitle={props.subtitle}>
<Button
data-testid={'checkBtn'}
onClick={() => {
if(!props.disabled){
setSelected(!selected);
if(props.onChange) props.onChange(!selected);
}
}}
>
{selected ? <CheckBoxOn/> : <CheckBoxOff/>}
</Button>
<TextContainer>
<Text style={{fontSize: 16}}>
{props.title}
</Text>
{props.subtitle && <Text style={{fontSize: 12}}>{props.subtitle}</Text>}
</TextContainer>
</Container>
);
};
export default CheckBox;
Run Code Online (Sandbox Code Playgroud)
当我将所选 props 值渲染为 false 的组件以及将所选 props 渲染为 true 时,如何检查状态值?如何测试按钮上的单击事件是否触发 setSelected()?顺便说一句,我们不能使用酶
cle*_*son 11
最近在测试中检查状态被认为是一种不好的做法。人们通常建议检查状态更改的后果:在您的情况下,您可以检查CheckBoxOn.
| 归档时间: |
|
| 查看次数: |
24221 次 |
| 最近记录: |