It's pretty much my first time writing unit tests in React and i think i'm understanding most of the code that's already written but i'm struggling a bit here and there, i must've missed something. In fact i'm trying to write code in a test file that asserts if a checkbox is checked after using fireEvent.click() on it :
const checkbox = screen.getByLabelText("Modalité 1");
console.log(checkbox); // returns a HTMLInputElement with 'checked: false' which to me,
// confirms that i get an element of the type checkbox.
fireEvent.click(checkbox); // also tried with userEvent.click(checkbox);
expect(checkbox).toBeChecked();
console.log(checkbox); // returns exactly the same thing as before, with 'checked: false'.
The error message shows Expected: true Received: false
I didn't find this exact error anywhere else, but instead found other solutions implying other test methods which only made things more complicated :
fireEvent.change(checkbox, { target: { checked: true } });
Instead of making the user click on the checkbox, i believe this method changes the property 'checked' diretly and isn't realistic.
The non-test javascript file contains the following : (code uses @material-ui)
<div key={modalite.value} className="modalite-container">
<FormControlLabel
className="modalite"
name={this.props.name}
value={modalite.value}
control={
<Checkbox
onChange={(event) =>
this.handleChange(event, modalite)
}
checked={
this.state.selected.indexOf(modalite.value) > -1
? true
: false
}
/>
}
color={styleStore.isTypeMIS ? "mis" : "primary"}
label={
<div className="precisez-container">
{label}
{modalite.precision ? (
<div>
<input
label="précisez"
variant="outlined"
type="text"
className="precisez colored"
placeholder={t("entrez_precision")}
name="precision"
value={valuePrecision}
onChange={(event) =>
this.handleChangePrecision(
event,
modalite
)
}
/>
</div>
) : (
""
)}
</div>
}
/>
and i have no idea how to correctly test that. Is the click event wrong ? Is the check-testing method wrong ?
Any ideas ?