简体   繁体   中英

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.

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 . 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) ?

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

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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