【发布时间】:2021-10-06 23:49:50
【问题描述】:
我正在为使用 react-intl 组件 FormattedTime 的自定义 React 挂钩实现单元测试。不幸的是,我在安装时遇到了以下错误:
[错误:FormattedTime(...):渲染没有返回任何内容。这通常意味着缺少 return 语句。或者,不渲染任何内容,返回 null。]
使用 FormattedTime 的钩子部分:
{ timeIncrements.map((time, key) => (
<DropdownItem value={ format(convertTime(time, date), "yyyy-MM-dd'T'HH:mm:'00'") } key={ key }>
<FormattedTime
value={ convertTime(time, date) }
timeZone={ timezone }
timeZoneName='short'
hour='numeric'
minute='numeric'
hour12={ true }
/>
</DropdownItem>
)) }
我已经确认convertTime 函数正在返回一个值以传递给组件。
单元测试还没有太多,但这里是:
it('mounts component', () => {
const Component = injectIntl(Settings);
const wrapper = mount(<Component />);
expect(wrapper.find(Schedule)).toHaveLength(1);
wrapper.unmount();
});
有没有办法 spyOn/mock FormattedTime 组件?我已经为 FormattedMessage 错误做了类似的 spyOn,但似乎找不到为 @987654328 实现类似的方法@。我认为这对某人来说是一个简单的问题,但它让我很不舒服,所以寻求帮助。
根据@diedu 的回答更新...这里是wrapper.debug() 的输出:
<IntlProvider locale="en-US" messages={{...}} formats={{...}} timeZone={[undefined]} textComponent={[symbol]} defaultLocale="en" defaultFormats={{...}} onError={[Function: mockConstructor] { _isMockFunction: true, getMockImplementation: [Function (anonymous)], mock: Object [Object: null prototype] { calls: [], instances: [], invocationCallOrder: [], results: [] }, mockClear: [Function (anonymous)], mockReset: [Function (anonymous)], mockRestore: [Function (anonymous)], mockReturnValueOnce: [Function (anonymous)], mockResolvedValueOnce: [Function (anonymous)], mockRejectedValueOnce: [Function (anonymous)], mockReturnValue: [Function (anonymous)], mockResolvedValue: [Function (anonymous)], mockRejectedValue: [Function (anonymous)], mockImplementationOnce: [Function (anonymous)], mockImplementation: [Function (anonymous)], mockReturnThis: [Function (anonymous)], mockName: [Function (anonymous)], getMockName: [Function (anonymous)] }} />
【问题讨论】:
标签: reactjs jestjs react-hooks react-intl