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

React单元测试挂载FormattedTime报错,如何对该组件进行spyOn或mock?

解决方法

方案1:使用spyOn mock FormattedTime组件

和你之前处理FormattedMessage的逻辑一致,直接对react-intl导出的FormattedTime做模拟实现即可:

import * as ReactIntl from 'react-intl';

// 测试用例执行前添加mock
let formattedTimeSpy;
beforeEach(() => {
  formattedTimeSpy = jest.spyOn(ReactIntl, 'FormattedTime').mockImplementation((props) => {
    // 可以根据需要自定义返回内容,这里直接把传入的value转成时间字符串返回即可满足挂载要求
    return <span>{new Date(props.value).toLocaleTimeString()}</span>;
  });
});

// 测试结束后恢复原始实现,避免影响其他用例
afterEach(() => {
  formattedTimeSpy.mockRestore();
});

it('mounts component', () => {
  const Component = injectIntl(Settings);
  const wrapper = mount(<Component />);
  expect(wrapper.find(Schedule)).toHaveLength(1);
  wrapper.unmount();
});

方案2:补充IntlProvider外层包裹

你当前的报错本质是因为FormattedTime组件找不到上层的intl上下文导致渲染异常,你也可以直接在挂载时外层包裹IntlProvider解决问题:

import { IntlProvider } from 'react-intl';

it('mounts component', () => {
  const wrapper = mount(
    <IntlProvider 
      locale="en-US" 
      messages={{}}
      // 你debug输出里timeZone为undefined,这里可以指定固定时区避免测试不稳定
      timeZone="Asia/Shanghai"
    >
      <Settings />
    </IntlProvider>
  );
  expect(wrapper.find(Schedule)).toHaveLength(1);
  wrapper.unmount();
});

如果你的测试不需要验证FormattedTime的实际渲染结果,推荐使用方案1,执行效率更高也不会受intl库本身逻辑影响。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.01 20:09:04