简体   繁体   中英

How to test components being rendered when the redux store is changed?

I have the below component- PLoad.js:

import React, { useEffect } from 'react';
import { connect } from 'react-redux';
import Spinner from '../../../components/UI/Spinner/Spinner';
import { getLoad } from '../../../store/actions/poe';
import Load from '../../../components/apps/P/Load';

const PLoad = ({ dispatchGetLoad, loadD, loading }) => {
    return (loading ? <Spinner /> :
    <div>
        <Load loadD={loadD} />
    </div>
  );
}

const mapStateToProps = state => ({
   loadD: state.p.loadD,
   loading: state.p.loading
});

const mapDispatchToProps = dispatch => ({
   dispatchGetLoad: () => dispatch(getLoad())
});

export default connect(mapStateToProps, mapDispatchToProps)(PLoad);

I am trying to test this component using Jest+Enzyme -- PLoad.test.js

import React from 'react';
import { shallow, mount } from 'enzyme';
import { Provider } from 'react-redux';
import PLoad from '../PLoad';
import store from '../../../../store';
import Load from '../../../../components/apps/P/Load';
import Spinner from '.././../../../components/UI/Spinner/Spinner';

describe('PLoad component', () => {
  let wrapper;

  beforeAll(() => {
    wrapper = mount(
        <Provider store={store}>
            <PLoad />
        </Provider>);
   });

  it('should render the Load and Spinner components', () => {
    expect(wrapper.find(Spinner)).toHaveLength(1); //this is passed
    expect(wrapper.find(Load)).toHaveLength(1); //ended in error
  });
});

NOTE:- store.js used in the above PLoad.test.js is the actual store.js used by my app. I want to test when the loading: false, PLoad renders LoadD and when its true it renders Spinner. loading is from the state of the redux store. Is it possible?

You might try dispatching an action to change loading flag in state which will trigger render of the component.

it('should render the Load components', () => {
    ---- dispatch action -------
    expect(wrapper.find(Load)).toHaveLength(1);
  });

Yes...It is possible. The component gets whatever data you are passing to the provider. Pass an initialState object to store with loading:false . In fact you can create helper method with all the store creation logic in a separate file and reuse it in every connected component.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM