title: Mocking require statements with Jest
body: <p>sum.js</p>
  
  <pre><code>module.exports = function sum(a, b){
      return a + b;
  };
  </code></pre>
  
  <p>Thing.js</p>
  
  <pre><code>var sum = require("./sum");
  
  module.exports = class Thing {
      add(a, b){
          return sum(a, b);
      }
  }
  </code></pre>
  
  <p>Thing.test.js</p>
  
  <pre><code>test('1 + 2 = 3', () =&gt; {
      //Arrange
      var Thing = require('./Thing');
      var thing = new Thing();
  
      //Act
      var result = thing.add(1, 2);
  
      //Assert
      expect(result).toBe(3);
  });
  
  test('sum mocked', () =&gt; {
      //Arrange
      jest.mock('./sum', () =&gt; {
          return jest.fn(() =&gt; 42);
      });
  
      var Thing = require('./Thing');
      var thing = new Thing();
  
      //Act
      var result = thing.add(1, 2);
  
      //Assert
      expect(result).toBe(42);
  });
  </code></pre>
  
  <p>How can I mock the sum 'require' dependency when testing? I get the following error.</p>
  
  <pre><code>sum mocked
  
      expect(received).toBe(expected)
  
      Expected value to be (using ===):
        42
      Received:
        3
  </code></pre>
  
  <p>What's interesting if I run each test individually with .only, they both work just fine on their own.</p>
  
  <p>In the past I've used proxyquire to do things like this but I'd like to avoid it if possible.</p>