title: Mocking ApolloClient's client.query method with Jest
body: <h3>Update January 22nd 2020</h3>
  
  <p>The solution from @slideshowp2 is correct, but I could not get it to work at all, due to this TypeError:</p>
  
  <blockquote>
    <p>TypeError: Cannot read property 'query' of undefined</p>
  </blockquote>
  
  <p>Well it turned out to be my jest configuration that had <code>resetMocks: true</code> set. After I removed it, the test did pass. (I don't know why though)</p>
  
  <hr>
  
  <h2>Original question:</h2>
  
  <p>I need to execute a graphql query in a helper function outside of a React component using Apollo Client and after a bit of trial and error I went for this approach which is working as it is supposed to:</p>
  
  <p>setup.ts</p>
  
  <pre class="lang-js prettyprint-override"><code>export const setupApi = (): ApolloClient&lt;any&gt; =&gt; {
    setupServiceApi(API_CONFIG)
    return createServiceApolloClient({ uri: `${API_HOST}${API_PATH}` })
  }
  </code></pre>
  
  <p>getAssetIdFromService.ts</p>
  
  <pre class="lang-js prettyprint-override"><code>import { setupApi } from '../api/setup'
  
  const client = setupApi()
  
  export const GET_ASSET_ID = gql`
    query getAssetByExternalId($externalId: String!) {
      assetId: getAssetId(externalId: $externalId) {
        id
      }
    }
  `
  
  export const getAssetIdFromService = async (externalId: string) =&gt; {
    return await client.query({
      query: GET_ASSET_ID,
      variables: { externalId },
    })
  
    return { data, errors, loading }
  }
  </code></pre>
  
  <p>Now I am trying to write test tests for the <code>getAssetIdFromService</code> function, but I have trouble figuring out how to get the <code>client.query</code> method to work in tests.</p>
  
  <p>I have tried the approach below including many others that did not work.
  For this particular setup, jest throws </p>
  
  <blockquote>
    <p>TypeError: client.query is not a function</p>
  </blockquote>
  
  <pre class="lang-js prettyprint-override"><code>import { setupApi } from '../../api/setup'
  import { getAssetIdFromService } from '../getAssetIdFromService'
  
  jest.mock('../../api/setup', () =&gt; ({
    setupApi: () =&gt; jest.fn(),
  }))
  
  describe('getAssetIdFromService', () =&gt; {
    it('returns an assetId when passed an externalId and the asset exists in the service', async () =&gt; {
      const { data, errors, loading } = await getAssetIdFromService('e1')
  
      // Do assertions  
    })
  }
  </code></pre>
  
  <p>I assume I am missing something in relation to this part:</p>
  
  <pre><code>jest.mock('../../api/setup', () =&gt; ({
    setupApi: () =&gt; jest.fn(),
  }))
  </code></pre>
  
  <p>...but I cannot see it.</p>