React 测试库 - 属性 'value' 在类型 'HTMLElement' 上不存在
React testing library - Property 'value' does not exist on type 'HTMLElement'
我有一个超级简单的表单,我正在尝试使用 React 测试库进行测试
形式如
import React, { useState } from 'react';
import './App.css';
function App() {
const [email, setEmail] = useState('')
const [password, setPassword] = useState('')
return (
<div className="App">
<form>
<label htmlFor="email">Email</label>
<input
type="email"
id="email"
name="email"
value={email}
onChange={e => setEmail(e.target.value)}
/>
<label htmlFor="password">Password</label>
<input
type="password"
id="password"
name="password"
value={password}
onChange={e => setPassword(e.target.value)}
/>
</form>
</div>
);
}
export default App;
并简单地尝试使用
测试输入
test('should be able to type an email', () => {
render(<App />)
const emailInput = screen.getByRole('textbox', {name: /email/i})
userEvent.type(emailInput, 'test@email.com')
expect(emailInput.value).toBe('test@email.com')
})
但是这个错误在 emailInput.value
说
Property 'value' does not exist on type 'HTMLElement'.
我在应用程序中使用打字稿,这与类型有关吗?我该如何解决这个问题
const emailInput = screen.getByRole<HTMLInputElement>('textbox', {name: /email/i})
应该适用于您的情况
我有一个超级简单的表单,我正在尝试使用 React 测试库进行测试
形式如
import React, { useState } from 'react';
import './App.css';
function App() {
const [email, setEmail] = useState('')
const [password, setPassword] = useState('')
return (
<div className="App">
<form>
<label htmlFor="email">Email</label>
<input
type="email"
id="email"
name="email"
value={email}
onChange={e => setEmail(e.target.value)}
/>
<label htmlFor="password">Password</label>
<input
type="password"
id="password"
name="password"
value={password}
onChange={e => setPassword(e.target.value)}
/>
</form>
</div>
);
}
export default App;
并简单地尝试使用
测试输入test('should be able to type an email', () => {
render(<App />)
const emailInput = screen.getByRole('textbox', {name: /email/i})
userEvent.type(emailInput, 'test@email.com')
expect(emailInput.value).toBe('test@email.com')
})
但是这个错误在 emailInput.value
说
Property 'value' does not exist on type 'HTMLElement'.
我在应用程序中使用打字稿,这与类型有关吗?我该如何解决这个问题
const emailInput = screen.getByRole<HTMLInputElement>('textbox', {name: /email/i})
应该适用于您的情况