【发布时间】: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