Graphql-yoga: How to use with supertest

Created on 23 Sep 2018  路  6Comments  路  Source: dotansimha/graphql-yoga

Hey there,

I wonder if there is a way to use supertest to test the graphQL endpoint.
I did not find a way to expose the http object for test, like supertest wants it : https://www.npmjs.com/package/supertest

Is there a way ? Because with Jest i cannot bind the server app on any port.

Most helpful comment

For those who may wonder, i used to make it work this way :

async function app(): Promise<GraphQLServer> {
  const schema = await getSchema();

  const server = new GraphQLServer({ schema });
  server.use('/health', healthController);
  server.use('/version', versionController);

  return server;
}

// and in my tests
const server = (await app).createHttpServer({});
const req: any = request(server)
  .post(url)
  .set('Accept', 'application/json');

And it work for both express and gaphql server middlewares

All 6 comments

For those who may wonder, i used to make it work this way :

async function app(): Promise<GraphQLServer> {
  const schema = await getSchema();

  const server = new GraphQLServer({ schema });
  server.use('/health', healthController);
  server.use('/version', versionController);

  return server;
}

// and in my tests
const server = (await app).createHttpServer({});
const req: any = request(server)
  .post(url)
  .set('Accept', 'application/json');

And it work for both express and gaphql server middlewares

@DavidBabel But how does the server know where to serve the graphql endpoint from?
I tried

(await app).createHttpServer({ endpoint: '/graphql' })

But the supertest request cannot find anything at /graphql.

Here is what we use as utils (note this is typescript, but can be easily adapted) :

import * as request from 'supertest';
import app from '../app';

interface IRequestResponse {
  errors: any[];
  data: object;
}

export async function getAPIResponse(
  query?: string
): Promise<IRequestResponse> {
  const server = (await app).createHttpServer({});
  const res = await request(server)
    .post('/')
    .set('Accept', 'application/json')
    .send({ query })
    .expect(200)
    .expect('Content-Type', /json/);

  return res.body;
}

@DavidBabel how to include the validationRules and formatError in supertest? As these options are passed to the start method, is there a way to include them in tests?

@DavidBabel thanks!

Was this page helpful?
0 / 5 - 0 ratings