【发布时间】:2019-04-11 05:34:11
【问题描述】:
我正在使用 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}
在this videoKent(库的创建者)中展示了您将如何测试表单输入输入。测试如下所示:
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 测试此功能?您将如何设置输入的值?
【问题讨论】:
标签: reactjs typescript unit-testing htmlelements react-testing-library