Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

enzyme shallow rendering just one node in redux components

Tags:

Enzyme shallow rendering behaves in an unexpected way if I am rendering a redux component with a mocked store.

I have a simple test that looks like this :

  import React from 'react';
  import { shallow } from 'enzyme';
  import { createMockStore } from 'redux-test-utils';

  import Test from './Test'

  it('should render ', () => {
    const testState = {
      app: {
        bar: ['a', 'b', 'c']
      }
    };

    const store = createMockStore(testState)
    const context = {
      store,
    };
    const shallowComponent = shallow(<Test items={[]}/>, {context});

    console.log(shallowComponent.debug());

  }

The Test component looks like :

class Test extends React.Component {
  constructor(props) {
    super(props);
  }
  render() {
    return(
      <div className="here"/>
    )
  }
}
export default Test;

Which as expected prints out this :

 <div className="here" />

However if my component is a redux component :

class Test extends React.Component {
  constructor(props) {
    super(props);
  }
  render() {
    return(
      <div className="here"/>
    )
  }
}
const mapStateToProps = state => {
  return {
    barData: state.app.bar
  }
}

export default connect(
  mapStateToProps
)(Test)

Then what I get in the console is this :

<BarSeriesListTest items={{...}} barData={{...}} dispatch={[Function]} />

Why is there this difference? How do I test that my component has <div className="here"/> embedded in it in my redux version of the component?

like image 386
Oliver Watkins Avatar asked Oct 22 '17 15:10

Oliver Watkins


1 Answers

You are referencing the HOC that connect is returning and not the component that you want to test.

You should use enzyme's dive function which will render the child component and return it as a wrapper.

const shallowComponent = shallow(<Test items={[]}/>, {context}).dive();

You can use it multiple times if you have multiple components that you need to dive through to get to. It's better than using mount as well because we are still testing in isolation.

like image 85
Martin Dawson Avatar answered Sep 25 '22 11:09

Martin Dawson