Skip to content

Instantly share code, notes, and snippets.

@nzaghini
Last active September 23, 2022 17:03
Show Gist options
  • Star 24 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save nzaghini/e038ff05c60bc2c5435f8331f890cea4 to your computer and use it in GitHub Desktop.
Save nzaghini/e038ff05c60bc2c5435f8331f890cea4 to your computer and use it in GitHub Desktop.
Apollo GraphQL Test Example with Jest
import fs from 'fs'
import { makeExecutableSchema } from 'graphql-tools'
import { graphql } from 'graphql'
// the actual resolvers
import resolvers from '../src/resolvers'
// the mock service
import mockMovieService from './mocks/mockMovieService'
// a nice structure for test cases
// found at https://hackernoon.com/extensive-graphql-testing-57e8760f1c25
const allMoviesTestCase = {
id: 'All Movies and Related Directors Test Case',
query: `
query {
allMovies {
id
title
year
director{
firstName
lastName
}
}
}
`,
variables: { },
// injecting the mock movie service with canned responses
context: { movieService: mockMovieService },
// expected result
expected: { data: { allMovies: [
{id: '1', title: 'Interstellar', year: '2014', director: { firstName: 'Christopher', lastName: 'Nolan' }},
{id: '2', title: 'Mad Max: Fury Road', year: '2015', director: { firstName: 'George', lastName: 'Miller' }}] } }
}
describe('My Test Cases', () => {
// array of all test cases, just 1 for now
const cases = [allMoviesTestCase]
// reading the actual schema
const typeDefs = fs.readFileSync('./src/schemas/Movie.graphql', 'utf8')
// make the actual schema and resolvers executable
const schema = makeExecutableSchema({ typeDefs, resolvers })
// running the test for each case in the cases array
cases.forEach(obj => {
const { id, query, variables, context, expected } = obj
test(`query: ${id}`, async () => {
const result = await graphql(schema, query, null, context, variables)
return expect(result).toEqual(expected)
})
})
})
@dep
Copy link

dep commented Jun 3, 2020

@nzaghini Thank you for this. Can you show me your './mocks/mockMovieService' file?

@nzaghini-phorest
Copy link

hey! here we go!

// ********* DUMMY DATA SOURCE *********  //

const directors = [
    {id: 1, firstName: 'Christopher', lastName: 'Nolan', movies: [1, 3]},
    {id: 2, firstName: 'George', lastName: 'Miller', movies: [2]}]
const movies = [
    {id: 1, title: 'Interstellar', year: 2014, directorId: 1},
    {id: 2, title: 'Mad Max: Fury Road', year: 2015, directorId: 2}]

const allDirectors = () => directors
const allMovies = () => movies

module.exports = { allDirectors, allMovies }

@dep-deprecated
Copy link

Thank you!

@dep-deprecated
Copy link

My last issue is that my resolvers expect data sources but there are none provided so the resolvers are failing to load as a result. Would you be also willing to share src/resolvers ? Apologies :)

@dep
Copy link

dep commented Jun 3, 2020

Never mind, I believe I've sorted things out. dropping it here in case it helps anyone:

const { mockServer } = require('graphql-tools');
const { describe, it } = require('mocha');
const { expect } = require('chai');
const { makeExecutableSchema } = require('graphql-tools');
const { typeDefs } = require('./typeDefs');

const schema = makeExecutableSchema({ `
    type Query {
        """
            This returns an array of Tags from the database
        """
        tags: [Tag]
    }
    type Tag {
        id: Int!
        tag: String!
    }
`});

const tagString = 'Hello';

const mocks = {
    Tag: () => ({
        tag: tagString,
    }),
};

const server = mockServer(schema, mocks);

const query = `
query {
    tags {
        id
        tag
    }
}
`;
const variables = {};

server.query(query, variables).then((response) => {
    describe('Tags', () => {
        it('query should return data', () => {
            expect(response.data.tags).to.have.lengthOf(2);
        });
        it('tag name should match the mocked data', () => {
            expect(response.data.tags[0].tag).to.equal(tagString);
        });
    });
});

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment