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.
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 documentation 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.
server.spec.ts
import * as fetchMock from 'fetch-mock';
import * as request from 'supertest';
import server from './server';
afterEach(() => {
server.close();
fetchMock.reset();
});
describe('router', () => {
test('GET: should return data', async () => {
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);
});
});
server.ts
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 => {
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;