首页 > 解决方案 > 无法读取 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)
})

对测试有什么建议吗?

标签: reactjsjestjsenzyme

解决方案


有一些语法错误和未闭合的大括号,但如果我正确理解你的意图,你会这样做:

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
})

推荐阅读