I'm trying to test a component that have a <Switch/>
(using Material-UI) and a <TextField/>
. When user clicks in this Switch, it makes another field (<TextField/>
) enable/disabled. The code works well, but my test using JEST always fails.
...
export function MyComponent(): JSX.Element{
const [enableExpiresOn, setEnableExpiresOn] = useState(false);
...
function handleAccountExpiresOn(e: React.ChangeEvent<HTMLInputElement>) {
setEnableExpiresOn(e.target.checked);
}
return (
<form ...>
...
<div>
<FormControlLabel
control={
<Switch
id="account-expires"
onChange={handleAccountExpiresOn}
name="account-expires"
color="primary"
checked={enableExpiresOn}
/>
}
label={t("Account Expires On")}
/>
</div>
<div>
<TextField
id="account-expires-on"
label={t("Account Expires On")}
type="datetime-local"
variant="outlined"
required={enableExpiresOn}
InputLabelProps={{
shrink: true,
}}
disabled={!enableExpiresOn}
/>
</div>
...
</form>
);
}
And in my JEST test file, I have the follow (as you can see, I'm trying to simulate a click in the Switcher):
describe("Should render correctly", () => {
let wrapper;
beforeAll(() => {
wrapper = mount(<MyComponent />);
});
...
fit("Should enable Account Expires On when switcher is on/checked", async () => {
wrapper.find("#account-expires").at(0).simulate("click");
expect(
wrapper.find("#account-expires-on").get(0).props.disabled
).toEqual(false);
});
However, Jest gives me an error in this expectation, saying that it have received true
instead false
.
I tried to put a setTimeout around the expectation, hoping that it would solve the problem because maybe we need to wait for the click to have effect, but it doesn't work.
I'm newer with JEST and React Hooks. So, I don't know if it is the best way to test what this behaviour or there is a better way.
Used Technologies
- React Hooks
- NextJS
- Material UI
- TypeScript
- Jest
- Enzyme