Lesson 5
Testing GraphQL APIs with Apollo Server 4
Deprecation Notice

This course path teaches Apollo Server 3, which has been deprecated. To access the new course paths covering Apollo Server 4, use this course path.

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.

TypeScript
1const typeDefs = `#graphql 2 type Book { 3 id: ID! 4 title: String! 5 author: String! 6 } 7 8 type Query { 9 books: [Book] 10 } 11 12 type Mutation { 13 addBook(title: String!, author: String!): Book 14 } 15`;

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.

TypeScript
1const books = [ 2 { id: '1', title: 'The Hobbit', author: 'J.R.R. Tolkien' }, 3 { id: '2', title: 'Harry Potter', author: 'J.K. Rowling' } 4]; 5 6const resolvers = { 7 Query: { 8 books: () => books 9 } 10};

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:

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

    TypeScript
    1const queryBooks = async () => { 2 const query = ` 3 query { 4 books { 5 id 6 title 7 author 8 } 9 } 10 `; 11 const res = await executeQuery(query); 12 console.log(res.body.singleResult.data); 13}; 14 15queryBooks();

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:

JSON
1{ 2 "books": [ 3 { 4 "id": "1", 5 "title": "The Hobbit", 6 "author": "J.R.R. Tolkien" 7 }, 8 { 9 "id": "2", 10 "title": "Harry Potter", 11 "author": "J.K. Rowling" 12 } 13 ] 14}
Implementing and Testing Mutations

Next, let's implement the addBook mutation and learn how to test it.

First, we define the resolver for the addBook mutation.

TypeScript
1const resolvers = { 2 Query: { 3 books: () => books 4 }, 5 Mutation: { 6 addBook: (_: any, { title, author }: { title: string, author: string }) => { 7 const newBook = { id: String(books.length + 1), title, author }; 8 books.push(newBook); 9 return newBook; 10 } 11 } 12};

To test this mutation in Apollo Server 4, utilize the server's capabilities to execute operations:

  1. Set Up Apollo Server and Execute the Mutation:

    TypeScript
    1import { ApolloServer } from '@apollo/server'; 2import { startStandaloneServer } from '@apollo/server/standalone'; 3 4const server = new ApolloServer({ typeDefs, resolvers }); 5 6const executeMutation = async (mutation: string) => { 7 const result = await server.executeOperation({ query: mutation }); 8 return result; 9};
  2. Write and Execute the Test Mutation:

    TypeScript
    1const addBook = async () => { 2 const mutation = ` 3 mutation { 4 addBook(title: "1984", author: "George Orwell") { 5 id 6 title 7 author 8 } 9 } 10 `; 11 const res = await executeMutation(mutation); 12 console.log(res.body.singleResult.data); 13}; 14 15addBook();

When you run this code, the server executes the addBook mutation, and you should see the following output:

JSON
1{ 2 "addBook": { 3 "id": "3", 4 "title": "1984", 5 "author": "George Orwell" 6 } 7}
Lesson Summary

To sum up, in this lesson, you learned how to:

  • Set up a basic GraphQL environment using Apollo Server 4.
  • Define a simple GraphQL schema.
  • Implement and test queries and mutations using Apollo Server's built-in operation execution methods.

These testing techniques ensure that your GraphQL API remains robust as it scales. Congratulations on completing the Comprehensive Intro to GraphQL in TypeScript course path! Now, you have a strong foundation in both creating and testing GraphQL APIs. Make sure to apply these skills in your future projects and dive deeper into more advanced topics as you grow your expertise. Happy coding!

Enjoy this lesson? Now it's time to practice with Cosmo!
Practice is how you turn knowledge into actual skills.