This example demonstrates a simple load test on a GraphQL API. Using the graphql-request NPM package, a lightweight GraphQL client,and its peer-dependency, the graphql NPM package, users can make GraphQL queries and mutations as part of their tests. The public GraphQL endpoint in this test consumes a country code and returns its name, capital, currency, languages, and other requested information.

Code

Environment Variables
GRAPHQL_ENDPOINT=https://countries.trevorblades.com/graphql
Test Spec
import { gql, GraphQLClient, request } from 'graphql-request';

class GraphQLTestSpec {
  npmDeps = {
    graphql: '16.6.0',
    'graphql-request': '6.0.0',
  };

  async vuInit(ctx) {
    // Create and pass down a GraphQL client
    const graphQLClient = new GraphQLClient(process.env.GRAPHQL_ENDPOINT);
    return { graphQLClient };
  }

  async vuLoop(ctx) {
    // Get the GraphQL client from vuInit()
    const { graphQLClient } = ctx.vuInitData;

    // Define the query
    const query = gql`
      {
        country(code: "US") {
          name
          native
          capital
          emoji
          currency
          languages {
            code
            name
          }
        }
      }
    `;

    const startTime = Date.now();
    // Execute the query and capture the time taken
    const response = await graphQLClient.request(query);
    ctx.metric('US Country Query', Date.now() - startTime, 'ms');

    // Log the output during a Debug Run to verify the result
    console.debug(JSON.stringify(response, null, 2));
  }
}