title: Reuse Jest module mocks across tests
body: <p>I want to mock a module for a test. Everything works, but I have to copy/paste the same code into every test file. How can I make this more maintainable?</p>
  <p><em>(This is using Babel and TypeScript in a Next.js project.)</em></p>
  <p>The production code looks like this:</p>
  <pre><code>import { useRouter } from 'next/router';
  
  // Then call the hook in a React component:
    const router = useRouter();
  </code></pre>
  <p>The test code:</p>
  <pre><code>// I need to access these mocks in the tests
  const mockRouterPush = jest.fn();
  const mockRouterBack = jest.fn();
  
  jest.mock('next/router', () =&gt; ({
    useRouter: () =&gt; ({
      push: mockRouterPush,
      query: { segment: 'seg1' },
      back: mockRouterBack,
    }),
  }));
  </code></pre>
  <p>This works fine. The module and its hook are mocked for the test file, and I can refer to the mocks in the tests. The issue is that it's difficult to maintain across multiple test files.</p>
  <p>Calls to <a href="https://jestjs.io/docs/es6-class-mocks#calling-jestmock-with-the-module-factory-parameter" rel="nofollow noreferrer">jest.mock()</a> are hoisted to the top of the file, and can only refer to variables that start with the word 'mock'.</p>
  <p>With other mocks I've used <code>require</code> within the module factory instead of <code>import</code>; this works and reduces boilerplate, but (a) makes it more difficult for the tests to refer to the mocks and (b) my IDE (VSCode) won't auto-update require paths like it does with imports when I move files. For example:</p>
  <pre><code>jest.mock('react-i18next', () =&gt; {
    // Sometimes the path is '../../../testhelpers' etc.
    const { mockUseTranslation } = require('./testhelpers');
  
    return {
      useTranslation: mockUseTranslation,
    };
  });
  </code></pre>
  <p>I've tried <code>doMock</code> and <code>createMockFromModule</code> without success.</p>
  <p>How do other folks deal with this issue?</p>