【问题标题】:How to Test Next.js's getServerSideProps with jest如何用玩笑测试 Next.js 的 getServerSideProps
【发布时间】:2021-08-17 04:45:21
【问题描述】:

我想在 Next.js 的 getServerSideProps 函数上使用 Jest 和 Enzyme 运行测试。该函数如下所示:

export const getServerSideProps: GetServerSideProps = async (context) => {
  const id = context?.params?.id;
  const businessName = getBusinessName(id);
  return {
    props: {
      businessName: response.data?.name,
      businessID: id,
    },
  };
};

但是,由于我在函数中使用了context 参数,因此我需要将上下文传递到我的测试中。我现在的测试看起来像:

it("check on good case", () => {
    const value = getServerSideProps(/*I'm not sure what to put here*/);
    expect(value).toEqual({props: {businessName: "Name", businessID: "fjdks"}})
  });

我的问题是我将什么传递给上下文参数。我知道它需要是类型:GetServerSidePropsContext<ParsedUrlQuery>。但我不确定如何创建该类型。我可以将什么传递给函数,同时还允许我在参数中添加 id 值?

【问题讨论】:

    标签: reactjs typescript jestjs next.js


    【解决方案1】:

    在测试中将context 对象传递给getServerSideProps 时,您可以使用类型转换。

    it("check on good case", () => {
        const context = {
            params: { id: "fjdks" } as ParsedUrlQuery
        };
        const value = getServerSideProps(context as GetServerSidePropsContext);
        expect(value).toEqual({props: {businessName: "Name", businessID: "fjdks"}});
    });
    

    【讨论】:

      猜你喜欢
      • 2020-06-30
      • 1970-01-01
      • 2021-02-10
      • 2020-07-31
      • 1970-01-01
      • 1970-01-01
      • 2018-08-12
      • 2020-11-14
      相关资源
      最近更新 更多