2017-06-19 87 views
0

而我正在尝试为redux reducer做单元测试。但我正在努力接受相同的预期和相同的结果。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: 'test-id' }

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

回答

2

通常它有助于拼出所有内容。

通过这种方式,您可以清楚地了解您的预期结果。

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

然后,就可以更容易地看到问题的确切位置。

1

这个问题你exprecting从减速回:

{ 
    ...state, 
    [action.customType.id]: { 
     ...action.customType 
} 

它,如果你发送

{ 
    type: CREATE_TYPE, 
    customType: { id: 'test-id' }, 
    id: 'test-id' 
} 

将等于自己:

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

你是eval uating它等于

我不知道你是如何期待通过您减速格式化你的状态 - 但你的减速建立现在的方式将不提供您所期待的状态。我不知道你在期待什么,因为我没有在你提供的代码中的任何其他地方看到节点或值“测试类型”。看起来你可能只是有一些语法错误?