pmiranda
pmiranda

Reputation: 8440

Jest on React, local state with useState

I have a component with:

const [state, setState] = useState({
reasonSelected: ''});

where in the render I got:

        { state.reasonSelected === 'other' && (
          <Input
            testID='reasonInput'
            value={state.reasonOther}
            onChangeText={ text => {
              setState({ ...state, reasonOther: text });
            }}
          />
        )}

So, if local state.reasonSelected is 'other' I can get rendered that componente.

I'm trying this test:

const otherReasonInput = rendered.getByTestId('reasonInput');
expect(otherReasonInput).toBeTruthy();

But in my test, how can I get the state.reasonSelected to be actually "other" in order to get Input rendered?

Upvotes: 1

Views: 69

Answers (1)

pmiranda
pmiranda

Reputation: 8440

I'm not sure if this is the valid answer, but what I did was this:

const pickerReason = rendered.getByTestId('reasonPicker');
// that it comes fron a component that if I change the value to other, will set the state to the desire one, so I want to actually change that values with:
fireEvent.valueChange(pickerReason, 'Otro');

Now the setState should be called as I wanted. Of course, I didn't put that part of the code in the original code, but the solution comes to mind after reading some other threads.

By calling to valueChanges the setState is called with the value that I pass by parameter, so everything goes ok.

Upvotes: 1

Related Questions