我正在使用 TypeScript 构建一个 React 应用程序。我使用 React 测试库进行组件测试。
假设您有这样的简单形式:
import React from 'react'
function Login({onSubmit}) {
return (
<div>
<form
onSubmit={e => {
e.preventDefault()
const {username, password} = e.target.elements
onSubmit({
username: username.value,
password: password.value,
})
}}
>
<label htmlFor="username">Username</label>
<input id="username" />
<label htmlFor="password">Password</label>
<input id="password" type="password" />
<br />
<button type="submit">Submit</button>
</form>
</div>
)
}
export {Login}
在此视频中,Kent(库的创建者)展示了如何测试表单输入输入。测试看起来像这样:
import React from 'react'
import {renderIntoDocument, cleanup} from 'react-testing-library'
import {Login} from '../login'
afterEach(cleanup)
test('calls onSubmit with username and password', () => {
const handleSubmit = jest.fn()
const {getByLabelText, getByText} = renderIntoDocument(
<Login onSubmit={handleSubmit} />,
)
getByLabelText(/username/i).value = 'chuck'
getByLabelText(/password/i).value = 'norris'
getByText(/submit/i).click()
expect(handleSubmit).toHaveBeenCalledTimes(1)
expect(handleSubmit).toHaveBeenCalledWith({
username: 'chuck',
password: 'norris',
})
})
问题是他用纯 JavaScript 做到了。使用 TypeScript 执行此操作时,他设置的行.value
会引发以下错误
[ts] Property 'value' does not exist on type 'HTMLElement'.
如何使用 React 测试库使用 TypeScript 测试此功能?您将如何设置输入的值?