如何传递使用Enzyme.js渲染的组件的道具?

时间:2017-11-21 17:15:17

标签: reactjs ecmascript-6 jestjs enzyme

我有一个如下所示的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测试我的组件。我只是在练习模拟我需要的道具所需的语法时才遇到问题。建议的副本更抽象和概念化。我的问题是关于这些概念的粒度执行。

1 个答案:

答案 0 :(得分:6)

您正在测试的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} />)
相关问题