This answer was helpful, allowing me to successfully test my Dialog's ability to open and display specific passed data.
I wanted to come back and share what I did so hopefully it can help someone else down the road.
Thanks @skube for the answer.
The component
const ButtonDialog = ({ data }) => {
const { Title, Desc, List } = data;
const [openDialog, setOpenDialog] = useState(false);
const handleClickClose = () => {
setOpenDialog(false);
};
const handleClickOpen = () => {
setOpenDialog(true);
};
return (
<>
<Button
data-testid="titleButton"
variant="contained"
onClick={handleClickOpen}
>
{Title}
</Button>
<Dialog open={openDialog} onClose={handleClickClose}>
<DialogTitle>{Title}</DialogTitle>
<DialogContent>
<DialogContentText>
<Typography data-testid="dialogDescription" sx={{ mb: 1 }}>
{Desc}
</Typography>
<ul>
{List && (
<Stack spacing={1} data-testid="listContainer">
{List.map((item, i) => (
<li key={i}>{item}</li>
))}
</Stack>
)}
</ul>
</DialogContentText>
<DialogActions>
<Button
data-testid="closeButton"
variant="contained"
onClick={handleClickClose}
>
Close
</Button>
</DialogActions>
</DialogContent>
</Dialog>
</>
);
};
The Tests
it("ButtonDialog opens when title button clicked", async () => {
render(
<ButtonDialog
data={{ id: "", Title: "Open", Desc: "This Dialog is open", List: "" }}
/>,
);
const openButton = screen.getByTestId("titleButton");
fireEvent.click(openButton);
await waitFor(() => {
screen.getByTestId("dialogDescription");
});
const description = screen.getByTestId("dialogDescription");
// eslint-disable-next-line testing-library/no-debugging-utils
// screen.debug(); //check printout to see if Dialog opens
expect(description).toBeTruthy();
expect(description).toHaveTextContent("This Dialog is open");
});
it("ButtonDialog opens to display list when data provided", async () => {
render(
<ButtonDialog data={{ id: "", Title: "Open", Desc: "", List: List }} />,
);
const openButton = screen.getByTestId("titleButton");
fireEvent.click(openButton);
await waitFor(() => {
screen.getByTestId("listContainer");
});
const list = screen.getByTestId("listContainer");
// eslint-disable-next-line testing-library/no-debugging-utils
// screen.debug(); //check to see if dialog opened
expect(list).toBeTruthy();
});
});
await waitFor
was not working. I don't understand why exactly, as the docs suggestwaitForElementToBeRemoved
is just a utility that wrapswaitFor
, but, FWIW, if any visitors to this page are having an issue withawait waitFor
this might be a viable solution. – Flume