Testing Reducers

Luckily, testing reducers is a lot like testing our synchronous action creators, since all reducer operations are synchronous. This plays a big role in making our global state easy to keep track of, which is why we're big fans of Redux.

We'll test the counter reducer in angular2-redux-starter, as follows:

  1. export default function counter(state = 0, action)
  2. switch (action.type) {
  3. case INCREMENT_COUNTER:
  4. return state + 1;
  5. case DECREMENT_COUNTER:
  6. return state - 1;
  7. default:
  8. return state;
  9. }
  10. }

As you can see, there are three cases to test: the default case, the increment and the decrement. We want to test that our actions trigger the state changes we expect from the reducer.

  1. import { INCREMENT_COUNTER, DECREMENT_COUNTER } from '../actions/counter';
  2. import counter from './counter';
  3. describe('counter reducers', () => {
  4. it('should handle initial state', () => {
  5. expect(
  6. counter(undefined, {})
  7. )
  8. .toEqual(0)
  9. });
  10. it('should handle INCREMENT_COUNTER', () => {
  11. expect(
  12. counter(0, {
  13. type: INCREMENT_COUNTER
  14. })
  15. )
  16. .toEqual(1)
  17. });
  18. it('should handle DECREMENT_COUNTER', () => {
  19. expect(
  20. counter(1, {
  21. type: DECREMENT_COUNTER
  22. })
  23. )
  24. .toEqual(0)
  25. });
  26. });

Note that we're only testing the section of Redux state that the counter reducer is responsible for, and not the whole.We can see from these tests that Redux is largely built on pure functions.

原文: https://angular-2-training-book.rangle.io/handout/testing/redux/reducers.html