title: How to test with Jest a fetch() call result
body: <p>I'm very new to Jest and I need to test a class method that fetches data. It's a regular JS file, I'm not on node environment.</p>
  <p>In my <code>script.js</code> I have the following class:</p>
  <pre class="lang-js prettyprint-override"><code>class Manager {
    constructor(params) {
      // ...
    }
    
    async getData() {
      const data = await fetch(this.#requestUrl)
        .then(res =&gt; res.json())
        .then(data =&gt; data)
      return data
    }
  }
  
  module.exports = {Manager}
  </code></pre>
  <p>In runtime it works, I do receive data from the URL in the following format: <code>{id: 'some_id', list: [{}, {}, ...]}</code>. However now I need to test it.</p>
  <p>So first I wrote this test in my <code>script.test.js</code>:</p>
  <pre class="lang-js prettyprint-override"><code>const { Manager } = require('./script')
  
  describe('Manager Script', ()=&gt; {
    const manager = new Manager({//params})
  
    test('Successfully fetching data', () =&gt; {
      expect.assertions(1)
      return manager.getData().then(({ data }) =&gt; {
        expect(data.list.length).toBeGreaterThanOrEqual(6)
      })
    })
  })
  </code></pre>
  <p>I received the following error: <code>ReferenceError: fetch is not defined</code></p>
  <p>I tried to mark the test callback function as async and tried this:</p>
  <pre class="lang-js prettyprint-override"><code>const data = await manager.getData().then(res =&gt; res)
  expect(data.list.length).toBeGreaterThanOrEqual(6)
  </code></pre>
  <p>Same result - <code>fetch is not defined</code></p>
  <p>So I tried to install <code>jest-fetch-mock</code> and mock the result. After many attempts this mock worked for me:</p>
  <pre class="lang-js prettyprint-override"><code>require('jest-fetch-mock').enableMocks()
  
  // in suit
  beforeEach(() =&gt; {
    fetch.resetMocks()
  })
  
  //in the actual test
  fetch.mockResponseOnce(
    JSON.stringify({
      data: {
        id: 'abc',
        list: [{ id: '1' }, { id: '2' }, { id: '3' }, { id: '4' }, { id: '5' }, { id: '6' }],
      },
    })
  )
  
  manager.getData().then(({ data }) =&gt; {
    expect(data.list.length).toBeGreaterThanOrEqual(6)
  })
  </code></pre>
  <p>But the question remains - how do I test the actual call? The data that I should receive from <code>getData</code> method?</p>
  <p>I saw a few similar questions here on SO, but I couldn't find a solution for my case.</p>