Radex
Radex

Reputation: 8587

Issue using jest - Cannot read property 'xxx' of undefined

I receive error using the following test case:

 Cannot read property 'weatherIconCode' of undefined

I am passing weatherIconCode to the component from the test case, but I do not understand why I get undefined.

Any ideas how to solve with a brief explanation is very welcome.

Component:

import React, {Component} from 'react'
import IconWeather from '../../shared/icon/IconWeather'

class SummaryChartIcon extends Component {
  render () {
    const { cx, cy, payload: {weatherIconCode} } = this.props
    return (
      <svg x={cx - 10} y={cy + 20}>
        <foreignObject width='100%' height='100%'>
          <IconWeather code={weatherIconCode} />
        </foreignObject>
      </svg>
    )
  }
}
export default SummaryChartIcon

test case:

import React from 'react'
import {shallow} from 'enzyme'
import toJson from 'enzyme-to-json'
import SummaryChartIcon from './SummaryChartIcon'

describe('<SummaryChartIcon />', () => {
  it('should render', () => {
    const wrapper = shallow(
      <SummaryChartIcon weatherIconCode={200} />
      )
    expect(toJson(wrapper)).toMatchSnapshot()
  })
})

Upvotes: 3

Views: 8714

Answers (1)

GibboK
GibboK

Reputation: 73918

You should pass the right property for your component, in your case is payload which contain another object called with property weatherIconCode

If you change the code as follow it should work.

describe('<SummaryChartIcon />', () => {
  it('should render', () => {
    const wrapper = shallow(
      <SummaryChartIcon payload={{weatherIconCode: 200}} />
      )
    console.log(wrapper.debug())
    expect(toJson(wrapper)).toMatchSnapshot()
  })
})

Upvotes: 3

Related Questions