Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

React Redux: Testing mapStateToProps and mapDispatchToProps with Enzyme/Jest

So I would like to test mapStateToProps and mapDispatchToProps with Enzyme/Jest.

I have a component DrawerAvatar like this:

DrawerAvatar.js

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

export default compose(
  connect(mapStateToProps, null)
)(DrawerAvatar);

DrawerAvatar.test.js

import configureMockStore from 'redux-mock-store';
import connectedDrawerAvatar, { DrawerAvatar } from './DrawerAvatar';

const mockStore = configureMockStore();

it('mapStateToProps should return the right value', () => {
  const initialState = {
    someState: 123
  };
  const store = mockStore(initialState);
  const wrapper = shallow(<connectedDrawerAvatar store={store} />);
  expect(wrapper.props().someState).toBe(123);
});

However, this doesn't work because wrapper.props().someState returns undefined... So I have no clue how to test mapStatesToProps along with redux-mock-store using the connected component.

I don't know neither how to test mapDispatchToProps ..! I've tried the methods providing in this blog but it doesn't work.

Thank you very much !

EDIT: This works, but I'm not sure if it really tests the mapStateToProps... Can someone confirm that this is the right way to test mapStateToProps ? DrawerAvatar.test.js

  it('mapStateToProps should return the right value', () => {
    const initialState = {
      isAuthenticated: false
    };
    const mockStore = configureMockStore();
    const store = mockStore(initialState);

    const wrapper = shallow(<connectedDrawerAvatar store={store} />);
    expect(wrapper.props().store.getState().isAuthenticated).toBe(false);
  });
like image 731
filipyoo Avatar asked Aug 21 '18 07:08

filipyoo


1 Answers

One way I found from : redux discussion on github is

import React from 'react';
import { shallow } from 'enzyme';
import configureMockStore from 'redux-mock-store';

import ConnectedDrawerAvatar from './DrawerAvatar';
describe('DrawerAvatar', ()=> {
    const mockStore = configureMockStore();

    it.each([true, false], 'receives correct value from store as props', (value)=> {
        const initialState = { authReducer: { isAuthenticated: value } }
        const store = mockStore(initialState)

        const wrapper = shallow(<ConnectedDrawerAvatar store={store} />)
        expect(wrapper.props().isAuthenticated).toBe(value)
    })
})
like image 71
Rajnikant Avatar answered Nov 14 '22 00:11

Rajnikant