15. Testing GraphQL APIs
GraphQL APIs require different testing approaches than REST APIs. This module covers testing GraphQL queries, mutations, and subscriptions. Understanding GraphQL testing is essential for modern full-stack development.
The key insight is that GraphQL tests should verify the query, the resolver, and the response. Testing GraphQL involves testing schema, resolvers, and integration with the data layer. Understanding GraphQL testing is essential for reliable GraphQL APIs.
This module covers testing GraphQL with Apollo Server and GraphQL Yoga.
Testing GraphQL Queries
GraphQL queries are tested by sending a query to the GraphQL endpoint and verifying the response. Tools like Apollo Server testing utilities and supertest can be used. Tests should cover: successful queries, error cases, and authorization.
GraphQL tests should be fast and independent. Use a test database or mock external dependencies. Run tests in isolation to avoid conflicts.
Try It Yourself: GraphQL Testing
Follow these steps to practice GraphQL testing.
Step 1: Set up the GraphQL server// server.js<br>import { ApolloServer, gql } from <strong><code>apollo-server;
const typeDefs = gql`
type User {
id: ID!
name: String!
email: String!
}
type Query {
users: [User!]!
user(id: ID!): User
}
type Mutation {
createUser(name: String!, email: String!): User!
}
`;
let users = [];
let id = 1;
const resolvers = {
Query: {
users: () => users,
user: (_, { id }) => users.find(u => u.id === Number(id)),
},
Mutation: {
createUser: (_, { name, email }) => {
const user = { id: id++, name, email };
users.push(user);
return user;
},
},
};
const server = new ApolloServer({ typeDefs, resolvers });
export default server;
Step 2: Write GraphQL tests// server.test.js<br>import { createTestClient } from <strong><code>apollo-server-testing;
import server from ./server;
describe(GraphQL API, () => {
const { query, mutate } = createTestClient(server);
test('QUERY users returns empty array initially', async () => {
const res = await query({
query: `query { users { id name email } }`
});
expect(res.data.users).toEqual([]);
});
test(MUTATION createUser creates a new user, async () => {
const res = await mutate({
mutation: `mutation {
createUser(name: Alice, email: alice@example.com) {
id name email
}
}`
});
expect(res.data.createUser).toHaveProperty(id, 1);
expect(res.data.createUser.name).toBe(Alice);
expect(res.data.createUser.email).toBe(alice@example.com);
});
test(QUERY user returns user by id, async () => {
await mutate({
mutation: `mutation { createUser(name: Bob, email: bob@example.com) { id } }`
});
const res = await query({
query: `query { user(id: 1) { id name email } }`
});
expect(res.data.user).toHaveProperty(id, 1);
expect(res.data.user.name).toBe(Bob);
});
});
Try It Yourself: Add a mutation to update a user. Write tests for it. Add error handling and test error cases.
Knowledge Check
Ready to test your understanding of 15. Testing GraphQL APIs?