Testing higher order reducer with jest











up vote
2
down vote

favorite












I'm trying to understand conception of creating unit tests for the frontend applications.



I have created higher order reducer:



// @flow

type action = {
type: string,
payload?: any
};

/**
* Async Reducer Factory to reduce duplicated code in async reducers.
* Higher Order Reducer.
*
* @param {String} name - Reducer name.
* @returns {Function}
*/
export const asyncReducerFactory = (name: String) => {
return (
state = { data: null, isLoading: false, error: null },
action: action
) => {
switch (action.type) {
case `FETCH_${name}_STARTED`:
return { data: null, isLoading: true, error: null };
case `FETCH_${name}_SUCCESS`:
return { data: action.payload, isLoading: false, error: null };
case `FETCH_${name}_ERROR`:
return { data: null, isLoading: false, error: action.payload };
default:
return state;
}
};
};


Tests:



import { asyncReducerFactory } from "./factories";

describe("Test async reducers factory", () => {
const factory = asyncReducerFactory("TEST");

it("should create reducer", () => {
expect(factory).not.toBe(null);
});

it("should start fetching", () => {
expect(factory({}, { type: "FETCH_TEST_STARTED" })).toEqual({
data: null,
isLoading: true,
error: null
});
});

it("should end fetching with success", () => {
expect(
factory({}, { type: "FETCH_TEST_SUCCESS", payload: "success" })
).toEqual({
data: "success",
isLoading: false,
error: null
});
});

it("should end fetching with error", () => {
expect(
factory({}, { type: "FETCH_TEST_ERROR", payload: "error" })
).toEqual({
data: null,
isLoading: false,
error: "error"
});
});

it("should return default state", () => {
expect(factory({}, { type: "DIFFERENT" })).toEqual({});
});
});


I would really appreciate, if you could let me know:




  1. if i'm using flow correctly?

  2. if my tests are reliable?

  3. how could i make it more generic?










share|improve this question














bumped to the homepage by Community 16 hours ago


This question has answers that may be good or bad; the system has marked it active so that they can be reviewed.



















    up vote
    2
    down vote

    favorite












    I'm trying to understand conception of creating unit tests for the frontend applications.



    I have created higher order reducer:



    // @flow

    type action = {
    type: string,
    payload?: any
    };

    /**
    * Async Reducer Factory to reduce duplicated code in async reducers.
    * Higher Order Reducer.
    *
    * @param {String} name - Reducer name.
    * @returns {Function}
    */
    export const asyncReducerFactory = (name: String) => {
    return (
    state = { data: null, isLoading: false, error: null },
    action: action
    ) => {
    switch (action.type) {
    case `FETCH_${name}_STARTED`:
    return { data: null, isLoading: true, error: null };
    case `FETCH_${name}_SUCCESS`:
    return { data: action.payload, isLoading: false, error: null };
    case `FETCH_${name}_ERROR`:
    return { data: null, isLoading: false, error: action.payload };
    default:
    return state;
    }
    };
    };


    Tests:



    import { asyncReducerFactory } from "./factories";

    describe("Test async reducers factory", () => {
    const factory = asyncReducerFactory("TEST");

    it("should create reducer", () => {
    expect(factory).not.toBe(null);
    });

    it("should start fetching", () => {
    expect(factory({}, { type: "FETCH_TEST_STARTED" })).toEqual({
    data: null,
    isLoading: true,
    error: null
    });
    });

    it("should end fetching with success", () => {
    expect(
    factory({}, { type: "FETCH_TEST_SUCCESS", payload: "success" })
    ).toEqual({
    data: "success",
    isLoading: false,
    error: null
    });
    });

    it("should end fetching with error", () => {
    expect(
    factory({}, { type: "FETCH_TEST_ERROR", payload: "error" })
    ).toEqual({
    data: null,
    isLoading: false,
    error: "error"
    });
    });

    it("should return default state", () => {
    expect(factory({}, { type: "DIFFERENT" })).toEqual({});
    });
    });


    I would really appreciate, if you could let me know:




    1. if i'm using flow correctly?

    2. if my tests are reliable?

    3. how could i make it more generic?










    share|improve this question














    bumped to the homepage by Community 16 hours ago


    This question has answers that may be good or bad; the system has marked it active so that they can be reviewed.

















      up vote
      2
      down vote

      favorite









      up vote
      2
      down vote

      favorite











      I'm trying to understand conception of creating unit tests for the frontend applications.



      I have created higher order reducer:



      // @flow

      type action = {
      type: string,
      payload?: any
      };

      /**
      * Async Reducer Factory to reduce duplicated code in async reducers.
      * Higher Order Reducer.
      *
      * @param {String} name - Reducer name.
      * @returns {Function}
      */
      export const asyncReducerFactory = (name: String) => {
      return (
      state = { data: null, isLoading: false, error: null },
      action: action
      ) => {
      switch (action.type) {
      case `FETCH_${name}_STARTED`:
      return { data: null, isLoading: true, error: null };
      case `FETCH_${name}_SUCCESS`:
      return { data: action.payload, isLoading: false, error: null };
      case `FETCH_${name}_ERROR`:
      return { data: null, isLoading: false, error: action.payload };
      default:
      return state;
      }
      };
      };


      Tests:



      import { asyncReducerFactory } from "./factories";

      describe("Test async reducers factory", () => {
      const factory = asyncReducerFactory("TEST");

      it("should create reducer", () => {
      expect(factory).not.toBe(null);
      });

      it("should start fetching", () => {
      expect(factory({}, { type: "FETCH_TEST_STARTED" })).toEqual({
      data: null,
      isLoading: true,
      error: null
      });
      });

      it("should end fetching with success", () => {
      expect(
      factory({}, { type: "FETCH_TEST_SUCCESS", payload: "success" })
      ).toEqual({
      data: "success",
      isLoading: false,
      error: null
      });
      });

      it("should end fetching with error", () => {
      expect(
      factory({}, { type: "FETCH_TEST_ERROR", payload: "error" })
      ).toEqual({
      data: null,
      isLoading: false,
      error: "error"
      });
      });

      it("should return default state", () => {
      expect(factory({}, { type: "DIFFERENT" })).toEqual({});
      });
      });


      I would really appreciate, if you could let me know:




      1. if i'm using flow correctly?

      2. if my tests are reliable?

      3. how could i make it more generic?










      share|improve this question













      I'm trying to understand conception of creating unit tests for the frontend applications.



      I have created higher order reducer:



      // @flow

      type action = {
      type: string,
      payload?: any
      };

      /**
      * Async Reducer Factory to reduce duplicated code in async reducers.
      * Higher Order Reducer.
      *
      * @param {String} name - Reducer name.
      * @returns {Function}
      */
      export const asyncReducerFactory = (name: String) => {
      return (
      state = { data: null, isLoading: false, error: null },
      action: action
      ) => {
      switch (action.type) {
      case `FETCH_${name}_STARTED`:
      return { data: null, isLoading: true, error: null };
      case `FETCH_${name}_SUCCESS`:
      return { data: action.payload, isLoading: false, error: null };
      case `FETCH_${name}_ERROR`:
      return { data: null, isLoading: false, error: action.payload };
      default:
      return state;
      }
      };
      };


      Tests:



      import { asyncReducerFactory } from "./factories";

      describe("Test async reducers factory", () => {
      const factory = asyncReducerFactory("TEST");

      it("should create reducer", () => {
      expect(factory).not.toBe(null);
      });

      it("should start fetching", () => {
      expect(factory({}, { type: "FETCH_TEST_STARTED" })).toEqual({
      data: null,
      isLoading: true,
      error: null
      });
      });

      it("should end fetching with success", () => {
      expect(
      factory({}, { type: "FETCH_TEST_SUCCESS", payload: "success" })
      ).toEqual({
      data: "success",
      isLoading: false,
      error: null
      });
      });

      it("should end fetching with error", () => {
      expect(
      factory({}, { type: "FETCH_TEST_ERROR", payload: "error" })
      ).toEqual({
      data: null,
      isLoading: false,
      error: "error"
      });
      });

      it("should return default state", () => {
      expect(factory({}, { type: "DIFFERENT" })).toEqual({});
      });
      });


      I would really appreciate, if you could let me know:




      1. if i'm using flow correctly?

      2. if my tests are reliable?

      3. how could i make it more generic?







      javascript unit-testing react.js






      share|improve this question













      share|improve this question











      share|improve this question




      share|improve this question










      asked Aug 3 at 15:52









      Dan Zawadzki

      112




      112





      bumped to the homepage by Community 16 hours ago


      This question has answers that may be good or bad; the system has marked it active so that they can be reviewed.







      bumped to the homepage by Community 16 hours ago


      This question has answers that may be good or bad; the system has marked it active so that they can be reviewed.
























          1 Answer
          1






          active

          oldest

          votes

















          up vote
          0
          down vote













          I have very minimal flow experience, but the action definition looks right. You may also be able to define a state type for this reducer.



          It's pretty generic right now, so I'm not sure I would push it much more. Maybe it should be called fetchReducerFactory, just to keep the terminology consistent.



          The tests look good. By "reliable", you probably mean "good." They are readable and look to provide good coverage for the code and branches.




          • You may want to test that the default state is correct.

          • You may want to test that unknown actions do nothing to the state.




          NOTE: The following comment is pretty minor, but wanted to bring it up. The way the code is structured, the tests make sense. But there are implicit cases that work because of the code structure. Let me explain:



          You expect FETCH_TEST_SUCCESS to do 3 things: (1) clear the isLoading flag (2) set data to the payload, and (3) set error to null. These three behaviors are wrapped together in one test. And, the only data that is actually changed by the reducer in this test is the data property; isLoading and error are not changed. So, for this test, you could make sure all values are changed by passing in a different state:



          expect(
          factory({ data: null, isLoading: true, error: 3 },
          { type: "FETCH_TEST_SUCCESS", payload: "success" })
          ).toEqual({
          data: "success",
          isLoading: false,
          error: null
          });


          This will guard against code changes later where someone refactors. Or, you could just have three small tests, each that test single property mutations. Again, small potatoes.






          share|improve this answer





















            Your Answer





            StackExchange.ifUsing("editor", function () {
            return StackExchange.using("mathjaxEditing", function () {
            StackExchange.MarkdownEditor.creationCallbacks.add(function (editor, postfix) {
            StackExchange.mathjaxEditing.prepareWmdForMathJax(editor, postfix, [["\$", "\$"]]);
            });
            });
            }, "mathjax-editing");

            StackExchange.ifUsing("editor", function () {
            StackExchange.using("externalEditor", function () {
            StackExchange.using("snippets", function () {
            StackExchange.snippets.init();
            });
            });
            }, "code-snippets");

            StackExchange.ready(function() {
            var channelOptions = {
            tags: "".split(" "),
            id: "196"
            };
            initTagRenderer("".split(" "), "".split(" "), channelOptions);

            StackExchange.using("externalEditor", function() {
            // Have to fire editor after snippets, if snippets enabled
            if (StackExchange.settings.snippets.snippetsEnabled) {
            StackExchange.using("snippets", function() {
            createEditor();
            });
            }
            else {
            createEditor();
            }
            });

            function createEditor() {
            StackExchange.prepareEditor({
            heartbeatType: 'answer',
            convertImagesToLinks: false,
            noModals: true,
            showLowRepImageUploadWarning: true,
            reputationToPostImages: null,
            bindNavPrevention: true,
            postfix: "",
            imageUploader: {
            brandingHtml: "Powered by u003ca class="icon-imgur-white" href="https://imgur.com/"u003eu003c/au003e",
            contentPolicyHtml: "User contributions licensed under u003ca href="https://creativecommons.org/licenses/by-sa/3.0/"u003ecc by-sa 3.0 with attribution requiredu003c/au003e u003ca href="https://stackoverflow.com/legal/content-policy"u003e(content policy)u003c/au003e",
            allowUrls: true
            },
            onDemand: true,
            discardSelector: ".discard-answer"
            ,immediatelyShowMarkdownHelp:true
            });


            }
            });














            draft saved

            draft discarded


















            StackExchange.ready(
            function () {
            StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fcodereview.stackexchange.com%2fquestions%2f200912%2ftesting-higher-order-reducer-with-jest%23new-answer', 'question_page');
            }
            );

            Post as a guest















            Required, but never shown

























            1 Answer
            1






            active

            oldest

            votes








            1 Answer
            1






            active

            oldest

            votes









            active

            oldest

            votes






            active

            oldest

            votes








            up vote
            0
            down vote













            I have very minimal flow experience, but the action definition looks right. You may also be able to define a state type for this reducer.



            It's pretty generic right now, so I'm not sure I would push it much more. Maybe it should be called fetchReducerFactory, just to keep the terminology consistent.



            The tests look good. By "reliable", you probably mean "good." They are readable and look to provide good coverage for the code and branches.




            • You may want to test that the default state is correct.

            • You may want to test that unknown actions do nothing to the state.




            NOTE: The following comment is pretty minor, but wanted to bring it up. The way the code is structured, the tests make sense. But there are implicit cases that work because of the code structure. Let me explain:



            You expect FETCH_TEST_SUCCESS to do 3 things: (1) clear the isLoading flag (2) set data to the payload, and (3) set error to null. These three behaviors are wrapped together in one test. And, the only data that is actually changed by the reducer in this test is the data property; isLoading and error are not changed. So, for this test, you could make sure all values are changed by passing in a different state:



            expect(
            factory({ data: null, isLoading: true, error: 3 },
            { type: "FETCH_TEST_SUCCESS", payload: "success" })
            ).toEqual({
            data: "success",
            isLoading: false,
            error: null
            });


            This will guard against code changes later where someone refactors. Or, you could just have three small tests, each that test single property mutations. Again, small potatoes.






            share|improve this answer

























              up vote
              0
              down vote













              I have very minimal flow experience, but the action definition looks right. You may also be able to define a state type for this reducer.



              It's pretty generic right now, so I'm not sure I would push it much more. Maybe it should be called fetchReducerFactory, just to keep the terminology consistent.



              The tests look good. By "reliable", you probably mean "good." They are readable and look to provide good coverage for the code and branches.




              • You may want to test that the default state is correct.

              • You may want to test that unknown actions do nothing to the state.




              NOTE: The following comment is pretty minor, but wanted to bring it up. The way the code is structured, the tests make sense. But there are implicit cases that work because of the code structure. Let me explain:



              You expect FETCH_TEST_SUCCESS to do 3 things: (1) clear the isLoading flag (2) set data to the payload, and (3) set error to null. These three behaviors are wrapped together in one test. And, the only data that is actually changed by the reducer in this test is the data property; isLoading and error are not changed. So, for this test, you could make sure all values are changed by passing in a different state:



              expect(
              factory({ data: null, isLoading: true, error: 3 },
              { type: "FETCH_TEST_SUCCESS", payload: "success" })
              ).toEqual({
              data: "success",
              isLoading: false,
              error: null
              });


              This will guard against code changes later where someone refactors. Or, you could just have three small tests, each that test single property mutations. Again, small potatoes.






              share|improve this answer























                up vote
                0
                down vote










                up vote
                0
                down vote









                I have very minimal flow experience, but the action definition looks right. You may also be able to define a state type for this reducer.



                It's pretty generic right now, so I'm not sure I would push it much more. Maybe it should be called fetchReducerFactory, just to keep the terminology consistent.



                The tests look good. By "reliable", you probably mean "good." They are readable and look to provide good coverage for the code and branches.




                • You may want to test that the default state is correct.

                • You may want to test that unknown actions do nothing to the state.




                NOTE: The following comment is pretty minor, but wanted to bring it up. The way the code is structured, the tests make sense. But there are implicit cases that work because of the code structure. Let me explain:



                You expect FETCH_TEST_SUCCESS to do 3 things: (1) clear the isLoading flag (2) set data to the payload, and (3) set error to null. These three behaviors are wrapped together in one test. And, the only data that is actually changed by the reducer in this test is the data property; isLoading and error are not changed. So, for this test, you could make sure all values are changed by passing in a different state:



                expect(
                factory({ data: null, isLoading: true, error: 3 },
                { type: "FETCH_TEST_SUCCESS", payload: "success" })
                ).toEqual({
                data: "success",
                isLoading: false,
                error: null
                });


                This will guard against code changes later where someone refactors. Or, you could just have three small tests, each that test single property mutations. Again, small potatoes.






                share|improve this answer












                I have very minimal flow experience, but the action definition looks right. You may also be able to define a state type for this reducer.



                It's pretty generic right now, so I'm not sure I would push it much more. Maybe it should be called fetchReducerFactory, just to keep the terminology consistent.



                The tests look good. By "reliable", you probably mean "good." They are readable and look to provide good coverage for the code and branches.




                • You may want to test that the default state is correct.

                • You may want to test that unknown actions do nothing to the state.




                NOTE: The following comment is pretty minor, but wanted to bring it up. The way the code is structured, the tests make sense. But there are implicit cases that work because of the code structure. Let me explain:



                You expect FETCH_TEST_SUCCESS to do 3 things: (1) clear the isLoading flag (2) set data to the payload, and (3) set error to null. These three behaviors are wrapped together in one test. And, the only data that is actually changed by the reducer in this test is the data property; isLoading and error are not changed. So, for this test, you could make sure all values are changed by passing in a different state:



                expect(
                factory({ data: null, isLoading: true, error: 3 },
                { type: "FETCH_TEST_SUCCESS", payload: "success" })
                ).toEqual({
                data: "success",
                isLoading: false,
                error: null
                });


                This will guard against code changes later where someone refactors. Or, you could just have three small tests, each that test single property mutations. Again, small potatoes.







                share|improve this answer












                share|improve this answer



                share|improve this answer










                answered Aug 13 at 2:47









                ndp

                1,08676




                1,08676






























                    draft saved

                    draft discarded




















































                    Thanks for contributing an answer to Code Review Stack Exchange!


                    • Please be sure to answer the question. Provide details and share your research!

                    But avoid



                    • Asking for help, clarification, or responding to other answers.

                    • Making statements based on opinion; back them up with references or personal experience.


                    Use MathJax to format equations. MathJax reference.


                    To learn more, see our tips on writing great answers.





                    Some of your past answers have not been well-received, and you're in danger of being blocked from answering.


                    Please pay close attention to the following guidance:


                    • Please be sure to answer the question. Provide details and share your research!

                    But avoid



                    • Asking for help, clarification, or responding to other answers.

                    • Making statements based on opinion; back them up with references or personal experience.


                    To learn more, see our tips on writing great answers.




                    draft saved


                    draft discarded














                    StackExchange.ready(
                    function () {
                    StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fcodereview.stackexchange.com%2fquestions%2f200912%2ftesting-higher-order-reducer-with-jest%23new-answer', 'question_page');
                    }
                    );

                    Post as a guest















                    Required, but never shown





















































                    Required, but never shown














                    Required, but never shown












                    Required, but never shown







                    Required, but never shown

































                    Required, but never shown














                    Required, but never shown












                    Required, but never shown







                    Required, but never shown







                    Popular posts from this blog

                    Ellipse (mathématiques)

                    Quarter-circle Tiles

                    Mont Emei