Testing higher order reducer with jest The 2019 Stack Overflow Developer Survey Results Are...

Manuscript was "unsubmitted" because the manuscript was deposited in Arxiv Preprints

Is flight data recorder erased after every flight?

Inflated grade on resume at previous job, might former employer tell new employer?

Where does the "burst of radiance" from Holy Weapon originate?

Patience, young "Padovan"

Limit the amount of RAM Mathematica may access?

The difference between dialogue marks

What does "rabbited" mean/imply in this sentence?

Which Sci-Fi work first showed weapon of galactic-scale mass destruction?

Inversion Puzzle

Geography at the pixel level

What is this 4-propeller plane?

Are there any other methods to apply to solving simultaneous equations?

"To split hairs" vs "To be pedantic"

What is the use of option -o in the useradd command?

Realistic Alternatives to Dust: What Else Could Feed a Plankton Bloom?

Is this food a bread or a loaf?

Idiomatic way to prevent slicing?

Landlord wants to switch my lease to a "Land contract" to "get back at the city"

How to reverse every other sublist of a list?

Why don't Unix/Linux systems traverse through directories until they find the required version of a linked library?

Inline version of a function returns different value than non-inline version

Why can Shazam do this?

What do the Banks children have against barley water?



Testing higher order reducer with jest



The 2019 Stack Overflow Developer Survey Results Are InTesting a mixin functionPassing functions using higher order components in ReactTest if a string is a palindromeLocale language reducerHigher order component for verifying authenticationSupport static typing / analysis with dependency injectionSuppress console output from React in Jest testing output but not in browser outputRedux reducer with a filterReact higher-order component: withHigherHandlersReact - Higher Order Component





.everyoneloves__top-leaderboard:empty,.everyoneloves__mid-leaderboard:empty,.everyoneloves__bot-mid-leaderboard:empty{ margin-bottom:0;
}







2












$begingroup$


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









$endgroup$




bumped to the homepage by Community 44 secs ago


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






















    2












    $begingroup$


    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









    $endgroup$




    bumped to the homepage by Community 44 secs ago


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


















      2












      2








      2





      $begingroup$


      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









      $endgroup$




      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 '18 at 15:52









      Dan ZawadzkiDan Zawadzki

      162




      162





      bumped to the homepage by Community 44 secs 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 44 secs 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


















          0












          $begingroup$

          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









          $endgroup$














            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',
            autoActivateHeartbeat: false,
            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









            0












            $begingroup$

            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









            $endgroup$


















              0












              $begingroup$

              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









              $endgroup$
















                0












                0








                0





                $begingroup$

                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









                $endgroup$



                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 '18 at 2:47









                ndpndp

                1,21686




                1,21686






























                    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.




                    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

                    Fairchild Swearingen Metro Inhaltsverzeichnis Geschichte | Innenausstattung | Nutzung | Zwischenfälle...

                    Pilgersdorf Inhaltsverzeichnis Geografie | Geschichte | Bevölkerungsentwicklung | Politik | Kultur...

                    Marineschifffahrtleitung Inhaltsverzeichnis Geschichte | Heutige Organisation der NATO | Nationale und...