Dom-testing-library: Issue update the input value when using `useState` hook

Created on 7 Dec 2018  路  4Comments  路  Source: testing-library/dom-testing-library

I am having issues update the input value when using useState hook.

Relevant code or config:

const LoginForm = () => {
    const [form, setValues] = useState({
        username: '',
        password: '',
    });

    const updateField = (e: React.FormEvent<HTMLInputElement>): void => {
        setValues({
            ...form,
            [e.currentTarget.name]: e.currentTarget.value,
        });
    };

    return (
        <>
            <form onSubmit={performLogin}>
                <label htmlFor="username">
                    Username
                </label>
                <input
                    type="text"
                    value={form.username}
                    onChange={updateField}
                />

                <label htmlFor="password">
                    Password
                </label>
                <input
                    type="password"
                    value={form.password}
                    onChange={updateField}
                />
                <button type="submit">Login</button>
            </form>
        </>
    );
}

What you did:

I am trying to update the username and password but to no avail. My code looks like the following:

import React from 'react';
import { render, getByLabelText, getByText } from 'react-testing-library';

it('renders the Login Form and allows a user to login', async () => {
    const usernameInput = getByLabelText(/username/i);
    const passwordInput = getByLabelText(/password/i);
    usernameInput.value = 'Mary';
    passwordInput.value = '****';
    getByText(/Mary/i);
});

What happened:

screenshot 2018-12-07 at 17 25 13

Reproduction:

Here is a code sandbox - https://codesandbox.io/s/7j7o12qv96

All 4 comments

You should update them like this:

fireEvent.change(inputField, { target: { value: 'new value' } })

instead of

inputField.value = 'new value'

Have you tried that? I recall that the latter is no longer supported, but now reviewing the README I see that there are still examples in it using this way. If you confirm the first way of doing it in the examples above works, then maybe the README needs to be updated.

That works.

fireEvent.change(inputField, { target: { value: 'new value' } })

Also, I'm not sure getByText would find an input element with that text being its value. getByText is meant to find elements that have that textContent. That could be an issue here as well.

Tbh, I am testing a mock api call so I wanted to check the values were being sent to the mocked api call. I just put the getByText there for this question.

Was this page helpful?
0 / 5 - 0 ratings