DEV Community

Cameron Paige
Cameron Paige

Posted on

Testing GraphQL Schema Without Data

"Cannot" is not in my vocabulary. So when I couldn't get GraphQL to work the way the tutorial I was following promised it would, I got a little bit... obsessed.

So it's not much of a surprise that now, just a couple of months since the end of the bootcamp, I find myself in a hands-on two-day GraphQL workshop.

Apart from the expected, what I learned today was:

  • that nobody else in the room had attempted using GraphQL with both Apollo and Prisma. (So maybe I should cut myself some slack there.)

  • that you can and should put comments in your schema.graphql file. (Something for another post.) And finally,

  • that there's a way (not mentioned in the GraphQL spec*) to test the schema without creating a dedicated .json file or fetching actual data from anywhere else.

Here's how:

Set up your index.js to require apollo-server only**, and write your schema directly below. In the picture below, we were working on a simple schema for coffee orders at a cafe:
Screenshot showing const { ApolloServer, gql } = require("apollo-server")

Then, below your schema and resolvers, set up the server to use mock data for all your types:
Screenshot showing const server = new ApolloServer({ typeDefs, resolvers, mocks: true });

If you run npm start now, you should be able to test your schema locally in the GraphQL Playground, with dummy variables substituted for actual data.

In the below example, I ran the allFoodItems query asking for name (specified as the scalar type String in the schema) and price (scalar type Float), and got a valid response (textual data for name and a signed double-precision fractional value for price):
Screenshot of the GraphQL Playground Query Response

And if you do have some of the data already available, you can avoid it being overwritten with mock values by adding mockEntireSchema: false to the server:
Screenshot showing const server = new ApolloServer({ typeDefs, resolvers, mocks: true, mockEntireSchema: false });


*I'd know. I always read the docs.

**I'm assuming that you're familiar with Node.js and have installed the necessary packages (apollo-server, graphql, and nodemon) already.

Top comments (0)