【问题标题】:How do I pass props a component rendered with Enzyme.js?如何将使用 Enzyme.js 渲染的组件传递给 props?
【发布时间】:2018-05-05 06:14:19
【问题描述】:

我有一个如下所示的 SongLink 组件:

import React from 'react'

const SongLink = props => (
  <ul className='search-results__ul'
      key={props.result.id} 
      onClick={props.handleClick} 
  >
    {props.result.name} by {props.result.artist}
  </ul>
)

export default SongLink

我正在尝试编写一个 Jest 测试来测试这个组件。我的第一次尝试是这样的:

import React from 'react'
import { shallow } from 'enzyme'
import { configure } from 'enzyme'
import Adapter from 'enzyme-adapter-react-15'

import SongLink from '../components/SongLink'

configure({ adapter: new Adapter() })

test('it renders correctly', () => { 
  const component = shallow(<SongLink />)
  let tree = component.toJSON()
  expect(tree).toMatchSnapshot()
})

我收到了这个错误:TypeError: Cannot read property 'id' of undefined 我理解这可能意味着我没有正确地将道具传递给我的测试。

然后,我尝试了这个,其目的是模拟我认为道具的样子:

import React from 'react'
import { shallow } from 'enzyme'
import { configure } from 'enzyme'
import Adapter from 'enzyme-adapter-react-15'

import SongLink from '../components/SongLink'

configure({ adapter: new Adapter() })   

test('it renders correctly', () => {

  // This is where I tried to imitate the props and pass them in. 

  const songLinkProps = {
    result: {
      id: '6rPO02ozF3bM7NnOV4h6s2'
    },
    handleClick: () => {
      console.log('click')
    }
  }

  const component = shallow(<SongLink key={songLinkProps.result.id} />)
  let tree = component.toJSON()
  expect(tree).toMatchSnapshot()
})

当我运行上面的代码时,我得到了和以前一样的错误。

对于我做错了什么或我在这里不理解的任何建议,我将不胜感激。谢谢!

编辑:有人建议这个问题与另一个问题重复:Getting started testing React components with Enzyme and Jest

我不认为这是重复的。我知道我想使用 Jest 和 Enzyme 测试我的组件。我只是在实际模拟测试工作所需的道具时遇到了语法问题。建议的副本更加抽象和概念化。我的问题是关于这些概念的精细执行。

【问题讨论】:

标签: reactjs ecmascript-6 jestjs enzyme


【解决方案1】:

您正在测试的SongLink 组件只需要一个包含以下属性的对象

  • props.result.id
  • props.handleClick
  • props.result.name
  • props.result.artist

shallow渲染需要测试的组件时需要传递。你可以这样做

const songLinkProps = {
    result: {
      id: '6rPO02ozF3bM7NnOV4h6s2',
      name: 'sf',
      artist: 'sgs'
    },
    handleClick: () => {
      console.log('click')
    }
  }

  const component = shallow(<SongLink {...songLinkProps} />)

【讨论】:

  • 谢谢@ShubhamKhatri!非常感谢!
猜你喜欢
  • 2016-03-19
  • 2019-12-05
  • 1970-01-01
  • 2021-04-15
  • 2022-11-17
  • 2021-10-03
  • 1970-01-01
  • 2019-08-09
  • 2018-08-11
相关资源
最近更新 更多