1
votes

I want validate graphql tags on our react client against the schema produced on our graphql server. This validation would run as part of our test setup, and warn us if there are breaking changes in the graphql schema defintion.

So far I have extrated the schema.json from the server using apollo schema:download --endpoint=http...

Now I would like to test the following mutation:

import gql from 'graphql-tag';

const LOGIN_MUTATION = gql`
    mutation LoginMutation($email: String!, $password: String!) {
        login(email: $email, password: $password) {
            id
            accessToken
            refreshToken
            expires
        }
    }
`;

with a test like this:

import { GraphQLSchema } from 'graphql';
import { validate } from 'graphql/validation';
import * as schemaJson from '../../../../../backend/schema.json';
const schema = new GraphQLSchema(schemaJson as any);
import { LOGIN_MUTATION } from './Auth';

test("validate login mutation", assert => {
    const errors = validate(schema, LOGIN_MUTATION);
    const isValid = !errors.length;
    expect(isValid).toBe(true);
});

This gives me the error: Query root type must be provided

How can I valdiate the graphql tag against a given json schema?

2

2 Answers

3
votes

The apollo schema:download command runs an introspection query against the server and gives you the JSON result of that query. You can't take this JSON and pass it directly to the GraphQLSchema constructor -- the proper way to initialize that class is shown in the docs. However, you can use the buildClientSchema function, which:

Given the result of a client running the introspection query, creates and returns a GraphQLSchema instance which can be then used with all GraphQL.js tools, but cannot be used to execute a query, as introspection does not represent the "resolver", "parse" or "serialize" functions or any other server-internal mechanisms.

Putting it all together:

const gql = require('graphql-tag')
const { validate, buildClientSchema } = require('graphql')
const schema = buildClientSchema(introspectionResult)
const document = gql`{
  someQuery
}`
const errorArray = validate(schema, document)
1
votes

You don't need write unit test for checking graphql tag against a given json schema.

During development you can use WebStorm IDE plugin or similar tool or Visual Studio Code plugin. It will look like that: enter image description here

During CI/CD before building you can use GraphQL eslint plugin as part of checking your codestyle.