How to Test Next.js's getServerSideProps with jest

Viewed 4169

I would like to run tests with Jest and Enzyme on Next.js's getServerSideProps function. The function looks like the following:

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. 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>. 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?

1 Answers

You can resort to type casting when passing the context object to getServerSideProps in your test.

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"}});
});
Related