title: How can I mock an ES6 module import using Jest?
body: <p>I want to test that one of my <a href="https://en.wikipedia.org/wiki/ECMAScript#6th_Edition_%E2%80%93_ECMAScript_2015" rel="noreferrer">ES6</a> modules calls another ES6 module in a particular way. With <a href="https://en.wikipedia.org/wiki/Jasmine_(JavaScript_testing_framework)" rel="noreferrer">Jasmine</a> this is super easy --</p>
  <p>The application code:</p>
  <pre><code>// myModule.js
  import dependency from './dependency';
  
  export default (x) =&gt; {
    dependency.doSomething(x * 2);
  }
  </code></pre>
  <p>And the test code:</p>
  <pre><code>//myModule-test.js
  import myModule from '../myModule';
  import dependency from '../dependency';
  
  describe('myModule', () =&gt; {
    it('calls the dependency with double the input', () =&gt; {
      spyOn(dependency, 'doSomething');
  
      myModule(2);
  
      expect(dependency.doSomething).toHaveBeenCalledWith(4);
    });
  });
  </code></pre>
  <p>What's the equivalent with Jest? I feel like this is such a simple thing to want to do, but I've been tearing my hair out trying to figure it out.</p>
  <p>The closest I've come is by replacing the <code>import</code>s with <code>require</code>s, and moving them inside the tests/functions. Neither of which are things I want to do.</p>
  <pre><code>// myModule.js
  export default (x) =&gt; {
    const dependency = require('./dependency'); // Yuck
    dependency.doSomething(x * 2);
  }
  
  //myModule-test.js
  describe('myModule', () =&gt; {
    it('calls the dependency with double the input', () =&gt; {
      jest.mock('../dependency');
  
      myModule(2);
  
      const dependency = require('../dependency'); // Also yuck
      expect(dependency.doSomething).toBeCalledWith(4);
    });
  });
  </code></pre>
  <p>For bonus points, I'd love to make the whole thing work when the function inside <code>dependency.js</code> is a default export. However, I know that spying on default exports doesn't work in Jasmine (or at least I could never get it to work), so I'm not holding out hope that it's possible in Jest either.</p>