1
votes

I have a React component like the following:

Component1.js

import React from 'react';
import Component2 from './Component2.js';

const Component1 = () => (<div data-test="component1-component"><Component2 /></div>);

Component2.js

import React from 'react';
import { connect } from 'react-redux';

const Component2 = (props) => {
  return(
     <div data-test="component2-component">
       <h1>{`I am Component #2. Key is ${props.key}`}</h1>
     </div>
  );
};

const mapStateToProps = state => ({ key: state.key });

export default connect(mapStateToProps)(Component2);

As you can see, Component1 renders Component2 as a child component and this child component is connected to Redux store. I want to write a Jest-Enzyme test case for Component1 that tests to see whether it renders Component2 as its child without connecting Component2 to Redux mock store. I am looking for something like the following:

describe('Component1', () => {
  const wrapper = mount(<Component1 />);
  const component1Component = wrapper.find({ "data-test": "component1-component" });
  const component2Component = wrapper.find({ "data-test": "component2-component" });

  it('renders the ~Component2~ as a child component', () => {
    expect(component2Component.exists()).toBeTruthy();
  });
});

Currently, I am getting an error saying that the child component is not provided with the store. How do I go about testing this?

1
you can wrap Component1 with a Provider in your test => <Provider store={store}> <Component1 /> </Provider>Olivier Boissé
@OlivierBoissé That is not the original questionuser117829

1 Answers

0
votes

Usually you would just shallow render your Component1. This means that Component1 will be "rendered" but the Child Components of Component1 won't be rendered. (Documentation of the shallow rendering api.)

import { shallow } from 'enzyme';

describe('Component1', () => {
  const wrapper = shallow(<Component1 />);
  ...

In your example the shallow render would contain a div and Component2 as Child of that div. However Component2 is not rendered (it is basically treated like the div, which cannot be resolved further). Therefore there is no need to supply any mock store.

Note that shallow rendering Component1 limits the test to Component1, Component2 is not tested at all the test above and you should test Component2 seperately. (Export the unconnected version of Component2 and supply the required props to test it.)

Complete Example

As an example for good tests which handle connected components I would recommend the source code of react admin.

For example the SimpleForm Component (just randomely picked):

Side Note: Don't use key like a normal prop as it has a special use to (re)identify the component in the virtual dome. More about the usage of keys can be found in the docs here and here. Connecting the key prop as you did in your example would result in React recreating the component for every change of that prop.