Created
May 2, 2016 02:44
-
-
Save z2015/9879ea516c29df7f2cacdae40eafa93b to your computer and use it in GitHub Desktop.
Redux: Writing a Todo List Reducer (Toggling a Todo)
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| const todos = (state=[], action) => { | |
| switch (action.type) { | |
| case 'ADD_TODO': | |
| return [ | |
| ...state, | |
| { | |
| id: action.id, | |
| text: action.text, | |
| completed: false | |
| } | |
| ]; | |
| case 'TOGGLE_TODO': | |
| return state.map( | |
| todo => { | |
| if (todo.id != action.id){ | |
| return todo; | |
| } | |
| return { | |
| ...todo, | |
| completed: !todo.completed | |
| }; | |
| } | |
| ) | |
| default: | |
| return state; | |
| } | |
| }; | |
| const testAddTodo = () => { | |
| const stateBefore = []; | |
| const action = { | |
| type: 'ADD_TODO', | |
| id: 0, | |
| text: 'Learn Redux' | |
| }; | |
| const stateAfter = [ | |
| { | |
| id: 0, | |
| text: 'Learn Redux', | |
| completed: false | |
| } | |
| ]; | |
| deepFreeze(stateBefore); | |
| deepFreeze(stateAfter); | |
| expect ( | |
| todos(stateBefore, action) | |
| ).toEqual(stateAfter); | |
| }; | |
| const testToggleTodo = ()=> { | |
| const stateBefore = [ | |
| { | |
| id: 0, | |
| text: 'Learn Redux', | |
| completed: false | |
| }, | |
| { | |
| id: 1, | |
| text: 'Go shopping', | |
| completed: false | |
| } | |
| ]; | |
| const action = { | |
| type: 'TOGGLE_TODO', | |
| id: 1 | |
| }; | |
| const stateAfter = [ | |
| { | |
| id: 0, | |
| text: 'Learn Redux', | |
| completed: false | |
| }, | |
| { | |
| id: 1, | |
| text: 'Go shopping', | |
| completed: true | |
| } | |
| ]; | |
| deepFreeze(stateBefore); | |
| deepFreeze(stateAfter); | |
| expect( | |
| todos(stateBefore, action) | |
| ).toEqual(stateAfter); | |
| }; | |
| testAddTodo(); | |
| testToggleTodo(); | |
| console.log('Passed'); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment