userEvent.type 未更新测试中输入的值

Sir*_*oob 27 testing input reactjs

我正在测试这个组件,它只是根据输入字段中的新输入来更改其状态,并将输入元素的值设置为该状态。

function Login () {
    //Login Credentials
    const [loginCredentials, setLoginCredentials] = useState({ name: '' })
    const handleChange = ({target}) => {
        setLoginCredentials(prev => ({ ...prev, [target.name]: target.value }));
    }

    return (
            <div className="login-container">
                <h1>Log In</h1>
                    <div className="login-label-input">
                        <label htmlFor="name">Account Name
                            <input
                            type="name"
                            id="name"
                            name="name"
                            placeholder="Enter Name"
                            onChange={handleChange}
                            value={loginCredentials.name}
                            aria-label="name"
                            />
                        </label>
                  </div>
             </div>
    )
}
Run Code Online (Sandbox Code Playgroud)

由于某种原因,此测试不会在 screen.debug() 中显示输入值“testUser”,而仅显示“t”....


    test("log in with empty name input returns error message",  () => {
    render(<Login />)
    const nameField = screen.getByLabelText(/account name/i);
    userEvent.type(nameField, 'testUser'); 
    screen.debug()
});

Run Code Online (Sandbox Code Playgroud)

这不应该起作用吗?为什么不呢?摘自 screen.debug():

function Login () {
    //Login Credentials
    const [loginCredentials, setLoginCredentials] = useState({ name: '' })
    const handleChange = ({target}) => {
        setLoginCredentials(prev => ({ ...prev, [target.name]: target.value }));
    }

    return (
            <div className="login-container">
                <h1>Log In</h1>
                    <div className="login-label-input">
                        <label htmlFor="name">Account Name
                            <input
                            type="name"
                            id="name"
                            name="name"
                            placeholder="Enter Name"
                            onChange={handleChange}
                            value={loginCredentials.name}
                            aria-label="name"
                            />
                        </label>
                  </div>
             </div>
    )
}
Run Code Online (Sandbox Code Playgroud)

ana*_*912 52

在当前版本@testing-library/user-event: ^14.2.0及其对应的官方文档中,有一个userEvent.type等待调用的示例:

test('type into an input field', async () => {
  render(<input defaultValue="Hello," />)
  const input = screen.getByRole('textbox')

  await userEvent.type(input, ' World!')

  expect(input).toHaveValue('Hello, World!')
})
Run Code Online (Sandbox Code Playgroud)

async当然,test() 中的回调需要像这样声明。

在撰写本文时,链接到文档中的此内容:https ://testing-library.com/docs/user-event/utility/#type

也许很高兴知道:也适用于不受控制的组件。