Autoplay

    Redux: Writing a Counter Reducer with Tests

    Dan AbramovDan Abramov

    You will learn how to write the reducer for the counter application in a test driven development way, as well as the conventions in implementing reducers.

    Code

    Code

    Become a Member to view code

    You must be a Member to view code

    Access all courses and lessons, track your progress, gain confidence and expertise.

    Become a Member
    and unlock code for this lesson
    Transcript

    Transcript

    00:00 The first function we're going to write is the reducer for the counter example. Reducer accepts straight and action as arguments and returns the next trait. Before jumping into the implementation, we're going to make certain assertions using Michael Jackson's Expect library. We're going to assert that when the straight of the counter is zero and you pass an increment action it should return one. Similarly it should return two when this straight is one and you increment.

    00:33 We're going to add a couple of tests that test how decrement works, which is that it decrements from two to one and from one to zero and we're going to add a log to tell if our tests are successful.

    00:48 If you ran this test, they're actually going to fail because we haven't even begun to implement our reducer. We're going to start by checking the action type and if the action type is increment we're going to return straight plus one, but if it is decrement we're going to return straight minus one.

    01:10 If you run the tests we will find that this is enough to get them to pass. However, there are still some flaws in our current implementation of the counter reducer. For example, I think that if we dispatch an action that it does not understand, it should return the current straight of the application.

    01:31 However, if we check for that we will see that this test fails, because we currently don't handle unknown actions. I'm going to add an else clause that returns the current straight. The tests pass now.

    01:46 Another issue is that while the reducer is normally in control of the application straight, currently it does not specify the initial straight. In the case of counter example that would be zero. The convention we use in Redux is that if the reducer receives undefined as the straight argument, it must return what it considers to be the initial straight of the application. In this case it will be zero.

    02:14 Now come a few cosmetic tweaks. I'll replace this bunch of tweaks with a switch statement and I'm going to replace this condition with ES6 default argument, which looks better. I'm also going to replace the function declaration with an arrow function, which has clearer semantics in ES6.

    Discuss

    Discuss