Shallow snapshot to ignore child components

Viewed 343

I have the following component where the component have a child component within it which also has a child in it.
Thus forming following structure.

<BackgroundComponent>
    <MidComponent>
        <InnerComponent>
            // some data
        </InnerComponent>
    </MidComponent>
</BackgroundComponent>


Is there a way to snapshot only the top level component without rendering the child components?

Meaning I only want 1 snapshot to hold data on BackgroundComponent.
Another snapshot only for MidComponent.
And another snapshot only for InnerComponent.

I was expecting to achieve this via shallow. But this is not the case.
Shallow is capturing everything when I target BackgroundComponent ending up with a very large snapshot
which I wish to avoid and keep the snapshot smaller. Please advice.

This is the component

import React, { Fragment } from 'react';

const MyComponent = () => {

  return (
    <Fragment>
        <BackgroundComponent>
          <MidComponent>
            <InnerComponent>
              {'Some text value}
            </InnerComponent>
          </MidComponent>
        </BackgroundComponent>
    </Fragment>
  );
};

export default MyComponent;

This is my test case.

import React from 'react';
import { shallow } from 'enzyme';
import MyComponent from '../../src/components/MyComponent';

describe('MyComponent tests', () => {
  const render = props => shallow(
    <MyComponent/>
  );

  it('should render the MyComponent MidComponent', () => {
    // expected this to only snapshot top level for BackgroundComponent component. Instead the snapshot captures
    // everything including the MidComponent and InnerComponent components. 
    expect(render().find('BackgroundComponent')).toMatchSnapshot();

    // This ends up snapshoting MidComponent and InnerComponent when I only want it to be MidComponent
    // expect(render().find('MidComponent')).toMatchSnapshot();

    // This would make sense snapshoting only the inner one which is what I want. 
    // Issue is with above 2 snaps.  
    // expect(render().find('InnerComponent')).toMatchSnapshot();
  });
});
1 Answers

Try mocking the components you want out of the snapshot for each respective file

jest.mock('./MidComponent', () => ({
  default: () => <div />
}))

or

import MidComponent from './MidComponent'
jest.mock('./MidComponent')
MidComponent.mockImplementation = () => <div />

You can try () => null for a full exemption of any HTML. Not sure if it works though

Related