Writing a Counter Reducer with Tests

In notebook:
Egghead Redux
Created at:
2016-07-09
Updated:
2016-07-09
Tags:
libraries React JavaScript pattern
Uses Michael Jackson’s (from React Router fame) expect library for assertions. 

Writes the tests. Demonstrates that the reducer is really a pure function. Just passes a value and an action type and the result should equal the new state. 
  function counter (state, action) {
  if (action.type === 'INCREMENT') {
    return state + 1;
  } else if (action.type === 'DECREMENT') {
    return state - 1;
  }
}

// tests

expect(
  counter(0, {type: 'INCREMENT'})
  ).toEqueal(1);
// ETC
Adds the ability to handle unknown actions. 
  function counter (state, action) {
  if (action.type === 'INCREMENT') {
    return state + 1;
  } else if (action.type === 'DECREMENT') {
    return state - 1;
  } else {
    // +++++
    return state;
  }
}
It should also provide an initial state. If the reducer receives ​undefined​ as the ​state​ argument, it should return what it considers to be the initial state.
  function counter (state, action) {
  // ++++
  if (typeof state === 'undefined') {
    return 0;
  }
  
  
  if (action.type === 'INCREMENT') {
    return state + 1;
  } else if (action.type === 'DECREMENT') {
    return state - 1;
  } else {
    return state;
  }
}
Then replaces the ​if​ statements with ​switch(action.type)​. 
And adds some ES6 syntax for adding default state, arrow functions.