title: How do you stub fetch api request
body: <p>I am having a problem with stubbing/testing function that is using fetch.</p>
  
  <p>Using simple example:</p>
  
  <pre><code>export const clickTimeseries =&gt; {
    return fetch('...url...')
      .then(response =&gt; {
        if(response.status == 200)
          return response.json()
        else
          throw 'something'
      })
      .then(json =&gt; {
        return {
          success: true,
          data: json,
        }
      })
      .catch(err =&gt; {
        return {
          success: false,
          error: err,
        }
      })
  }
  </code></pre>
  
  <p>And my test:</p>
  
  <pre><code>import { expect } from 'chai'
  import sinon from 'sinon' 
  
  import Promise from 'es6-promise' 
  Promise.polyfill() 
  
  import 'whatwg-fetch'
  
  import clickTimeseries from './above'
  
  const jsonOK = body =&gt; {  
    const mockResponse = new Response(JSON.stringify(body), {  
      status: 200,
      headers: { 
        'Content-type': 'application/json'
      }
    })
  
    return Promise.resolve(mockResponse) 
  }
  
  describe('APIs', () =&gt; {  
    describe('Click timeseries', () =&gt; { 
      it('builds a correct data on success', () =&gt; { 
        sinon.stub(window, 'fetch').returns(jsonOK({stuff: [1,2,3]})) 
  
        expect(clickTimeseries()).to.eq({ 
          success: true,
          data: {stuff: [1,2,3]}
        })
      })
    })
  })
  </code></pre>
  
  <p>I am getting error:</p>
  
  <pre><code>expected { Object (, _state, ...) } to equal { success: true, data: {stuff: [ 1, 2, 3, 4 ] }}
  </code></pre>
  
  <p>It looks like <code>spendTimeseries</code> returns promise, instead of the result of calling both <code>then</code> blocks.</p>
  
  <p>How would you have to setup your test to have it pass?</p>