How to access child of a component in jest in a re

2019-08-02 07:31发布

问题:

I like to test a component inside Connect in a Redux app:

this.component = TestUtils.renderIntoDocument(<Provider store={store}><Header path={this.path} /></Provider>);

I have no idea about how to access Header inside Provider...(since I can not stop through in a debugger when running the jest from CLI.

So when I tried to get a child inside Header

      const path = findDOMNode(self.component.refs.pathElemSpan);
      console.log("path="+path)

I got undefined on path

Any suggestion?

thanks

回答1:

Use enzyme, you have a bunch of nice selectors to navigate through your virtual DOM kingdom. :)

http://airbnb.io/enzyme/

A super simple test to access your component:

import { mount } from 'enzyme'
import Header from './header'

//... in your test
const wrapper = mount(<Provider store={store}><Header path='foo' /></Provider>)
const header = wrapper.find(Header).first()
expect(header.exists()).toBe(true)
// you can even check out the props
expect(header.prop('path')).toBe('foo')

This example is using mount but you also have the option to do shallow rendering. I highly recommend you grab something to drink and read the docs a little. ;)



回答2:

import Foo from '../components/Foo';


const wrapper = mount(<MyComponent />);

expect(wrapper.find(Foo)).to.have.lengthOf(1); //you can use this one
expect(wrapper.find('Foo')).to.have.lengthOf(1); //you can use this one as well


回答3:

Are you looking for this ?

function Welcome(props) {
  return <h1>Hello, {props.name}</h1>;
}

function App() {
  return (
    <div>
      <Welcome name="Sara" />
      <Welcome name="Cahal" />
      <Welcome name="Edite" />
    </div>
  );
}

ReactDOM.render(
  <App />,
  document.getElementById('root')
);