Reputation: 9
I've got this setup:
Component A that uses a hook
Component B that imports component A
When testing B I'm dynamically reimporting it with a require(B)
on a beforeEach
and resetting modules via jest.resetModules()
Doing the dynamic import to update other mocked values.
That seems to cause Invariant Violation: Invalid hook call
. I'm not exactly sure why this happens. Did anyone run into this? What could be a fix here?
Here's a contrived example https://codesandbox.io/s/cocky-hodgkin-gz1tl, for some reason it runs fine in the sandbox but fails locally
Upvotes: 0
Views: 841
Reputation: 12174
The problem is with your Item
returning both state and function via items
.
export function Item() {
const items = React.useState([123, 234, 768]);
return <div>Items - {items}</div>; <--- problem
}
From useState()
:
It returns a pair of values: the current state and a function that updates it.
So it should be:
export function Item() {
const [items, setItems] = React.useState([123, 234, 768]);
return <div>Items - {items}</div>;
}
or
return <div>Items - {items[0]}</div> <--- return state only
Upvotes: 1