Ad

Cannot Read Property Function Of Null

- 1 answer

Hello I'm trying to test a function from a function but tells me this error.

TypeError: Cannot read property 'getNextServiceIconStyle' of null

Code

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

test('should', () => {
    const wrapper = shallow(<IssueNextServiceIcon {...mockPropsForComponent} />)
    const instance = wrapper.instance()
    const expectedResult = 'next-service-overdue'
    expect(instance.getNextServiceIconStyle(true, false)).toEqual(expectedResult)
})

Any suggestion for the test?

Ad

Answer

There a few syntax errors and unclosed braces, but if I understood your intent correctly, you'd do smth like this:

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

Regarding the test, you cannot use wrapper.instance() because this is not a class component. What you could do is to render your component and check that it has proper styles applied:

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
})
Ad
source: stackoverflow.com
Ad