title: How do I mock the Google Translate API within this code?
body: <p>What I'd like to achieve is any instance of Translation that gets <code>new</code>'ed up in my test is a Jest mock of that class.  I don't want to actually call the Google Translate API for a test case, just check that if I pass different known results back from the Google call, my code logically handles them as it should.</p>
  <p>I cannot figure out how to mock <code>Translate</code> and the functions that I use.</p>
  <p>The code below has littered in a variety of attempts to mock. I'll continue to try after I post this. Any guidance is most appreciated, but you don't need to say &quot;why you mock @google AND the <code>makeTranslationRequest</code> functions?&quot; below because they were two different attempts that I'm providing to show I've come at the problem from different angles.</p>
  <p>translation.js</p>
  <pre><code>...
  const { Translate } = require('@google-cloud/translate').v2
  ...
  
  const makeTranslationRequest = async (dialog, fromLocale, toLocale) =&gt; {
  ...
                  const translate = new Translate({ credentials: serviceKey })  // &lt;== MOCK THIS CLASS IN TEST
  ...
  
  module.exports = {
      getTranslation,
      makeTranslationRequest
  }
  </code></pre>
  <p>translation.test.js</p>
  <pre><code>const { before } = require('lodash')
  const translation = require('../../../../services/nlp/lib/translation')
  const { Translate } = require('@google-cloud/translate').v2  // &lt;=== ???
  
  jest.mock(('@google-cloud/translate').v2)  // &lt;=== ???  Jest docs say to mock the whole module
  
  beforeEach(() =&gt; {
      Translate.mockClear();  // &lt;== this errors out with &quot;mockClear not a function&quot; so I guess Jest didn't mock every instance of the class?  
  })
  
  describe('translation', () =&gt; {
  test('calls makeTranslationRequest if root language codes differ', async () =&gt; {
          process.env.APPLICATION_SETTINGS = JSON.stringify(require('../../../../config/settings.json'))
          
          translation.makeTranslationRequest = jest.fn().mockReturnValue('mock value');  // &lt;== tried this in one run, not working at all
  
          res = await translation.getTranslation(&quot;español&quot;, &quot;es-ES&quot;, &quot;en-US&quot;)
          expect(res).toEqual('Spanish')
      })
  })
  </code></pre>