Enzyme: How to test components which are props of a shallow rendered component

Created on 22 Apr 2016  路  3Comments  路  Source: enzymejs/enzyme

I'm testing a component with a structure like this:

<ComponentA foo={<ComponentB bar={something} />

I want to verify that ComponentA.foo is a ComponentB and that its props are set correctly.

My test looks something like this:

const a = shallow(<ComponentA {...props} />)
const b = a.prop('foo')
expect(b.is(ComponentB)).to.be.true
// etc...

This doesn't work because b isn't wrapped in a shallow render, so I can't use shallow's API to test stuff. b appears to be a react component. I tried wrapping it in a shallow myself like this:

const wrappedB = shallow(b)

But that was problematic because ComponentB is actually a redux connected component and attempting to render it fails since the store isn't available and if at all possible I don't want to mock that out.

How can I handle testing components with this structure in a reasonable way? Is there something like shallow.find which can select a prop for me that is still _wrapped_ by shallow?

Most helpful comment

One bit of advice I can give with redux connected components is to also export your base class as well as your connected component and import that directly instead.

export class BaseClass extends Component {
// ...
}

export default connect()(BaseClass)

Then you can just do

import {BaseClass} from './components/BaseClass'

and just mock the props that redux provides.

All 3 comments

If shallow-rendering it with const wrappedB = shallow(b) fails, then so too would anything shallow itself would do to wrap it.

One bit of advice I can give with redux connected components is to also export your base class as well as your connected component and import that directly instead.

export class BaseClass extends Component {
// ...
}

export default connect()(BaseClass)

Then you can just do

import {BaseClass} from './components/BaseClass'

and just mock the props that redux provides.

472

Was this page helpful?
0 / 5 - 0 ratings