diff --git a/__tests__/router_spec.js b/__tests__/router_spec.js index c7eafa9..fd70899 100644 --- a/__tests__/router_spec.js +++ b/__tests__/router_spec.js @@ -1,4 +1,4 @@ -import { Server, Router } from '../src'; +import { Server, Router, Response as KakapoResponse } from '../src'; describe('Router', () => { test('Router # config # host', async () => { @@ -261,5 +261,60 @@ describe('Router', () => { expect(response.body).toEqual('async response'); }); + + test('Router # Fetch # Content-Type image/svg+xml', async () => { + const server = new Server(); + const router = new Router(); + + const svgData = 'svgData'; + + + router.get('/svg_content', request => { + return new KakapoResponse(200, svgData, { + 'content-type': 'image/svg+xml' + }); + }); + + server.use(router); + + const response = await fetch('/svg_content'); + + expect(response.body).toEqual(svgData); + }); + + + test('Router # Fetch # No Content Type', async () => { + const server = new Server(); + const router = new Router(); + const expectedResponse = { foo: 'bar'}; + + router.get('/json_content', request => { + return new KakapoResponse(200, expectedResponse); + }); + + server.use(router); + + const response = await fetch('/json_content'); + + expect(response.json()).resolves.toEqual(expectedResponse); + }); + + test('Router # Fetch # Content Type application/json', async () => { + const server = new Server(); + const router = new Router(); + const expectedResponse = { foo: 'bar'}; + + router.get('/json_content', request => { + return new KakapoResponse(200, expectedResponse, { + 'content-type': 'application/json', + }); + }); + + server.use(router); + + const response = await fetch('/json_content'); + + expect(response.body).toEqual(JSON.stringify(expectedResponse)); + }); // @TODO Test strategies in router. }); diff --git a/src/interceptors/fetchInterceptor.js b/src/interceptors/fetchInterceptor.js index a9a8fdc..e479a2c 100644 --- a/src/interceptors/fetchInterceptor.js +++ b/src/interceptors/fetchInterceptor.js @@ -9,9 +9,16 @@ import { import { mapRequestInfoToUrlString, canUseWindow } from "../utils"; const nativeFetch = canUseWindow && window.fetch; -const fakeResponse = (response = {}, headers = {}) => { - const responseStr = JSON.stringify(response); - return new Response(responseStr, { headers }); +const fakeResponse = (response: string | any = {}, headers = {}) => { + // If content type exist and is different to application/json no parse the response + if (headers['content-type'] && headers['content-type'].indexOf('application/json') == -1) { + console.log(response); + + return new Response(response, { headers }); + } + + // Default handler, If no content type response as json. + return new Response(JSON.stringify(response), { headers }); }; export class FakeFetch {