How to test child component method with Enzyme?

Fomahaut picture Fomahaut · Feb 15, 2017 · Viewed 28.4k times · Source

I have a component like that:

<Parent>
  <Child/>
</Parent>

and <Child/> component have a method foo. I want test the foo method but I don't know how to access it. I tried:

mount(<Parent><Child/></Parent>).props().children.foo

or

mount(<Parent><Child/></Parent>).children().foo

but both them are undefined. I can't use .instance() because it's not root. I can't mount <Child/> only because the <Parent> add something (react-router's context.router) on context and I need them when init <Child/>. Any idea with this?

Answer

rnmalone picture rnmalone · Feb 8, 2018

I would consider writing tests for only your parent class, and then a separate test file to only test your child.

Once you have mounted you component using:

const component = mount(<Child>); 

you then have access to it's methods using:

component.instance().methodname

You can then do stuff like override it with jest.fn() and test appropriately.