【发布时间】: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