title: How to mock navigator mediaDevices for Jest
body: <p>I have a test that needs to use <code>navigator.mediaDevices</code> but I cannot get any mocks to work correctly.</p>
  <p>I am using <code>create-react-app</code>.</p>
  <p>Here is my test:</p>
  <pre><code>import getConnectedDevices from &quot;./getConnectedDevices&quot;;
  
  describe(&quot;getConnectedDevices&quot;, () =&gt; {
    it(&quot;Should work&quot;, () =&gt; {
      console.log(navigator);              // Navigator {}
      console.log(navigator.mediaDevices); // undefined
    });
  });
  </code></pre>
  <p>I have tried adding a mock as it states <a href="https://jestjs.io/docs/en/manual-mocks#mocking-methods-which-are-not-implemented-in-jsdom" rel="noreferrer">here in the jest documentation</a></p>
  <pre class="lang-js prettyprint-override"><code>// tests/navigator.mock
  Object.defineProperty(window, &quot;navigator&quot;, {
    writable: true,
    value: {
      mediaDevices: {
        enumerateDevices: jest.fn(),
      },
    },
  });
  
  </code></pre>
  <pre><code>import &quot;../../tests/navigator.mock&quot;; // &lt;- Mock added
  
  import getConnectedDevices from &quot;./getConnectedDevices&quot;;
  
  describe(&quot;getConnectedDevices&quot;, () =&gt; {
    it(&quot;Should work&quot;, () =&gt; {
      console.log(navigator);              // Navigator {}
      console.log(navigator.mediaDevices); // undefined
    });
  });
  </code></pre>
  <p>I have also tried <a href="https://create-react-app.dev/docs/running-tests/#initializing-test-environment" rel="noreferrer">Initializing the test environment</a> according to the create-react-app docs.</p>
  <pre><code>// src/setupTests.ts
  
  // jest-dom adds custom jest matchers for asserting on DOM nodes.
  // allows you to do things like:
  // expect(element).toHaveTextContent(/react/i)
  // learn more: https://github.com/testing-library/jest-dom
  import &quot;@testing-library/jest-dom&quot;;
  
  const navigatorMock = {
    mediaDevices: {
      enumerateDevices: jest.fn(),
    },
  };
  
  global.navigator = navigatorMock;
  </code></pre>
  <p>What am I doing wrong?</p>