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
To properly test stateful functional components, it would be good to start with mocking the useState hook along with the setState function. The SearchReposInput component's purpose is to handle text entered by the user and pass it to the Redux action on button press.
- [Instructor] The Jest framework can be used to functionally test an application. The results can be included in a code coverage report, which is really useful. As a reminder, functional testing literally tests the functionality of an application.
so basically useState is the ability to encapsulate local state in a functional component. React has two types of components, one is class components which are ES6 classes that extend from React and the other is functional components.
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
.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With