You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

React中如何测试参数包含req的导出函数getServerSideProps

测试getServerSideProps函数的实现方法

getServerSideProps本质是独立的纯函数,仅依赖传入的上下文参数返回结果,不需要依赖组件渲染逻辑,单独做单元测试即可,步骤如下:

  • 第一步:导入你页面文件中导出的getServerSideProps函数
  • 第二步:构造模拟的请求入参,只需要填充你代码中用到的req.properties字段即可
  • 第三步:调用函数后断言返回的props结构和值符合预期

基础测试用例示例(以Jest为例)

// 替换为你实际的页面文件路径
import { getServerSideProps } from './pages/daily-profit';

test('getServerSideProps 正确提取req中的profit字段返回', () => {
  // 构造模拟入参
  const mockContext = {
    req: {
      properties: {
        profit: 996.55
      }
    }
  };

  const res = getServerSideProps(mockContext);

  // 验证返回结果
  expect(res).toEqual({
    props: {
      profit: 996.55
    }
  });
});

边界场景测试用例

你还可以补充异常场景的测试,覆盖参数缺失的情况:

test('getServerSideProps 处理req.properties不存在的场景', () => {
  const mockContext = {
    req: {}
  };
  // 如果你没有做异常兜底这里会抛错,对应可以调整你的业务代码加兜底逻辑
  expect(() => getServerSideProps(mockContext)).toThrow();
});

test('getServerSideProps 处理profit字段为空的场景', () => {
  const mockContext = {
    req: {
      properties: {}
    }
  };
  const res = getServerSideProps(mockContext);
  expect(res.props.profit).toBeUndefined();
});

额外说明

如果需要做集成测试,可以把getServerSideProps返回的props传递给DailyProfit组件,验证组件接收props后的渲染逻辑是否符合预期,这部分属于组件测试的范畴,和函数本身的测试可以分开执行。

内容的提问来源于stack exchange,提问作者samjo

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.10.07 03:57:03