Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to access child of a component in jest in a react/redux app

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

like image 632
Mark Qian Avatar asked Jul 05 '17 05:07

Mark Qian


1 Answers

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

like image 123
CharlieBrown Avatar answered Oct 17 '22 07:10

CharlieBrown