【问题标题】:Intercepting Auth0 getSession with MSW.js and Cypress使用 MSW.js 和 Cypress 拦截 Auth0 getSession
【发布时间】:2022-11-25 04:16:52
【问题描述】:

我正在使用 SSR 构建 NextJS 应用程序。我已经编写了调用 supabase 的 getServerSideProps 函数。在拨打电话之前,我试图通过调用 @auth0/nextjs-auth0 包中的 getSession 函数来获取用户会话。

我试图在 handlers.ts 文件中模拟它:

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));
  }),
];

我的模拟文件: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();

最后,我在 _app.tsx 文件中调用它:

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

不幸的是,它确实对我有用。我在页面组件的 getServerSideProps 函数中没有得到任何用户会话数据:

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
};

关于如何使其在 Cypress 测试中工作的任何建议都会很棒。

我希望我能够使用 MSW.js 库模拟在 getServerSideProps 函数中发出的请求。

【问题讨论】:

    标签: reactjs next.js cypress auth0 msw


    【解决方案1】:

    我终于做到了。看起来我不必模拟任何电话。我需要复制我的用户appSession cookie 并将其保存在cypress/fixtures/appSessionCookie.json 文件中:

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

    然后在测试中使用它,如下所示:

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

    这使用户自动使用 Auth0 登录。

    【讨论】:

      猜你喜欢
      • 2021-02-22
      • 2021-12-22
      • 2023-04-02
      • 1970-01-01
      • 2023-03-14
      • 1970-01-01
      • 1970-01-01
      • 2021-05-02
      • 1970-01-01
      相关资源
      最近更新 更多