【问题标题】:Unable to get props while testing with jest Enzyme React用 jest Enzyme React 测试时无法获得道具
【发布时间】:2018-08-25 05:23:36
【问题描述】:

我的组件代码:

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

测试代码

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

数据:

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

我无法从我的组件获取所有道具到测试代码。 我收到错误为“TypeError:无法读取未定义的属性'标题'”。 我需要有关如何执行此操作的帮助。
添加数据以了解。我从一个组件中的 firebase 获取数据,并将其作为道具传递给要测试的 InfoViewComponent。 提前致谢。

【问题讨论】:

  • 与我们分享 MyComponent 的完整代码以及 this.props.data 的样子
  • 好的,我已经更新了代码
  • 也分享您的数据,即 this.props.data。问题是数据可用但标题键不存在或数据未定义,当您尝试访问它时将未定义。因此,为了进一步了解,我们想看看您的数据是什么样的,以及您从 wr 将数据传递给 MyComponent

标签: reactjs jestjs enzyme react-props


【解决方案1】:

当数据未定义时,您正在尝试访问标题。所以你要做的是检查数据是否未定义,然后才能访问它的字段,如下所示

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

【讨论】:

  • 当然可以:)
猜你喜欢
  • 1970-01-01
  • 2017-02-12
  • 2020-08-07
  • 2017-11-26
  • 2019-01-29
  • 1970-01-01
  • 2019-05-01
  • 2017-11-10
  • 2018-08-20
相关资源
最近更新 更多