title: How to use doMock in jest?
body: <p>I find that when using <code>jest.doMock</code> instead of <code>jest.mock</code> to mock a function (I will need to create multiple mock implementations for the same function in different <code>it</code> blocks), I find that the test fails with</p>
  
  <p><strong>Error</strong> </p>
  
  <pre><code>expect(jest.fn()).toBeCalled()
  
  Expected mock function to have been called.
  </code></pre>
  
  <p>Also, if I require the module at the top of the test instead of doing it within the same it block, it gives me a different error:</p>
  
  <pre><code>expect(jest.fn())[.not].toBeCalled()
  
  jest.fn() value must be a mock function or spy.
  Received:
    function: [Function headObject]
  </code></pre>
  
  <p><strong>Code</strong></p>
  
  <ol>
  <li><p>headObject(Collaborator being mocked)</p>
  
  <pre><code>// NOT IMPLEMENTED YET
  module.exports = function() {}
  </code></pre></li>
  <li><p>Test code</p>
  
  <pre><code>it('checks to see if a resource exists when given a threshold', () =&gt; {
    jest.doMock('../s3/headObject', () =&gt; {
      return jest.fn(() =&gt; {})
    })
    const headObject = require('../s3/headObject')
    handler(event.correct_uses_propertyId_withExplicitThreshold, {}, () =&gt; {})
    expect(headObject).toBeCalled()
  })
  </code></pre></li>
  <li><p><strong>Source Code</strong></p>
  
  <pre><code>const headObject  = require('../s3/headObject')
    module.exports = async function(event, context, callback) {
     headObject()
  }
  </code></pre></li>
  </ol>
  
  <p><strong>Previously</strong> </p>
  
  <p>I used environment variables to change the mock implementation using mocks within <code>__mocks__</code> like this:</p>
  
  <pre><code>const result = jest.genMockFromModule('../realModule.js')
  const mockResponse = require('../../eventMocks/realModuleName/fixture.json')
  
  function mock (bearerToken, address) {
    if (process.env.DONT_USE_TEST_ONLY_EMPTY_ESTIMATE) {
      return {
        history: []
      }
    }
    return mockResponse
  }
  
  result.mockImplementation(mock)
  
  module.exports = result
  </code></pre>
  
  <p>and in my test, I would:</p>
  
  <pre><code>it('does not store empty results in S3', () =&gt; {
    process.env.DONT_USE_TEST_ONLY_EMPTY_ESTIMATE = true
    const res = LambdaTester(handler)
    .event(event.correct_uses_address)
    .expectResult(r =&gt; {
      expect(r.statusCode).toEqual(404)
      const body = JSON.parse(r.body)
      expect(body.message).toEqual(NO_ESTIMATE)
    })
  
    process.env.DONT_USE_TEST_ONLY_EMPTY_ESTIMATE = false
    return res
  })
  </code></pre>