title: How can I set window to undefined in order to test the SSR rendering in an isomorphic application?
body: <p>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.</p>
  
  <p>Any help is much appreciated.</p>
  
  <p>I have tried setting <code>window = undefined</code> and <code>global.window = undefined</code> in the test and within the definition before function (both all and each options). Both approaches have not been successful.</p>
  
  <p>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.</p>
  
  <p>I have provided an example below of what I am trying to test and how.</p>
  
  <p><strong>Function to Test</strong></p>
  
  <pre><code>export default () =&gt; {
     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;
  };
  </code></pre>
  
  <p><strong>Jest Test</strong></p>
  
  <pre><code>import getLanguage = './getLanguage';
  
  describe('Get Language SSR', () =&gt; {
      const realWindow = window;
  
      beforeAll(() =&gt; {
          window = undefined;
      });
  
      afterAll(() =&gt; {
          window = realWindow;
      });
  
      it('should return "en"', () =&gt; {
           expect(getLanguage()).toEqual('en');
      })
  });
  </code></pre>
  
  <p>The code coverage shows that the else block is never hit. </p>