I want to perform using the test on the component I have in my react app. when I simply tried to render my component using the render from react testing it is throwing me the error.
Can anyone please suggest to me the solution to this? please see the code below:
Code for testing the authorgroup componenet;
import { render, screen } from "@testing-library/react";
import AuthorsGroup from "./Authorsgroup";
it("should render author component", () => {
render(<AuthorsGroup />);
const headerEl = screen.getByRole("heading", { name: /happyusertapesh/i });
expect(headerEl).toBeInTheDocument();
});
Authorcomponent
const Authorsgroup = ({
posts,
groupDropdownValue,
setShowForm,
setPostId,
showForm
}) => {
const authorGroup = posts.reduce((group, authorgroup) => {
(group[authorgroup.author.replace(/ /g, "")] =
group[authorgroup.author.replace(/ /g, "")] || []).push(authorgroup);
return group;
}, {});
const [authorGroupValues, setAuthorGroupValues] = useState(authorGroup);
const authorGroupEntries = Object.entries(authorGroupValues);
useEffect(() => {
setAuthorGroupValues(authorGroup);
}, [groupDropdownValue, showForm]);
return (
<>
<Container>
<Container style={{ marginTop: "3rem" }}>
{authorGroupEntries.map(([author, posts]) => {
return (
<div key={author}>
<Accordion>
<AccordionSummary
expandIcon={<ExpandMoreIcon />}
aria-controls="panel1a-content"
id="panel1a-header"
>
<Typography variant="h6" style={{ color: "#EB1283" }}>
{author}
</Typography>
</AccordionSummary>
{posts.map(({ id, text, author, location }) => {
return (
<div key={id}>
<AccordionDetails>
<Typography variant="h4">
{id} {author}
</Typography>
<Typography>
{text} {location}
</Typography>
<Button
variant="outlined"
onClick={() => {
setShowForm(!showForm);
setPostId(id);
}}
startIcon={<EditIcon />}
>
Edit
</Button>
</AccordionDetails>
</div>
);
})}
</Accordion>
</div>
);
})}
</Container>
</Container>
</>
);
};
export default Authorsgroup;
Thanks for your help.
Error
CodePudding user response:
You aren't passing any props into the test component. This means that the value posts is being set to undefined.
Simply pass a mock value for posts as a prop in the render method
render(<AuthorsGroup posts={/* posts mock value here */} />)
You will also need to do this for each of the other props you have defined.