react-testing-library: Form Inputs not updating after change event is fired

  • react-testing-library version: 4.1.5
  • react version: 16.4.1
  • node version: 8.6.0
  • npm (or yarn) version: 6.2.0

Relevant code or config:

test('submits form successfully', async () => {

const { getByText, queryByText, getByLabelText, debug } = renderWithRouter(
<SignIn setCurrentUser={jest.fn()} isSignedIn={false} history={{}} />
);

const submitButton = getByText('Sign In');
const emailInput = getByLabelText('Email');
const passwordInput = getByLabelText('Password');

emailInput.value = 'test@test.com';
passwordInput.value = '12345678';

fireEvent.change(emailInput);
fireEvent.change(passwordInput);

debug();
/* 
In debug email has value of 'test@test.com' and password has a value of ' ' 
*/

fireEvent.click(submitButton);

const emailErrorNode = queryByText('Email is required');
const passwordErrorNode = queryByText('Password is required')

expect(emailErrorNode).toBeNull();
expect(passwordErrorNode).toBeNull();

});

What you did:

Test a sign in form by setting username to ‘test@test.com’ and password to ‘12345678’

What happened:

When updating 2 inputs in a test, only one input gets updated the second input’s value is ’ ’ (empty)

Reproduction:

https://codesandbox.io/s/0xwn98wo1p

Problem description:

I can’t test forms with more than one field change

Suggested solution:

About this issue

  • Original URL
  • State: closed
  • Created 6 years ago
  • Reactions: 3
  • Comments: 21 (14 by maintainers)

Commits related to this issue

Most upvoted comments

Ok, so this bug happened due to the way React works, and now dom-testing-library’s fireEvent utility supports setting properties on the target element when you fire an event. This allows you to set the value at the time of the event and dom-testing-library will set it in a way that works around how React tracks input value changes.

Here’s how you use it: https://codesandbox.io/s/github/kentcdodds/react-testing-library-examples/tree/master/?module=%2Fsrc%2F__tests__%2Fon-change.js&previewwindow=tests

Here’s the basic example:

fireEvent.change(passwordInput, {target: {value: '12345678'}})

🎉

Thanks! Now we gotta figure out how to help people avoid this in the future 🤔

Yes, if you’re going to fire a change event then that’s how the value should be changed. Otherwise manipulating the value should work fine.

fireEvent.change(passwordInput, {target: {value: '12345678'}})

This should definitely be added to the README file.

@pcfields, if you’d like to open a PR that makes this work in dom-testing-library that’d be great. I think that’s the right place for this change because even though it’s kind of an implementation detail for react it doesn’t impact how things work for other frameworks and I believe that Cypress (another framework-agnostic tool) handles this case.

We’ll definitely want some good comments for this though…