reactjs - 无法读取 null 的属性函数
问题描述
您好,我正在尝试从一个函数中测试一个函数,但告诉我这个错误。
TypeError: Cannot read property 'getNextServiceIconStyle' of null
代码
function IssueNextServiceIcon ({ nextService, intl }) {
return (
<div styles[getNextServiceIconStyle(nextService.approaching, nextService.overDue)])}>
<NextServiceIcon className={styles['icon']} />
</div>
)
function getNextServiceIconStyle (approaching, overDue) {
if (overDue) {
return 'next-service-overdue'
}
else if (approaching) {
return 'next-service-approaching'
}
return ''
}
}
测试
test('should', () => {
const wrapper = shallow(<IssueNextServiceIcon {...mockPropsForComponent} />)
const instance = wrapper.instance()
const expectedResult = 'next-service-overdue'
expect(instance.getNextServiceIconStyle(true, false)).toEqual(expectedResult)
})
对测试有什么建议吗?
解决方案
有一些语法错误和未闭合的大括号,但如果我正确理解你的意图,你会这样做:
function IssueNextServiceIcon({ nextService, intl }) {
function getNextServiceIconStyle(approaching, overDue) {
if (overDue) {
return "next-service-overdue";
} else if (approaching) {
return "next-service-approaching";
}
return "";
}
const styleKey = getNextServiceIconStyle(
nextService.approaching,
nextService.overDue
);
return (
// Or if you need to pass className: className={styles[styleKey]}
<div styles={styles[styleKey]}>
<NextServiceIcon className={styles["icon"]} />
</div>
);
}
关于测试,您不能使用wrapper.instance()
,因为这不是类组件。您可以做的是渲染您的组件并检查它是否应用了正确的样式:
test('it should have correct styling', () => {
const wrapper = shallow(<IssueNextServiceIcon {...mockPropsForComponent} />)
expect(component.find('NextServiceIcon').prop('style')).toHaveProperty('color', 'red') // test for the actual css you have
})
推荐阅读
- java - PowerMockito.doNothing() 抛出空指针异常
- ios - 如何同步主后台核心数据线程?
- python - Pandas: Find N largest values on each group Then create N columns
- angular - Cannot read property 'isXXXXX' of undefined
- javascript - Object value in array is undefined
- conv-neural-network - Number of parameter for convolutional filter
- docker - 如何在 Airflow 上运行 DockerOperator?
- python - 在 Python 中从字符串中提取电子邮件服务提供商
- opendaylight - 编译 Opendaylight Fluorine 的 hello world 示例时出错 - yang 工具问题
- javascript - Get all the Child Elements and push it into array