简体   繁体   English

如何测试React渲染功能的贴图结果?

[英]How to test for a map result of a react render function?

This is how I get an array of Dropdown.Item elements returned in my react component. 这就是我如何在我的react组件中返回一个Dropdown.Item元素数组。

render () {
  const { data } = this.props

  if (data) {
    return data.map((item, index) => {
      return <Dropdown.Item
        text={item.title}
        key={index}
      />
    })
  }
  return null
}

Now I'm trying to test for the returned result, but my test fails with recieved.length: 0 . 现在,我正在尝试测试返回的结果,但是我的测试失败,显示为recieved.length: 0 I think the issue is returning a map... How do I have to test for that? 我认为问题正在返回地图...我该如何测试?

it('should render dropdown items', () => {
  wrapper = shallow(<Component data={data} />)
  expect(wrapper.find(Dropdown.Item)).toHaveLength(2)
})

My data looks like: 我的数据如下:

[ { _id: '1', title: 'Item 1' }, { _id: '2', title: 'Item 2' } ]

Update 更新资料

This is working for me: 这为我工作:

expect(wrapper.at(0).find(Dropdown.Item)).toHaveLength(2)

But why do I have to use at(0) ? 但是为什么我必须使用at(0)

I think you could do something like this.. 我想你可以做这样的事情。

class Component extends React.Component {
...
  render() {
  const { data } = this.props
  return (data.map((item, index) =>  <Dropdown text={item.title} key={index}/>));
  }
}
class Dropdown extends React.Component {
...
  render(){
  const {text, key} = this.props;

  return(
    <div>  
      <li className='test'>
        {text}
      </li> 
    </div>
   )
  }
}

describe('<MyComponent />', () => {
  it('renders two <Dropdown /> components', () => {
     const wrapper = shallow(<Component data={[{ _id: '1', title: 'Item 1' }, { _id: '2', title: 'Item 2' }]} />);
     expect(wrapper.find('Dropdown').to.have.length(2));
  });
});

use to.have.length instead of toHaveLength , check enzyme docs ref: http://airbnb.io/enzyme/docs/api/ReactWrapper/find.html 使用to.have.length而不是toHaveLength ,检查酶文档参考: http : toHaveLength

see also Shallow Rendering example from enzyme docs: 另请参见酶文档中的“浅渲染”示例:

describe('<MyComponent />', () => {
  it('renders three <Foo /> components', () => {
    const wrapper = shallow(<MyComponent />);
    expect(wrapper.find(Foo)).to.have.length(3);
  });

ref: https://github.com/airbnb/enzyme/blob/HEAD/docs/api/shallow.md 参考: https : //github.com/airbnb/enzyme/blob/HEAD/docs/api/shallow.md

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM