Shravan Jain
Shravan Jain

Reputation: 720

Need to write unit test cases for redux reducers which are using combine reducers

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.

Upvotes: 0

Views: 2010

Answers (2)

Rikin
Rikin

Reputation: 5473

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');
  });
});

Upvotes: 1

Simon Mulquin
Simon Mulquin

Reputation: 156

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});
});

Upvotes: 2

Related Questions