2

我正在尝试测试 combineReducers 但出现以下错误。

TypeError: _testReducer.testReducer.test11 不是函数

以下是减速机

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

以下是测试用例

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

如果我在 reducer 中导出所有函数并在测试用例中导入单个函数,它会起作用,但这不是想法。

4

2 回答 2

6

combineReducers返回一个函数,该函数合并了您放入其中的所有减速器的状态。它不允许您访问单个减速器并单独调用它们。

您应该以这种方式使用它来处理您的情况:

expect(
    testReducer(true, {type: "temp11"}).test11
).toEqual(returnTrueValue);
于 2019-03-27T08:59:32.607 回答
2

我假设组件减速器如下所示:

export const initialState = {
  totalValue: 0
};

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

我假设根减速器如下所示:

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

测试文件应如下所示:

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);
  });
});
于 2021-05-11T06:47:53.557 回答