0

I want to write some unit test cases which are using combnereducers() function. I have something like following.

myReducers1.js

function reducer1(state = {}, action) {
   //some logic
}

function reducer2(state = {value1: {}}, action) {
  //some logic
}

const appReducer = combineReducers({reducer1, reducer2})

export default appRecuer;

So is there any way to test the code written inside the reducer1 and reducer2? If there is then how can i reach to the reducer1 and reducer2 function which are inside myReducers1.js. I have already gone through to the Testing Redux combined reducers but this is having the different context. So please help me. Thanks in advance.

skyboyer
  • 22,209
  • 7
  • 57
  • 64
Shravan Jain
  • 720
  • 1
  • 11
  • 32
  • 1
    export reducer1 and reducer2 and test them indivudually (you dont need to test 'combineReducers' it is supposed to be tested by redux ;) ) – Ji aSH Jun 05 '18 at 21:20
  • Are you talking about testing individual reducers? If so then just import reducer in your test file and pass mock objects to it. – Rikin Jun 05 '18 at 21:21
  • All of my reducers are in a single file. And i am combining them by using combineReducers() function. – Shravan Jain Jun 06 '18 at 10:08

2 Answers2

2

using jest:

mock a prevState:

const state = {var1: value};

make sure both reducer and action are declared or imported in the test file and run your test:

test('reducer test', () => {
  expect(reducer(state, action).toBe(your result);
});

exemple:

const testAction = { type:'INCREMENT_AGE' };

const prevState = { age: 37, name: "John Doe"};

const reducer = (state, action) => (action.type === "INCREMENT_AGE" ?{...state, age: state.age + 1} : state)

test('reducer test', () => {
  expect(reducer(prevState, testAction).toEqual({name: "John Doe", age: 38});
});
1

Assuming you have exported individual reducer and action, you just call reducer with custom/desired action and pass initial state or desired state and test for changed state object.

import reducer from '../src/reducers/reducer1';
import * as actions from '../src/actions/action1';

describe('reducer1', () => {
  it('should return the initial state', () => {
    const state = reducer(undefined, {});
    expect(state.loading).toEqual(true);
  });

  it('should handle CUSTOM_ACTION', () => {
    const action = {
      type: actions.CUSTOM_ACTION
    };
    const state = reducer({}, action);

    expect(state.foo).toEqual('desired value');
  });
});
Rikin
  • 5,351
  • 2
  • 15
  • 22
  • All of my reducers are in a single file. And i am combining them by using combineReducers() function. I got the solution from above answer. Thanks for your help. – Shravan Jain Jun 06 '18 at 10:06