[英]How to Test Next.js's getServerSideProps with jest
I would like to run tests with Jest and Enzyme on Next.js's getServerSideProps
function.我想在 Next.js 的
getServerSideProps
function 上使用 Jest 和 Enzyme 运行测试。 The function looks like the following: function 如下所示:
export const getServerSideProps: GetServerSideProps = async (context) => {
const id = context?.params?.id;
const businessName = getBusinessName(id);
return {
props: {
businessName: response.data?.name,
businessID: id,
},
};
};
However since I'm using the context
parameter in my function I need to pass a context into my test.但是,由于我在 function 中使用
context
参数,因此我需要将上下文传递到我的测试中。 My test right now looks like:我现在的测试看起来像:
it("check on good case", () => {
const value = getServerSideProps(/*I'm not sure what to put here*/);
expect(value).toEqual({props: {businessName: "Name", businessID: "fjdks"}})
});
My question is what do I pass into the parameter for context.我的问题是我将什么传递给上下文参数。 I know it needs to be of type:
GetServerSidePropsContext<ParsedUrlQuery>
.我知道它需要是以下类型:
GetServerSidePropsContext<ParsedUrlQuery>
。 But I'm not sure how to create that type.但我不确定如何创建该类型。 What can I pass into the function that also allows me to add an
id
value in the params as well?我可以将什么传递给 function 也允许我在参数中添加一个
id
值?
You can resort to type casting when passing the context
object to getServerSideProps
in your test.在测试中将
context
object 传递给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"}});
});
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.