title: How to setup fetch-mock with node-fetch, supertest and typescript
body: <p>I am trying to add some jest tests to my node typescipt project. I would like to use supertest to call my koa router, but also use fetch-mock to mock requests that are made using node-fetch.</p>
  
  <p>My solution so far is below, but the fetch in my router does not use the mocked fetch setup with fetch-mock. The unit test fails because the expected response I mocked is not returned. I have tried following the <a href="http://www.wheresrhys.co.uk/fetch-mock/#usageusage-with-jest" rel="noreferrer">documentation</a> for global fetch mocking but without success, and typescript makes it difficult to follow the non-typescript solutions I have found. I would like to avoid using the non-global sandbox if possible as I would have to re-write a lot of code to pass the fetch around.</p>
  
  <p><strong>server.spec.ts</strong></p>
  
  <pre><code>import * as fetchMock from 'fetch-mock';
  import * as request from 'supertest';
  import server from './server';
  
  afterEach(() =&gt; {
    server.close();
    fetchMock.reset();
  });
  
  describe('router', () =&gt; {
    test('GET: should return data', async () =&gt; {
      const expectedResponse = { test: 'TEST' };
      fetchMock.get('https://myapi.com/test', expectedResponse);
  
      const response = await request(server).get('/test');
      expect(response.status).toEqual(200);
      expect(response.body).toMatchObject(expectedResponse);
    });
  });
  </code></pre>
  
  <p><strong>server.ts</strong></p>
  
  <pre class="lang-js prettyprint-override"><code>import * as Koa from 'koa';
  import * as Router from 'koa-router';
  import fetch from 'node-fetch';
  
  const app = new Koa();
  
  const router = new Router();
  
  router.get('/test', async ctx =&gt; {
    const options = { method: 'GET' };
    try {
      const response = await fetch('https://myapi.com/test', options);
      ctx.body = await response.json();
    } catch (error) {
      error.fetchUrl = url;
      throw error;
    }
  });
  
  app.use(router.routes());
  
  const server = app.listen(3000);
  
  export default server;
  </code></pre>