title: How to mock variable responses based on the url when fetch(url) is called using the Jest testing framework?
body: <p>I have a module that looks like follows:</p>
  
  <blockquote>
    <p><strong>calculate-average.js</strong></p>
  
  <pre><code>const fetch = require('node-fetch')
  const stats = require('stats-lite')
  const BASE_URL = 'https://www.example.com/api'
  
  const calculateAverage = async(numApiCalls) =&gt; {
    const importantData = []
  
    for (let i = 0; i &lt; numApiCalls; i++) {
        const url = `${BASE_URL}/${i}` // will make requests to https://www.example.com/api/0, https://www.example.com/api/1 and so on....
        const res = await fetch(url)
        const jsonRes = await res.json()
  
        importantData.push(jsonRes.importantData)
    }
  
    return stats.mean(importantData)
  }
  
  module.exports = calculateAverage
  </code></pre>
  </blockquote>
  
  <p>I tried testing it along the following lines but I am clearly way off from the solution:</p>
  
  <blockquote>
    <p><strong>calculate-average.test.js</strong></p>
  
  <pre><code>const calculateAverage = require('../calculate-average')
  
  jest.mock(
      'node-fetch',
      () =&gt; {
          return jest.fn(() =&gt; {})
      }
  )
  
  test('Should calculate stats for liquidation open interest delatas', async() =&gt; {
      const stats = await calculateAverage(100) // Should make 100 API calls.
  
      console.log(stats)
  })
  </code></pre>
  </blockquote>
  
  <p>What I need to do is the following:</p>
  
  <ol>
  <li>Be able to specify custom varied responses for each API call. For example, I should be able to specify that a call to <code>https://www.example.com/api/0</code> returns <code>{ importantData: 0 }</code>, a call to <code>https://www.example.com/api/1</code> returns <code>{ importantData: 1 }</code> and so on...</li>
  <li>If a request is made to a <code>url</code> that I have not specified a response for, a default response is provided. For example if a response is made to <code>https://www.example.com/api/101</code>, then a default response of <code>{ importantData: 1000 }</code> is sent.</li>
  </ol>
  
  <p>I would preferably like to do this only using Jest without depending on modules like <code>mock-fetch</code> and <code>jest-mock-fetch</code>. However, if the solution without using is way too complex, then I would be happy to use them. Just don't want to create unnecessary dependencies if not required.</p>