在 dom-testing-library
/react-testing-library
中,测试一个元素的值,最好的方法是什么?
我的做法是通过 closest()
方法获取原始的输入元素本身,这样我就可以直接访问 value
属性:
const input = getByLabelText("Some Label")
expect(input.closest("input").value).toEqual("Some Value")
我希望有一种方法可以在不直接访问HTML属性的情况下完成这个任务。这似乎不符合测试库的精神。也许可以使用像jest-dom toHaveTextContent matcher这样的匹配器:
const input = getByLabelText("Some Label")
expect(input).toHaveTextContent("Some Value")
更新
根据评论中的请求,这里有一个代码示例,展示了我在构建应用时遇到需要测试输入框值的情况。
这是我在应用程序中构建的一个模态组件的简化版本。整个想法是,基于一个字符串prop,模态框打开并预填充了一些文本。用户可以自由编辑该输入,并通过按下按钮提交它。但是,如果用户关闭模态框,然后重新打开它,我希望将文本重置为原始的字符串prop。我编写了一个测试,因为模态框的先前版本未能重置输入值。
我正在使用TypeScript编写此内容,以便每个prop的类型非常清晰。
interface Props {
onClose: () => void
isOpen: boolean
initialValue: string
}
export default function MyModal({ onClose, isOpen, initialValue }) {
const [inputValue, setInputValue] = useState(initialValue)
// useEffect does the reset!
useEffect(() => {
if (!isOpen) {
setNameInput(initialValue)
}
}, [isOpen, initialValue])
return (
<SomeExternalLibraryModal isOpen={isOpen} onClose={onClose}>
<form>
<input
value={inputValue}
onChange={(e: ChangeEvent<HTMLInputElement>) =>
setInputValue(e.target.value)
}
/>
<button onClick={onClose}>Cancel</button>
</form>
</SomeExternalLibraryModal>
)
}
inputValue
?我在value={inputValue}
中看到它,但那是用于输入栏的,当用户点击按钮时你在哪里使用它? - Arnaud ClaudelinputValue
用于类似于单击“更新”按钮时表单的onSubmit
处理程序之类的东西(再次强调,由于与我最初的问题无关,因此被省略)。 - ecbrodie