Testing GraphQL APIs with Apollo Server 4

Introduction to Testing GraphQL APIs

Welcome to the final lesson of our course! Here, we'll learn how to test GraphQL APIs, ensuring that your server is robust and reliable. Testing is crucial for maintaining the stability and functionality of your API as it evolves.

Defining the GraphQL Schema

Let's define a simple schema involving books. This schema includes the Book type, a Query for retrieving books, and a Mutation for adding a book.

const typeDefs = `#graphql
  type Book {
    id: ID!
    title: String!
    author: String!
  }

  type Query {
    books: [Book]
  }

  type Mutation {
    addBook(title: String!, author: String!): Book
  }
`;

Here's a brief explanation:

  • Book: Represents a book with id, title, and author fields.
  • Query books: Fetches a list of books.
  • Mutation addBook: Adds a new book.

Implementing and Testing Queries

Let's implement the books query and see how to test it. We'll use a simple array to store our books.

const books = [
  { id: '1', title: 'The Hobbit', author: 'J.R.R. Tolkien' },
  { id: '2', title: 'Harry Potter', author: 'J.K. Rowling' }
];

const resolvers = {
  Query: {
    books: () => books
  }
};

In Apollo Server 4, testing is handled differently as it does not utilize apollo-server-testing. Instead, we can use tools like @apollo/server combined with graphql-testing utilities or direct request simulation.

Here's a basic approach to testing the books query using Apollo Server 4:

  1. Set Up Apollo Server:

    import { ApolloServer } from '@apollo/server';
    import { startStandaloneServer } from '@apollo/server/standalone';
    
    const server = new ApolloServer({ typeDefs, resolvers });
    
    // For testing purposes, we will directly execute queries using ApolloServer methods
    const executeQuery = async (query: string) => {
      const result = await server.executeOperation({ query });
      return result;
    };
  2. Write and Execute the Test Query:

    const queryBooks = async () => {
      const query = `
        query {
          books {
            id
            title
            author
          }
        }
      `;
      const res = await executeQuery(query);
      console.log(res.body.singleResult.data);
    };
    
    queryBooks();

When you run this code, it sets up the server and uses executeOperation to send the books query, receiving the results directly in your code for inspection. The expected output is:

{
  "books": [
    {
      "id": "1",
      "title": "The Hobbit",
      "author": "J.R.R. Tolkien"
    },
    {
      "id": "2",
      "title": "Harry Potter",
      "author": "J.K. Rowling"
    }
  ]
}
Sign up

Join the 1M+ learners on CodeSignal

Be a part of our community of 1M+ users who develop and demonstrate their skills on CodeSignal