gpt4 book ai didi

reactjs - 如何传递使用 Enzyme.js 渲染的组件的 props?

转载 作者:行者123 更新时间:2023-12-03 13:26:23 24 4
gpt4 key购买 nike

我有一个看起来像这样的 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:无法读取未定义的属性“id”,我理解这可能意味着我没有正确地将 Prop 传递到我的测试中。

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

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 测试我的组件。我只是在实际模拟测试工作所需的 Prop 所需的语法方面遇到了麻烦。建议的副本更加抽象和概念化。我的问题是关于这些概念的精细执行。

最佳答案

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

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

当您渲染需要测试的组件时,您需要传递它。你可以这样做

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

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

关于reactjs - 如何传递使用 Enzyme.js 渲染的组件的 props?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47418912/

24 4 0
文章推荐: reactjs - react 16 : Warning: Expected server HTML to contain a matching