javascriptreactjsreact-reduxreact-testing-libraryreact-testing

React Testing Library - Cannot read property 'contents' of undefined] - value from redux


Am new in writing testcases using React Test library.

Here is my component

    import React from 'react';
    import PropTypes from 'prop-types';
    import { connect } from 'react-redux';
    class MyContainer extends React.Component {
      static propTypes = {
        graphicalData: PropTypes.object.isRequired,
      };
      render() {
        const { graphicalData } = this.props;
        return (
         graphicalData && (
            <div>
             /////some action and rendering
        </div>
        ))}
        }
        const mapStateToProps = (state) => {
      return {
        graphicalData: state.design.contents ? state.design.contents.graphicalData : {},
      };
    };
    const mapDispatchToProps = (dispatch) => ({});
    export default connect(mapStateToProps, mapDispatchToProps)(MyContainer)));

So i am writing my test case file using React Testing library

    import React from 'react';
    import '@testing-library/jest-dom';
    import { render, cleanup, shallow } from '@testing-library/react';
    import MyContainer from '../../MyContainer';
    import configureMockStore from 'redux-mock-store';
    import ReactDOM from 'react-dom';
    const mockStore = configureMockStore();
    import { Provider } from 'react-redux';
    
    
    const store = mockStore({
        state: {
            design: {
              contents: {
                graphicalModel: { cars: [{},{}], bikes: [{},{}] },
              },
            },
          },
    });
    
    afterEach(cleanup);
    
    it('renders without crashing', () => {
      const div = document.createElement('div');
      ReactDOM.render(
        <Provider store={store}>
          <MyContainer />
        </Provider>,
        div
      );
      ReactDOM.unmountComponentAtNode(div);
    });

Am not sure what went wrong , my idea is to check if the component loads without crashing , also if the cars array length is greater than 0 , check something rendered on page.

But am getting some error, any help with example or suggestion will save my day


Solution

  • The error seems correct. Check the structure that you have passed into the mockStore() function. It is

    state: {
      design: {
        contents: {
          graphicalModel: { cars: [{},{}], bikes: [{},{}] },
        },
      },
    },
    

    So, when you access in your MyContainer, you should access it as

    state.state.design.contents
    

    It is just that you have an extra hierarchy in the state object.

    Or, if you don't want to change the component, change the structure of the state passed into your mockStore() method as:

    const store = mockStore({
      design: {
        contents: {
          graphicalModel: { cars: [{},{}], bikes: [{},{}] },
        },
      },
    });