How to test the state of a functional component in React with Jest (No Enzyme)

10,368

Checking state in your tests lately has been considered a bad practice. What people generally recommend is to check the consequences of a state change: in your case, you could check the presence of CheckBoxOn.

Share:
10,368
Sebastian
Author by

Sebastian

Updated on July 25, 2022

Comments

  • Sebastian
    Sebastian almost 2 years

    Hi everybody how can I test the state of a functional component from the useState hook? This my component:

    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;
    

    How can I check the value of the state when I render the component with the selected props value to false and when I render it with selected prop to true? And how I can test if the click event on the button trigger setSelected()? By the way we are not able to use Enzyme