blankface
blankface

Reputation: 6347

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>
        </>
    )
}

Upvotes: 3

Views: 6722

Answers (1)

Matthieu Libeer
Matthieu Libeer

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.

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.

Upvotes: 6

Related Questions