如何在测试中替换 Context 值并验证不同状态分支

问题

如何在测试中替换 Context 值并验证不同状态分支

知识点

  1. React.createContext 与 Provider 的渲染机制
  2. @testing-library/react 的 render 函数支持 wrapper 参数
  3. 自定义 Wrapper 组件在测试用例间动态传值
  4. jest.mock / jest.spyOn 对模块级 Context 默认值的 mock
  5. 多分支渲染(条件渲染、错误边界、加载态)在单测中的断言技巧
  6. 国内主流 CI(GitLab-CI、Jenkins、GitHub Actions 自建)对测试用例隔离性的要求
  7. 阿里/腾讯/字节等一线厂代码评审中对“分支覆盖≥90%”的硬性指标

答案

核心思路:把“替换 Context 值”抽象成“测试夹具”,保证每个用例拿到干净且确定的上下文,再针对渲染结果做断言。国内团队普遍使用 @testing-library/react + Jest,下面给出可直接落地的三段式方案。

1. 构造可传值的 Wrapper

// test-utils.jsx
import { render as rtlRender } from '@testing-library/react';
import { ConfigContext } from '@/contexts/config';

function renderWithContext(
  ui,
  { value = {}, ...options } = {}
) {
  function Wrapper({ children }) {
    return (
      <ConfigContext.Provider value={value}>
        {children}
      </ConfigContext.Provider>
    );
  }
  return rtlRender(ui, { wrapper: Wrapper, ...options });
}

export * from '@testing-library/react';
export { renderWithContext };

该文件统一导出 renderWithContext,屏蔽掉 RTL 默认 render,团队其他成员直接 import { renderWithContext } from '@/test-utils' 即可,符合国内“测试工具链收口”规范。

2. 针对分支写用例

假设业务组件:

function Price() {
  const { currency, rate } = useContext(ConfigContext);
  if (!currency) return <span>货币未配置</span>;
  return <span>{`¥${(100 * rate).toFixed(2)}`}</span>;
}

测试文件:

import { renderWithContext, screen } from '@/test-utils';

describe('Price 组件分支覆盖', () => {
  it('货币为空时展示提示', () => {
    renderWithContext(<Price />, { value: {} });
    expect(screen.getByText('货币未配置')).toBeInTheDocument();
  });

  it('人民币场景下计算正确', () => {
    renderWithContext(<Price />, { value: { currency: 'CNY', rate: 1 } });
    expect(screen.getByText('¥100.00')).toBeInTheDocument();
  });

  it('美元场景下计算正确', () => {
    renderWithContext(<Price />, { value: { currency: 'USD', rate: 6.4 } });
    expect(screen.getByText('¥640.00')).toBeInTheDocument();
  });
});

每个用例只改 value,不污染全局,符合国内 CR 对“用例隔离”的强制要求。

3. 模块级默认值的 mock(可选)

当 Context 的 defaultValue 来自另一个模块(如 import config from '@/config'),而测试需要把 config 整体替换时,用 jest.mock 一次性拦截:

jest.mock('@/config', () => ({
  currency: 'EUR',
  rate: 7.5
}));

注意:jest.mock 提升会污染整个文件,推荐放在「集成测试」或「多分支快照对比」场景;单元测试优先用 Wrapper 传值,保持单测原子性。

拓展思考

  1. 并发特性(React 18)下,act 包裹更新已成强制规范;若 Context 变化触发 startTransition,需要 await act(async () => {...}),否则 CI 会报 “Warning: An update to ConfigContext inside a test was not wrapped in act(...)”。
  2. 对于“深层嵌套 Consumer”或“多 Context 组合”,可结合 AllTheProviders 模式:把多个 Provider 串成高阶组件,再透传参数,实现“一行代码切换整套上下文”,在微前端主应用测试中尤为常见。
  3. 国内很多团队把“分支覆盖”与“行覆盖”同时写进 MR 门禁,建议配合 jest --coverage --changedSince=origin/main 只跑增量用例,既保证质量又节省云主机时长。
  4. 若使用 React Native 场景,@testing-library/react-native 同样支持 wrapper 参数,但需注意 SafeAreaProvider 等系统级 Context 也要一并 mock,否则会出现“Insets is undefined”的报错。