I have some login code
<Grid className={classes.container} item xs={12} sm={6}>
<TextField data-testid='employeeId' className={classes.input} value={employeeId} onChange={handleChange} label="Employee id" variant="outlined" />
{(employeeId && employeeId.length > 0)?
<Button className={classes.button} disableElevation onClick={onSubmit} variant="contained" color="primary">Login</Button>:
<Button className={classes.button} disableElevation variant="contained" disabled>
Login
</Button>
}
</Grid>
</Grid>
when user enters name, and clicks login, user is navigated to the home page. I wrote tests to check that the login code should not be present after submitting. App behaves as expected but tests to check whether login page has stopped displaying fail.
render(<App/>);
userEvent.type(screen.getByTestId('employeeId'), 'aryan');
userEvent.click(screen.getByText(/login/i));
const linkElement = screen.getByText(/home screen/i);
expect(linkElement).toBeInTheDocument();
expect(screen.getByTestId('employeeId')).not.toBeInTheDocument();
});
code sandbox link: https://codesandbox.io/s/tender-glitter-wjpye?file=/src/App.tsx
When checking if an element is not present, you have to use queryBy instead. queryBy can handle null cases, whereas getBy cannot (by design). So this should do it:
expect(screen.queryByTestId('employeeId')).not.toBeInTheDocument();
I got the answer. I was using material-ui TextBox for input and putting a test-id on the TextBox. It won't work because TextBox is just a wrapper and it should be something like
userEvent.type(screen.getByRole('textbox'), 'aryan');
Now tests are running fine.