0

I'm building NextJS app with SSR. I've written the getServerSideProps function that makes a call to supabase. Before making the call I'm trying to get user session by calling getSession function from @auth0/nextjs-auth0 package.

I'm trying to mock it in the handlers.ts file:

import { rest } from 'msw';

export const handlers = [
  // this is the endpoint called by getSession
  rest.get('/api/auth/session', (_req, res, ctx) => {
    return res(ctx.json(USER_DATA));
  }),

  rest.get('https://<supabase-id>.supabase.co/rest/v1/something', (_req, res, ctx) => {
    return res(ctx.json(SOMETHING));
  }),
];

My mocks file: requestMocks/index.ts:

export const initMockServer = async () => {
  const { server } = await import('./server');
  server.listen();

  return server;
};

export const initMockBrowser = async () => {
  const { worker } = await import('./browser');
  worker.start();

  return worker;
};

export const initMocks = async () => {
  if (typeof window === 'undefined') {
    console.log('<<<< setup server');
    return initMockServer();
  }

  console.log('<<<< setup browser');
  return initMockBrowser();
};

initMocks();

Finally, I'm calling it in the _app.tsx file:

if (process.env.NEXT_PUBLIC_API_MOCKING === 'true') {
  require('../requestMocks');
}

Unfortunately, it does work for me. I'm getting no user session data in the getServerSideProps function in my page component:

import { getSession } from '@auth0/nextjs-auth0';

export const getServerSideProps = async ({ req, res }: { req: NextApiRequest; res: NextApiResponse }) => {
  const session = getSession(req, res);

  if (!session?.user.accessToken) {
    // I'm constantly falling here
    console.log('no.session');
    return { props: { something: [] } };
  }

  // DO something else
};

Any suggestions on how to make it working in Cypress tests would be great.

I'm expecting that I will be able to mock requests made in getServerSideProps function with MSW.js library.

1 Answers1

0

I made it finally. Looks like I don't have to mock any calls. I need to copy my user appSession cookie and save it in cypress/fixtures/appSessionCookie.json file:

{
  "appSession": "<cookie-value>"
}

Then use it in tests as follows:

  before(() => {
    cy.fixture('appSessionCookie').then((cookie) => {
      cy.setCookie('appSession', cookie.appSession);
    });
  });

This makes a user automatically logged in with Auth0.