Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Accessing useState value from jest test

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>
        </>
    )
}
like image 204
blankface Avatar asked Jan 18 '26 12:01

blankface


1 Answers

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.

Alternative 1: Test the DOM

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

Alternative 2: Extract the state logic in a reducer, and test the reducer

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.

like image 197
Matthieu Libeer Avatar answered Jan 21 '26 04:01

Matthieu Libeer