mae*_*zzi 6 ecmascript-6 reactjs 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
Run Code Online (Sandbox Code Playgroud)
我正在尝试编写一个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()
})
Run Code Online (Sandbox Code Playgroud)
我得到了这个错误: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()
})
Run Code Online (Sandbox Code Playgroud)
当我运行上面的代码时,我得到了与以前相同的错误.
对于我做错了什么,或者我在这里不明白,我会深表感谢.谢谢!
编辑:有人建议这个问题与另一个问题重复:开始使用Enzyme和Jest测试React组件.
我不认为这是重复的.我知道我想用Jest和Enzyme测试我的组件.我只是在练习模拟我需要的道具所需的语法时才遇到问题.建议的副本更抽象和概念化.我的问题是关于这些概念的粒度执行.
SongLink您正在测试的组件只需要一个包含以下属性的对象
在shallow渲染需要测试的组件时,需要传递它.你可以这样做
const songLinkProps = {
result: {
id: '6rPO02ozF3bM7NnOV4h6s2',
name: 'sf',
artist: 'sgs'
},
handleClick: () => {
console.log('click')
}
}
const component = shallow(<SongLink {...songLinkProps} />)
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
4661 次 |
| 最近记录: |