Reputation: 6347
In a class based component I can easily access state by doing:
const control = shallow(<Test />);
control.state()
For a hooks based component like the one below, how can I access count
from my test?
const Test = () => {
const [count, setCount] = useState(0);
return (
<>
<button onClick={() => setCount(count + 1)}>Count</button>
<div>{count}</div>
</>
)
}
Upvotes: 3
Views: 6722
Reputation: 2365
It is not possible, and it shouldn't be, given that the state is an implementation detail. If you rename the state to myCount
, the component still works, but the test would fail.
However, since you render the count, you can simply expect that the correct count is rendered.
Example using react-testing-library
:
import { render, fireEvent } from 'react-testing-library'
const rendered = render(<Test />)
rendered.getByText(0) // Test that 0 is present in the DOM
fireEvent.click(rendered.getByText('Count'))
rendered.getByText(0) // Test that 1 is present in the DOM
If you really want to test the state updates in isolation, you can useReducer
, and test the reducer easily with jest
, since it is a pure JavaScript function.
Upvotes: 6