我正在尝试测试 React 组件中的按钮启用和禁用。问题是按钮从未启用,并且由于我对validateEmail()
和validateForm()
inside的调用而从未启用handleInputChange()
。我尝试删除这些调用并将它设置isValid
为 true,它成功了。
我的联系人功能组件中的功能:
const [formData, setFormData] = useState({
firstName: '',
lastName: '',
email: '',
message: '',
})
const [isValid, setIsValid] = useState(false)
function validateForm(obj) {
return Object.values(obj).every((v) => v.length > 0)
}
const validateEmail = (email) => {
let re = /\S+@\S+\.\S+/
return re.test(email)
}
const handleInputChange = (e) => {
const { name, value } = e.target
setFormData({
...formData,
[name]: value,
})
if (validateEmail(formData.email) && validateForm(formData)) {
setIsValid(true)
}
}
然后我有几个输入和一个按钮:
<InputField
type="email"
name="email"
id="email"
autocomplete="email"
onChange={(e) => handleInputChange(e)}
label="Email"
value={formData.email}
testId="email"
/>
<Button
type="submit"
text="Send message"
disabled={!isValid}
testId="submit"
/>
我的测试:
test('send button is enabled when fields are not empty', async () => {
render(<Contact />);
let firstnameVal = "Test First Name";
let lastnameVal = "Test Last Name";
let email = "[email protected]";
let message = "This is a message";
fireEvent.change(screen.getByTestId("first-name"), {target: {value: firstnameVal}});
fireEvent.change(screen.getByTestId("last-name"), {target: {value: lastnameVal}});
fireEvent.change(screen.getByTestId("email"), {target: {value: email}});
fireEvent.change(screen.getByTestId("message"), {target: {value: message}});
expect(screen.getByTestId('submit')).toBeEnabled();
});
我该如何解决这个问题?我是不是漏掉了什么?