Component:
const MyComponent = props => {
const {price} = props;
const result1 = useResult(price);
return (
<div>...</div>
)
}
Custom Hook:
export const useResult = (price) => {
const [result, setResult] = useState([]);
useEffect(() => {
const data = [{price: price}]
setResult(data);
}, [price]);
return result;
};
Jest test:
it('should ...', async () => {
render(
<MyComponent price={300}/>)
)
await waitFor(() => {
expect(...).toBeInTheDocument();
});
});
What it does happen with the above code is that MyComponent
, when running the test, renders only once instead of two (when the application runs). After the initial render where result1
is an empty array, useEffect
of useResult
is running and since there is a state change due to setResult(data)
, I should expect MyComponent
to be re-rendered. However, that's not the case and result1
still equals to []
whereas it should equal to [{price:300}]
.
Hence, it seems custom hooks under testing behave differently than the real app. I thought it would be okay to test them indirectly through the component that calls them.
Any explanation/thoughts for the above?
UPDATE
The issue that invoked the above erroneous behaviour was state mutation!! It worked with the app but not with the test! My mistake was to attempt to use push
in order to add an element to an array that was a state variable...
const data = ... //we build an array somehow
- is this a synchronous operation? – CurlpaperwaitFor
. I cannot be more clear... – Expositor