【发布时间】:2018-06-01 23:19:11
【问题描述】:
我有一个返回取决于参数 HOC 组件的函数。我将此组件包装到 reduxForm HOC。我想使用 type() 用酶对其进行测试。该函数返回类型为 FormValues 的 HOC 组件,但如何在没有 HOC 的情况下返回进行测试。如何使用 proxyquire 对其进行测试
功能
export const getMiConfiguration = miConfigurationType => {
switch (miConfigurationType) {
case MiConfigurationTypes.WanderingDetection :
case MiConfigurationTypes.MuteWanderingDetection:
return <WanderingDetection />
case MiConfigurationTypes.OpenWanderingControl :
case MiConfigurationTypes.LockedWanderingControl:
return <WanderingControl />
default:
return null
}
}
测试
describe('getMiConfiguration', () => {
;[{id: MiConfigurationTypes.AccessPointOnly, component: null},
{id: MiConfigurationTypes.WanderingDetection, component: <WanderingDetection/>},
{id: MiConfigurationTypes.MuteWanderingDetection, component: <WanderingDetection/>},
{id: MiConfigurationTypes.LockedWanderingControl, component: <WanderingControl/>},
{id: MiConfigurationTypes.OpenWanderingControl, component: <WanderingControl/>},
].forEach(({id, component}) =>
it(`should render correct ${component} component for ${id} type`, () => {
const result = getMiConfiguration(id)
if (component === null)
expect(result).to.be.null
else
result.type.should.be.equal(component.type)
}))
})
组件示例
export const WanderingDetection = ({miConfigurationType}) =>
<Grid container>
<Grid item xs={12}>
<GeneralMiConfigurations />
</Grid>
{MiConfigurationTypes.MuteWanderingDetection === miConfigurationType &&
[
<Grid item xs={10} style={{margin: '0 auto'}}>
<Divider/>
</Grid>,
<Grid item xs={12} style={{alignSelf: 'center'}}>
<InfoMessage id='passage.label.useInputToMuteLocationField'/>
<InputTypeConfiguration/>
</Grid>,
]
}
</Grid>
WanderingDetection.propTypes = {
miConfigurationType: PropTypes.string,
}
export default formValues('miConfigurationType')(WanderingDetection)
【问题讨论】:
-
您可以从文件中返回 WanderingDetection 组件并在单元测试中使用它。导出 { WanderingDetection };
-
我有导出但函数返回 HOC 组件,当我导入时没有 {'wanderingDetection'} 我比较 result.type() // FormValues HOC 与组件 .type(WanderingDetection)跨度>
-
我想说的是,您使用 HOC 的默认回报很好。为您的单元测试添加一个导出,它将返回组件而不将其包装在 formValues 中,以便您可以对其进行测试。
-
好的,当添加导入为 {WanderingDetection} 而没有 HOC 导出 const WanderingDetection 时,这对我没有帮助,因为我正在测试的真正函数返回 HOC
标签: reactjs unit-testing chai enzyme proxyquire