0


I'm using grommet with react to render my application's UI. I have a Layer component shown when user click a button. Everything works fine but I don't know how to test Layer's children. I'm using enzyme, mocha and chai as test suite. This is code the code of my component:

<Layer align="right" closer>
    <Header size="large" justify="between" align="center">
        <Button icon={<CloseIcon />} plain={true} onClick={ props.hide }/>
    </Header>
    <Section key={index} pad={{ horizontal: 'large', vertical: 'small' }}>
        { props.list }
    </Section>   
</Layer>

and this is my test:

const wrapper = shallow(<MyComponent />);
const layer = wrapper.find(Layer);

//this works
expect(layer).to.have.length.of(1);

const section = layer.find(Section);

//and this fails
expect(section).to.have.length.of(1);

Looking at the rendered component in the application, I found that grommet render his Layer component in this way:

<Layer><span style={{ display: 'none'}}></span></Layer>

Anyone can help me? Thank you

2 Answers2

1

If you look at the source code for the layer component, you will see that it returns the span that you posted in the render method. It's not until the component has mounted that the layer's contents will be rendered by calling the addLayer method in the Layer class.

I believe that you should use enzyme's mount function in order to test that the Layer is properly rendering its content since you will want the componentDidMount method to be called.

Ryan C.
  • 539
  • 1
  • 5
  • 7
  • I try to use mount instead of shallow, but result is the same. I found the span not in the testing environment, but inspecting my page with chrome developers react Tools while application is running. I also notice that layer's content are rendered outside the entire application, but it doesn't make sense! – alessia pileri Jun 20 '17 at 17:55
  • Hey @alessia, that's correct. Looking through the [code](https://github.com/grommet/grommet/blob/master/src/js/components/Layer.js#L218-L233), it looks like the layer is added to the dom after mount so the result of the test is correct. – Ryan C. Jun 21 '17 at 21:24
  • 1
    I found an answer that contains instructions for testing the actual DOM using Enzyme and JSDom. See [here](https://stackoverflow.com/a/38424409/5948656). – Ryan C. Jun 21 '17 at 21:33
0

I finally managed to resolve this issue by mocking grommet Layer component:

jest.mock("grommet/components/Layer", () => (props) => props.children);
raisedbywolves
  • 111
  • 2
  • 6