ARTICLE AD BOX
I am working on a React component that implements a form with validation logic. The form includes the following fields:
Name
Employee ID
Joining Date
Each field has validation rules, and error messages should appear when the input is invalid. The submit button should only be enabled when all fields are valid.
Requirements:
Each input field should always display an error message if invalid
The submit button should be disabled until all inputs are valid
On successful submission, the form should reset
Some of my tests are failing, specifically this one:
Input fields functionality : should display no error for employee ID input field's if criteria is met Error: expect(received).toHaveLength(length) Expected value to have length: 2 Received: {"0": <input class="w-100" type="date" name="joiningDate" placeholder="Joining Date" value="2025-04-12" />} received.length: 1From this error, it seems like the test expects the container (e.g. data-testid="input-employee-id") to always have two children:
The input field
The error message <p>
However, when the input becomes valid, my component removes the error <p> entirely, leaving only 1 child.
import React, { useEffect, useState } from "react"; function EmployeeValidationForm() { const [name, setName] = useState(""); const [email, setEmail] = useState(""); const [employeeID, setEmployeeID] = useState(""); const [joinDate, setJoinDate] = useState(""); const isNameValid = name.trim().length >= 4 && /^[A-Za-z\s]+$/.test(name); const isEmailValid = /^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(email); const isEmployeeIDValid = /^\d{6}$/.test(employeeID); const isJoinDateValid = joinDate !== "" && new Date(joinDate) <= new Date(); const isFormValid = isNameValid && isEmailValid && isEmployeeIDValid && isJoinDateValid; const handleSubmit = (e) => { e.preventDefault(); if (!isFormValid) return; setName(""); setEmail(""); setEmployeeID(""); setJoinDate(""); }; return ( <div> <div data-testid="input-employee-id"> <input type="text" value={employeeID} onChange={(e) => setEmployeeID(e.target.value)} /> {!isEmployeeIDValid && ( <p className="error">Employee ID must be exactly 6 digits.</p> )} </div> <button disabled={!isFormValid} onClick={handleSubmit}> Submit </button> </div> ); } export default EmployeeValidationForm;I tried:
Keeping validation logic simple and correct
Ensuring isFormValid updates correctly
Rendering error messages conditionally
Should I always render the error <p> element (even when valid) and just toggle its content instead of conditionally rendering it?
Or is there something else I might be missing in terms of how the test is querying the DOM?
