Im using react hooks and using Use State for component states. While testing the component in jest i see i cant access state value and mock it either.
There are bunches of code which is looking for different values in state. since state is not acccesible i could t cover complete code coverage.
Please help me in writting a test case for below code.
const MyComponent = props => {
const [counterSecond, setCounterSecond] = React.useState(8);
const [counterFirst, setCounterFirst] = React.useState(0);
const handleIncrement = () => {
setCounterSecond(counterSecond + 1);
};
const handleDecrement = () => {
setCounterSecond(counterSecond - 1);
};
React.useEffect(() => {
if (counterSecond === 10) {
setCounterSecond(0);
setCounterFirst(1);
}
if (counterSecond === 3) {
setCounterSecond(1);
setCounterFirst(0);
}
if (counterSecond ===9) {
setCounterSecond(2);
setCounterFirst(1);
}
}, [counterSecond]);
return (
<div>
<div onClick={handleIncrement} >Increment</div>
<div onClick={handleDecrement} >Decrement</div>
</div>
);
};
export default MyComponent;
As you see the code is having useEffect, which looks after for the change in counterSecond value. But the internal conditions will only be covered when the state value matches 8 Or 3 Or 9.
Could you please guide me in writing Jest test case to cover the internal conditions in UserEffect.
1) And how to mock any state value
2) how to check of state value in Jest while using Hooks
render
– skyboyer