I have an MUI dialog which I am trying to test as part of a larger test case for the dialog’s parent. There are a few steps before the dialog can be opened. First, a Material-Table must be rendered. Then an action in the table’s action column must be clicked. Clicking on this action will call a function which runs a fetch request before setting the Dialogs open prop to true.
In my test, I am mocking the table data and the data which is passed into the dialog. I know the mocks are working as my other tests are passing.
Here is my test:
it("clicks the edit icon and opens the dialog", async () => {
render(<ParentComponent />);
const editRow = document.querySelector("#edit");
await act(async () => {
fireEvent.click(editRow);
expect(useData().fetchData).toHaveBeenCalledWith(data.Id);
const dialog = within(await screen.findByRole("dialog"));
expect(dialog.getByText("ID:")).toBeInTheDocument();
});
});
The test fails at:
Unable to find role="dialog"
... A really ling HTML output ...
> 112 | const dialog = within(await screen.findByRole("dialog"));
Here is the function where the dialog is opened:
const openDialog = async (Id, badge, name) => {
await fetchData(Id);
setOpen(Id);
};
Here is how the dialog is called within its parent:
<MyDialog
open={open}
data={data}
onClose={handleClose}
/>
And here is the dialog:
import { styled, Dialog, DialogActions, DialogTitle } from "@mui/material";
const CustomDialog = styled(Dialog)(() => ({
"& .MuiDialog-container": {
"& .MuiPaper-root": {
width: "40rem",
height: "29rem",
},
},
}));
export default function MyDialog(props) {
const { open, onClose, data } = props;
return (
<CustomDialog open={open} onClose={onClose}>
<DialogTitle>
ID: {data?.Id}
</DialogTitle>
<DialogActions>
<Button onClick={onClose}>Close</Button>
</DialogActions>
</CustomDialog>
);
}
3