接下来使用反应测试库进行seo测试

Next seo test with react testing library

我正在尝试测试我的 SEO 组件,它看起来像这样:

export const Seo: React.FC<Props> = ({ seo, title, excerpt, heroImage }) => {
  const description = seo?.description || excerpt
  const pageTitle = seo?.title || title

  const router = useRouter()

  return (
    <NextSeo // https://www.npmjs.com/package/next-seo
      canonical={seo?.canonical}
      nofollow={seo?.nofollow}
      noindex={seo?.noindex}
      title={pageTitle}
      description={description}
      openGraph={{
        title,
        description,
        type: "article",
...

我的测试是这样的:

describe("Seo", () => {
  it("should render the meta tags", async () => {
    const props = {
      title: "title page",
      excerpt: "string",
      seo: {
        title: "seo title",
        description: "meta description",
      },
      heroImage: {
        src: "url",
        alt: "alt text",
        width: 300,
        height: 400,
      },
    }

    function getMeta(metaName: string) {
      const metas = document.getElementsByTagName("meta")
      for (let i = 0; i < metas.length; i += 1) {
        if (metas[i].getAttribute("name") === metaName) {
          return metas[i].getAttribute("content")
        }
      }
      return ""
    }

    render(<Seo {...props} />)

    await waitFor(() => expect(getMeta("title")).toEqual("title page"))
  })
})

但是测试失败了:(看起来 head 元素是空的)

我遇到了同样的问题,但我发现 this answer on GitHub

所以基本上你需要模拟 next/head,将 document.head 传递给 render 选项的容器 属性,最后访问 document

你的测试会像这样结束:

jest.mock('next/head', () => {
  return {
    __esModule: true,
    default: ({ children }: { children: Array<React.ReactElement> }) => {
      return <>{children}</>;
    },
  };
});

describe("Seo", () => {
  it("should render the meta tags", () => {
    const props = {
      title: "title page",
      excerpt: "string",
      seo: {
        title: "seo title",
        description: "meta description",
      },
      heroImage: {
        src: "url",
        alt: "alt text",
        width: 300,
        height: 400,
      },
    }

    render(<Seo {...props} />, { container: document.head })

    expect(document.title).toBe("title page")
  })
})

在我的例子中,我没有使用 getMeta 函数对其进行测试,但我相信它也会起作用。

在 JS 中

jest.mock('next/head', () => {
  return {
    __esModule: true,
    default: ({ children }) => {
      return children;
    }
  };
});