PremKumar
PremKumar

Reputation: 1354

Unable to get props while testing with jest Enzyme React

My Component Code:

import React from 'react'
export default class InfoViewComponent extends React.Component {
  constructor (props) {
    super(props)
    this.toggle = this.toggle.bind(this)
    this.state = {
      counter: 1,
      activeTab: '1',
    }
  }
  render () {
    const data = this.props.data
    return (
      <section className="dish">
        <div>
          <Row>
            <Col>
                  <h1 className="display-1">{data.title}</h1>
                  <Button  onClick={this.handleAddToCart} >Add to Cart</Button>
                  <Button onClick={this.handleSubmit}>Place order</Button>
                </div>
                <p>{data.description}</p>

                <div>
                  <ButtonGroup>
                    <Button>-</Button>
                    <Button>{this.state.counter}</Button>
                  </ButtonGroup>
                 </div>
          </Row>
        </div>
      </section>
    )
  }
}

Testing Code

import React from 'react'
import { configure, shallow } from 'enzyme'
import Adapter from 'enzyme-adapter-react-16'
import InfoViewComponent from './InfoViewComponent'

configure({ adapter: new Adapter() })


describe('Info Component', () => {
  it('Should be defined', () => {
    const wrapper = shallow(<InfoViewComponent />)
    expect(wrapper.find(InfoViewComponent)).toBeDefined()
  })
})

data:

"menus": [
    {
      "code": "h8",
      "title": "Some Text",
      "type": "Some Text",
      "description": "Some Text",
      "images": [],
      "keywords": [
        "Some Text",
        "Some Text"
      ],
      "price": "3",
      "about": "Some Text,
     ],
    },
  ]

I'm unable to get all the props from my component to the testing code. I get error as "TypeError: Cannot read property 'title' of undefined". I need help on how to do this.
Added data to understand. I get the data from firebase in one component and pass it as it as props to InfoViewComponent that is to be tested. Thanks in advance.

Upvotes: 1

Views: 361

Answers (1)

Hemadri Dasari
Hemadri Dasari

Reputation: 34014

You are trying to access the title when the data is undefined. So what you have to do is check whether the data is undefined or not and only then access its fields like below

      {data && data != undefined && (<Row>
        <Col>
              <h1 className="display-1">{data.title}</h1>
              <Button  onClick={this.handleAddToCart} >Add to Cart</Button>
              <Button onClick={this.handleSubmit}>Place order</Button>
            </div>
            <p>{data.description}</p>

            <div>
              <ButtonGroup>
                <Button>-</Button>
                <Button>{this.state.counter}</Button>
              </ButtonGroup>
             </div>
      </Row>)}

Upvotes: 1

Related Questions