UNPKG

@graphql-codegen/testing

Version:
30 lines (29 loc) 1.07 kB
import { createYoga } from 'graphql-yoga'; import nock from 'nock'; export function mockGraphQLServer({ schema, host, path, intercept, method = 'POST', }) { const yoga = createYoga({ schema, logging: false }); const handler = async function (uri, body) { if (intercept) { intercept(this); } // Create a generic Request object that can be consumed by Yoga's fetch API const request = new Request(new URL(host + uri), { method, headers: this.req.headers, body: method === 'GET' ? undefined : JSON.stringify(body), }); const response = await yoga.fetch(request); const headers = {}; for (const [name, value] of response.headers) { headers[name] = value; } return [response.status, await response.json(), headers]; }; switch (method) { case 'GET': return nock(host).get(path).reply(handler); case 'POST': return nock(host).post(path).reply(handler); } return null; }