javascript - 使用 Jest 的问题 - 无法读取未定义的属性 'xxx'

标签 javascript reactjs jestjs enzyme

我在使用以下测试用例时收到错误:

 Cannot read property 'weatherIconCode' of undefined

我正在将 weatherIconCode 传递给测试用例中的组件,但我不明白为什么会出现 undefined。

非常欢迎任何想法如何通过简短的解释来解决。

组件:

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

测试用例:

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

最佳答案

您应该为您的组件传递正确的属性,在您的情况下是 payload,它包含另一个使用属性 weatherIconCode 调用的对象

如果您按以下方式更改代码,它应该可以工作。

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

关于javascript - 使用 Jest 的问题 - 无法读取未定义的属性 'xxx',我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46173527/

相关文章:

javascript - AMD、requirejs - 希望确保某些内容始终最后执行

javascript - 警告 : functions are not valid as a react child question. ..是因为我的容器吗?

javascript - 突出显示句子中的单独关键字

testing - 开 Jest beforeEach/afterEach 只是这个范围内的 block ?

reactjs - 使用 jest 和 react-testing-library 测试对象的属性时出错

javascript - 使用 Javascript 显示表单中的用户输入

javascript - React hooks - useState() 不会使用新的状态更新重新渲染 UI

javascript - 在 props 赋值中使用扩展运算符时 React Native 接收错误 : "In this environment the target of assign must be an object

javascript - 失败的 Jest 单元测试

node.js - 如何将 Node 调试 cli 与 Jest 一起使用?