如何使用react测试和jest测试react中reduce方法的组件?

sc4hvdpw  于 2022-12-20  发布在  Jest
关注(0)|答案(1)|浏览(231)

我想使用react应用程序中的组件进行测试。当我简单地尝试使用react测试中的渲染来渲染我的组件时,它向我抛出了错误。
任何人都可以请建议我的解决方案,这?请看下面的代码:

    • 测试作者组组件的代码;**
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();
});
    • 作者组件**
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;

谢谢你的帮助。

    • 错误**

06odsfpq

06odsfpq1#

您没有向测试组件传递任何属性,这意味着值posts被设置为undefined。
只需在render方法中传递一个post的mock值作为prop

render(<AuthorsGroup posts={/* posts mock value here */} />)

您还需要为已定义的其他每个 prop 执行此操作。

相关问题