Unit testing Redux减速器单元测试

Unit testing Redux减速器单元测试,unit-testing,redux,mocha.js,Unit Testing,Redux,Mocha.js,我正在尝试对redux reducer进行单元测试。但我正在努力获得同样的预期和同样的结果 const initState = {}; export default function (state = initState, action) { const newState = { ...state }; switch (action.type) { case CREATE_TYPE: return { ...state, [acti

我正在尝试对redux reducer进行单元测试。但我正在努力获得同样的预期和同样的结果

const initState = {};

export default function (state = initState, action) {
  const newState = { ...state };
  switch (action.type) {

    case CREATE_TYPE:
      return {
        ...state,
        [action.customType.id]: {
          ...action.customType
        }
      };
    default:
      return state;
  }
}
我的测试。似乎
customType:{id:'testid'}

describe('reducer', () => {
  it('should return the initial state', () => {
    const state = reducer(undefined, { type: 'unknown' });
    expect(state).toEqual({});
  });

  it('should handle CREATE_TYPE', () => {
    expect(reducer({ test: true }, {
      type: CREATE_TYPE,
      customType: { id: 'test-id' },
      id: 'test-id'
    })).toEqual({
      'test-id': 'test-type',
      'test': true
    });
  });
});

您正在从减速器中返回:

{
    ...state,
    [action.customType.id]: {
      ...action.customType
}
如果你寄

{
  type: CREATE_TYPE,
  customType: { id: 'test-id' },
  id: 'test-id'
}
将等同于:

{
   ...state,
   'test-id' : { id: 'test-id' }
}
你的评估结果等于

{
 ...state,
'test-id': 'test-type'
}

我不知道您希望如何通过reducer格式化您的状态-但是现在设置reducer的方式无法提供您期望的状态。我不知道您期望的是什么,因为我在您提供的代码的任何其他地方都看不到节点或值“test type”。看起来您可能只是有一些语法错误?

您正在从减速机中返回:

{
    ...state,
    [action.customType.id]: {
      ...action.customType
}
如果你寄

{
  type: CREATE_TYPE,
  customType: { id: 'test-id' },
  id: 'test-id'
}
将等同于:

{
   ...state,
   'test-id' : { id: 'test-id' }
}
你的评估结果等于

{
 ...state,
'test-id': 'test-type'
}

我不知道您希望如何通过reducer格式化您的状态-但是现在设置reducer的方式无法提供您期望的状态。我不知道您期望的是什么,因为我在您提供的代码的任何其他地方都看不到节点或值“test type”。看起来你只是有一些语法错误,也许吧?

通常,它有助于把所有的事情都说清楚

这样你就可以清楚地了解你的预期结果是什么

it('should handle CREATE_TYPE', () => {
  const initialState = { test: true };
  const customType = { id: 'test-id' };
  const action = {
    type: CREATE_TYPE,
    customType: customType,
    id: customType.id
  };
  const result = reducer(initialState, action);
  const expectedResult = {
    test: true,
    [customType.id]: customType
  };
  expect(result).toEqual(expectedResult);
});

这样就更容易看清问题的确切位置。

通常,这有助于把一切都说清楚

这样你就可以清楚地了解你的预期结果是什么

it('should handle CREATE_TYPE', () => {
  const initialState = { test: true };
  const customType = { id: 'test-id' };
  const action = {
    type: CREATE_TYPE,
    customType: customType,
    id: customType.id
  };
  const result = reducer(initialState, action);
  const expectedResult = {
    test: true,
    [customType.id]: customType
  };
  expect(result).toEqual(expectedResult);
});

这样就更容易看清问题所在。

事实上,我得到的减速机没有定义。实际上,我得到的减速机没有定义