swapnilpatil24
swapnilpatil24

Reputation: 41

how to test combineReducers with jest

I am trying to test combineReducers but getting following error.

TypeError: _testReducer.testReducer.test11 is not a function

Following is the reducer

// testReducer.js
import { combineReducers } from "redux-immutable";
const test11 = (state, action) => {
 switch (action.type) {
    case "temp11":
      return true;
    default:
      return state;
  }
};
const test22 = (state, action) => {
 switch (action.type) {
    case "temp22":
      return false;
    default:
      return state;
  }
};
export const testReducer = combineReducers({
  test11,
  test22,
});

Following is the test case

// testReducer.test.js
import { testReducer } from "./testReducer.js";
describe("test for testReducer", () => {
  it("test11", () => {
    const returnTrueValue = true;
    expect(
      testReducer.test11(
        true, {
          type: "temp11",
        }
      )
    ).toEqual(returnTrueValue);
  });
  it("test11", () => {
    const returnFalseValue = false;
    expect(
      testReducer.test22(
        true, {
          type: "temp22",
        }
      )
    ).toEqual(returnFalseValue);
  });
});

It worked if I export all functions in reducer and import individual in test case but thats not the idea case.

Upvotes: 3

Views: 4679

Answers (2)

Yuvraj Patil
Yuvraj Patil

Reputation: 8736

I assume component reducer looks like below:

export const initialState = {
  totalValue: 0
};

const DashboardReducer = (state = initialState, action: any)=> {
  switch(action.type) {
    case 'case1':
     .......
     .......
     .......
    default:
      return state;
 }

I assume root reducer looks like below:

export const rootReducer = combineReducers({
  dashboard: DashboardReducer
});

Test File should be like below:

import { rootReducer } from './root.reducer';
import { createStore } from 'redux';
import { initialState as dashboardState } from './modules/uv_dashboard/uv_dashboard.reducer';

describe('Root Reducer Suite', () => {

  let store = createStore(rootReducer)

  test('loaded correctly', () => {
    expect(store.getState().dashboard).toEqual(dashboardState);
  });
});

Upvotes: 4

Moti Azu
Moti Azu

Reputation: 5442

combineReducers returns a function that merges the states of all the reducers you put in it. It does not allow you to access individual reducers and call them individually.

You should use it this way for your case:

expect(
    testReducer(true, {type: "temp11"}).test11
).toEqual(returnTrueValue);

Upvotes: 6

Related Questions