Testing GraphQL APIs — GraphQL

Testing GraphQL APIs Test GraphQL API seperti test API biasa, tapi ada tooling khusus yang membantu. Integration Test import { ApolloServer } from "@apollo/serv

Testing GraphQL APIs

Test GraphQL API seperti test API biasa, tapi ada tooling khusus yang membantu.

Integration Test

import { ApolloServer } from "@apollo/server";
import { typeDefs, resolvers } from "./schema";

describe("User queries", () => {
  let server;

  beforeAll(() => {
    server = new ApolloServer({ typeDefs, resolvers });
  });

  test("get user by id", async () => {
    const response = await server.executeOperation({
      query: `
        query GetUser($id: ID!) {
          user(id: $id) {
            id
            name
            email
          }
        }
      `,
      variables: { id: "1" },
    });

    expect(response.body.singleResult.data.user).toEqual({
      id: "1",
      name: "Budi",
      email: "[email protected]",
    });
  });

  test("create user validates input", async () => {
    const response = await server.executeOperation({
      query: `
        mutation {
          createUser(input: { name: "", email: "invalid" }) {
            ... on ValidationError { field message }
          }
        }
      `,
    });

    expect(response.body.singleResult.data.createUser).toMatchObject({
      field: "email",
    });
  });
});

Testing Tools

Schema Testing

// Pastikan schema valid dan backward-compatible
import { buildSchema, validateSchema } from "graphql";

test("schema is valid", () => {
  const schema = buildSchema(typeDefs);
  const errors = validateSchema(schema);
  expect(errors).toHaveLength(0);
});

Yang akan kamu pelajari