React Testing Library - multiple fireEvent doesn't check text

Viewed 1199

I would like to text my component. I have form with select and paragraph with text. When I choose from select 6, the paragraph change text to '6 pieces'. When I choose from select 9, the paragraph change text to '9 pieces' etc.

The problem is, it works only on first time. On the second I have old text in paragraph. How can I refresh every select change?

const { getByTestId } = renderForm();

const textElem = getByTestId('text');
const select = getByTestId('select');


fireEvent.change(select, { target: { value: '6' } });

// works fine
expect(textElem).toHaveTextContent('6 pieces');


fireEvent.change(select, { target: { value: '9' } });

// is still 6 pieces
expect(textElem).toHaveTextContent('9 pieces');

I've tried also with act, but I've got the same results:

act(()=>{
    fireEvent.change(select, { target: { value: '6' } });
});

// works fine
expect(textElem).toHaveTextContent('6 pieces');


act(()=>{
    fireEvent.change(select, { target: { value: '9' } });
});

// is still 6 pieces
expect(textElem).toHaveTextContent('9 pieces');

Also I tried with rerender - same results.

1 Answers

After triggering the change, you need to do a new getByTestId() and assert on that.

fireEvent.change(select, { target: { value: '9' } }); expect(getByTestId('text')).toHaveTextContent('9 pieces')

Related