首页 > 解决方案 > Jest 测试通过但得到一个错误:在渲染组件时序列化从 `getStaticProps` 返回的 `symbol` 时出错。为什么?

问题描述

尝试将 JSX.Element 类型参数作为道具传递给我的组件时,运行时出现序列化错误yarn dev

但我的笑话测试通过了。

为什么实际上组件没有正确渲染时渲染测试通过了?

这是代码:

//Index.tsx
export const getStaticProps: GetStaticProps = async (context) => {
  const greeting = <DateFC date={new Date()} />;
  const saved_locations: JSX.Element[] = [];
  return {
    props: {
      greeting: greeting,
      saved_locations: saved_locations,
    },
  };
};

和错误

Server Error
Error: Error serializing `.greeting.$$typeof` returned from `getStaticProps` in "/".
Reason: `symbol` cannot be serialized as JSON. Please only return JSON serializable data types.

This error happened while generating the page. Any console logs will be displayed in the terminal window.

使用 react-testing-library 中的 render 函数传递渲染 Index.tsx 的测试

 test("should contain a header section with a role of banner", () => {
    const { container: dom_node } = render(<Index greeting={<DateFC />} />);

    expect(screen.getByRole("banner")).toStrictEqual(
      dom_node.querySelector("header")
    );
  });

和 Index.tsx 组件定义

function Index(props: IndexFCProps) {
  return (
    <>
      <header>{props.greeting}</header>
      <main>
        <section aria-label="weather in saved locations">
          {props.saved_locations}
        </section>
        <section aria-label="weather in favorite location">
          <WeatherTile withTime={false}></WeatherTile>
        </section>
      </main>
      <nav>
        <Nav></Nav>
      </nav>
    </>
  );
}

我正在使用 NextJs 反应框架。

标签: javascripttestingjestjsnext.jsts-jest

解决方案


推荐阅读