需要为使用联合减速器的redux减速器编写单元测试用例

时间:2018-06-05 18:09:45

标签: reactjs unit-testing redux react-redux jestjs

我想编写一些使用combnereducers()函数的单元测试用例。我有类似的事情。

myReducers1.js

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

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

const appReducer = combineReducers({reducer1, reducer2})

export default appRecuer;

那么有没有办法测试reducer1reducer2内写的代码?如果有,那么我如何才能到达reducer1内的reducer2myReducers1.js函数。 我已经进入了Testing Redux combined reducers,但这有不同的背景。所以请帮助我。 提前致谢。

2 个答案:

答案 0 :(得分:1)

使用jest:

模拟一个prevState:

const state = {var1: value};

确保在测试文件中声明或导入reducer和action并运行测试:

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

为例:

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 :(得分:1)

假设您已导出单个reducer和action,您只需使用自定义/所需操作调用reducer并传递初始状态或所需状态并测试已更改的状态对象。

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