title: Mocking globals in Jest
body: <p>Is there any way in Jest to mock global objects, such as <code>navigator</code>, or <code>Image</code>*? I've pretty much given up on this, and left it up to a series of mockable utility methods. For example:</p>
  
  <pre><code>// Utils.js
  export isOnline() {
      return navigator.onLine;
  }
  </code></pre>
  
  <p>Testing this tiny function is simple, but crufty and not deterministic at all. I can get 75% of the way there, but this is about as far as I can go:</p>
  
  <pre><code>// Utils.test.js
  it('knows if it is online', () =&gt; {
      const { isOnline } = require('path/to/Utils');
  
      expect(() =&gt; isOnline()).not.toThrow();
      expect(typeof isOnline()).toBe('boolean');
  });
  </code></pre>
  
  <p>On the other hand, if I am okay with this indirection, I can now access <code>navigator</code> via these utilities:</p>
  
  <pre><code>// Foo.js
  import { isOnline } from './Utils';
  
  export default class Foo {
      doSomethingOnline() {
          if (!isOnline()) throw new Error('Not online');
  
          /* More implementation */            
      }
  }
  </code></pre>
  
  <p>...and deterministically test like this...</p>
  
  <pre><code>// Foo.test.js
  it('throws when offline', () =&gt; {
      const Utils = require('../services/Utils');
      Utils.isOnline = jest.fn(() =&gt; isOnline);
  
      const Foo = require('../path/to/Foo').default;
      let foo = new Foo();
  
      // User is offline -- should fail
      let isOnline = false;
      expect(() =&gt; foo.doSomethingOnline()).toThrow();
  
      // User is online -- should be okay
      isOnline = true;
      expect(() =&gt; foo.doSomethingOnline()).not.toThrow();
  });
  </code></pre>
  
  <p>Out of all the testing frameworks I've used, Jest feels like the most complete solution, but any time I write awkward code just to make it testable, I feel like my testing tools are letting me down.</p>
  
  <p>Is this the only solution or do I need to add Rewire?</p>
  
  <p>*Don't smirk. <code>Image</code> is fantastic for pinging a remote network resource.</p>