jeudi 21 mai 2020

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

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=>
                    {props.title}
                </Text>
                {props.subtitle && <Text style=>{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

Aucun commentaire:

Enregistrer un commentaire