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
相关产品推荐
相关产品推荐

