How can I set window to undefined in order to test the SSR rendering in an isomorphic application?





.everyoneloves__top-leaderboard:empty,.everyoneloves__mid-leaderboard:empty,.everyoneloves__bot-mid-leaderboard:empty{ height:90px;width:728px;box-sizing:border-box;
}







0















I have been trying to test an else block for when window is undefined.
As I'm using Next.js the window will be undefined during server side rendering (SSR). At present I can not find a way to do this.



Any help is much appreciated.



I have tried setting window = undefined and global.window = undefined in the test and within the definition before function (both all and each options). Both approaches have not been successful.



When Googling the closest answer I can find is mocking or spying on a window method but this doesn't answer my problem. I have also found people noting you can run the test as a Node application (thus SSR) but not sure how this can be done for one test.



I have provided an example below of what I am trying to test and how.



Function to Test



export default () => {
console.log(typeof window); // This is always an object and never undefined
const language =
typeof window !== 'undefined'
? window.navigator.userLanguage || window.navigator.language || 'en'
: 'en';

return language;
};


Jest Test



import getLanguage = './getLanguage';

describe('Get Language SSR', () => {
const realWindow = window;

beforeAll(() => {
window = undefined;
});

afterAll(() => {
window = realWindow;
});

it('should return "en"', () => {
expect(getLanguage()).toEqual('en');
})
});


The code coverage shows that the else block is never hit.










share|improve this question































    0















    I have been trying to test an else block for when window is undefined.
    As I'm using Next.js the window will be undefined during server side rendering (SSR). At present I can not find a way to do this.



    Any help is much appreciated.



    I have tried setting window = undefined and global.window = undefined in the test and within the definition before function (both all and each options). Both approaches have not been successful.



    When Googling the closest answer I can find is mocking or spying on a window method but this doesn't answer my problem. I have also found people noting you can run the test as a Node application (thus SSR) but not sure how this can be done for one test.



    I have provided an example below of what I am trying to test and how.



    Function to Test



    export default () => {
    console.log(typeof window); // This is always an object and never undefined
    const language =
    typeof window !== 'undefined'
    ? window.navigator.userLanguage || window.navigator.language || 'en'
    : 'en';

    return language;
    };


    Jest Test



    import getLanguage = './getLanguage';

    describe('Get Language SSR', () => {
    const realWindow = window;

    beforeAll(() => {
    window = undefined;
    });

    afterAll(() => {
    window = realWindow;
    });

    it('should return "en"', () => {
    expect(getLanguage()).toEqual('en');
    })
    });


    The code coverage shows that the else block is never hit.










    share|improve this question



























      0












      0








      0








      I have been trying to test an else block for when window is undefined.
      As I'm using Next.js the window will be undefined during server side rendering (SSR). At present I can not find a way to do this.



      Any help is much appreciated.



      I have tried setting window = undefined and global.window = undefined in the test and within the definition before function (both all and each options). Both approaches have not been successful.



      When Googling the closest answer I can find is mocking or spying on a window method but this doesn't answer my problem. I have also found people noting you can run the test as a Node application (thus SSR) but not sure how this can be done for one test.



      I have provided an example below of what I am trying to test and how.



      Function to Test



      export default () => {
      console.log(typeof window); // This is always an object and never undefined
      const language =
      typeof window !== 'undefined'
      ? window.navigator.userLanguage || window.navigator.language || 'en'
      : 'en';

      return language;
      };


      Jest Test



      import getLanguage = './getLanguage';

      describe('Get Language SSR', () => {
      const realWindow = window;

      beforeAll(() => {
      window = undefined;
      });

      afterAll(() => {
      window = realWindow;
      });

      it('should return "en"', () => {
      expect(getLanguage()).toEqual('en');
      })
      });


      The code coverage shows that the else block is never hit.










      share|improve this question
















      I have been trying to test an else block for when window is undefined.
      As I'm using Next.js the window will be undefined during server side rendering (SSR). At present I can not find a way to do this.



      Any help is much appreciated.



      I have tried setting window = undefined and global.window = undefined in the test and within the definition before function (both all and each options). Both approaches have not been successful.



      When Googling the closest answer I can find is mocking or spying on a window method but this doesn't answer my problem. I have also found people noting you can run the test as a Node application (thus SSR) but not sure how this can be done for one test.



      I have provided an example below of what I am trying to test and how.



      Function to Test



      export default () => {
      console.log(typeof window); // This is always an object and never undefined
      const language =
      typeof window !== 'undefined'
      ? window.navigator.userLanguage || window.navigator.language || 'en'
      : 'en';

      return language;
      };


      Jest Test



      import getLanguage = './getLanguage';

      describe('Get Language SSR', () => {
      const realWindow = window;

      beforeAll(() => {
      window = undefined;
      });

      afterAll(() => {
      window = realWindow;
      });

      it('should return "en"', () => {
      expect(getLanguage()).toEqual('en');
      })
      });


      The code coverage shows that the else block is never hit.







      javascript jestjs isomorphic-javascript






      share|improve this question















      share|improve this question













      share|improve this question




      share|improve this question








      edited Jan 4 at 14:45









      LazerBass

      1,54531126




      1,54531126










      asked Jan 4 at 11:55









      tomevans18tomevans18

      164




      164
























          1 Answer
          1






          active

          oldest

          votes


















          1














          "By adding a @jest-environment docblock at the top of the file, you can specify another environment to be used for all tests in that file":



          /**
          * @jest-environment node
          */

          import getLanguage from './getLanguage';

          describe('Get Language SSR', () => {

          it('should return "en"', () => {
          expect(getLanguage()).toEqual('en'); // SUCCESS
          })

          });


          The @jest-environment docblock will set the test environment for this test file to node causing window to be undefined and resulting in the test passing.






          share|improve this answer
























            Your Answer






            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: "1"
            };
            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: true,
            noModals: true,
            showLowRepImageUploadWarning: true,
            reputationToPostImages: 10,
            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%2fstackoverflow.com%2fquestions%2f54038514%2fhow-can-i-set-window-to-undefined-in-order-to-test-the-ssr-rendering-in-an-isomo%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









            1














            "By adding a @jest-environment docblock at the top of the file, you can specify another environment to be used for all tests in that file":



            /**
            * @jest-environment node
            */

            import getLanguage from './getLanguage';

            describe('Get Language SSR', () => {

            it('should return "en"', () => {
            expect(getLanguage()).toEqual('en'); // SUCCESS
            })

            });


            The @jest-environment docblock will set the test environment for this test file to node causing window to be undefined and resulting in the test passing.






            share|improve this answer




























              1














              "By adding a @jest-environment docblock at the top of the file, you can specify another environment to be used for all tests in that file":



              /**
              * @jest-environment node
              */

              import getLanguage from './getLanguage';

              describe('Get Language SSR', () => {

              it('should return "en"', () => {
              expect(getLanguage()).toEqual('en'); // SUCCESS
              })

              });


              The @jest-environment docblock will set the test environment for this test file to node causing window to be undefined and resulting in the test passing.






              share|improve this answer


























                1












                1








                1







                "By adding a @jest-environment docblock at the top of the file, you can specify another environment to be used for all tests in that file":



                /**
                * @jest-environment node
                */

                import getLanguage from './getLanguage';

                describe('Get Language SSR', () => {

                it('should return "en"', () => {
                expect(getLanguage()).toEqual('en'); // SUCCESS
                })

                });


                The @jest-environment docblock will set the test environment for this test file to node causing window to be undefined and resulting in the test passing.






                share|improve this answer













                "By adding a @jest-environment docblock at the top of the file, you can specify another environment to be used for all tests in that file":



                /**
                * @jest-environment node
                */

                import getLanguage from './getLanguage';

                describe('Get Language SSR', () => {

                it('should return "en"', () => {
                expect(getLanguage()).toEqual('en'); // SUCCESS
                })

                });


                The @jest-environment docblock will set the test environment for this test file to node causing window to be undefined and resulting in the test passing.







                share|improve this answer












                share|improve this answer



                share|improve this answer










                answered Jan 7 at 2:02









                brian-lives-outdoorsbrian-lives-outdoors

                11.6k1930




                11.6k1930
































                    draft saved

                    draft discarded




















































                    Thanks for contributing an answer to Stack Overflow!


                    • 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%2fstackoverflow.com%2fquestions%2f54038514%2fhow-can-i-set-window-to-undefined-in-order-to-test-the-ssr-rendering-in-an-isomo%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

                    Monofisismo

                    Angular Downloading a file using contenturl with Basic Authentication

                    Olmecas