🚀 Nuova versione beta disponibile! Feedback o problemi? Contattaci

Testare le API GraphQL: Strategie e Strumenti

Codegrind TeamSep 05 2024

Testare le API GraphQL è un passaggio fondamentale per garantire che le query, le mutazioni e le subscriptions funzionino correttamente, siano efficienti e non presentino vulnerabilità. A differenza delle API REST, le API GraphQL offrono una maggiore flessibilità nella richiesta dei dati, il che rende il testing ancora più cruciale per verificare tutte le combinazioni possibili di input e output. In questo articolo esploreremo diverse strategie per testare le API GraphQL, comprese le migliori pratiche, gli strumenti e le tecniche per garantire la qualità delle API.

Tipi di Test per API GraphQL

1. Test delle Query

Le query vengono utilizzate per leggere i dati, quindi i test delle query devono verificare che i dati restituiti siano corretti in base agli input forniti e che le query non abbiano problemi di performance o sicurezza.

2. Test delle Mutazioni

Le mutazioni modificano i dati, e i test per le mutazioni devono garantire che l’integrità dei dati venga mantenuta dopo ogni operazione di scrittura, come la creazione, l’aggiornamento e la cancellazione di dati.

3. Test delle Subscriptions

Le subscriptions forniscono aggiornamenti in tempo reale, quindi il test delle subscriptions deve verificare che gli eventi siano emessi correttamente e che i client ricevano gli aggiornamenti attesi in modo coerente.

4. Test di Sicurezza

Le API GraphQL devono essere testate per garantire che non siano vulnerabili ad attacchi comuni, come l’injection, l’accesso non autorizzato ai dati o l’abuso di query complesse e nidificate.

5. Test delle Performance

La performance delle query e delle mutazioni va monitorata e testata per evitare colli di bottiglia o tempi di risposta elevati.

Strumenti per Testare le API GraphQL

1. Jest: Testing di API GraphQL con JavaScript

Jest è una popolare libreria di testing per JavaScript e TypeScript, ampiamente utilizzata per il test di applicazioni Node.js. Può essere facilmente integrata per testare API GraphQL.

Esempio di Test per una Query

npm install jest graphql-request
const { request, gql } = require("graphql-request");

const endpoint = "http://localhost:4000/graphql";

const GET_USER = gql`
  query getUser($id: ID!) {
    user(id: $id) {
      id
      name
      email
    }
  }
`;

test("fetch user by ID", async () => {
  const variables = { id: "1" };
  const data = await request(endpoint, GET_USER, variables);
  expect(data.user).toBeDefined();
  expect(data.user.name).toBe("Alice");
});

In questo esempio:

  • Jest esegue un test per la query getUser, verificando che l’utente con id: 1 venga restituito correttamente.
  • graphql-request semplifica l’invio delle query GraphQL al server.

2. Apollo Client: Testing di Query, Mutazioni e Subscriptions

Apollo Client può essere utilizzato per testare query, mutazioni e subscriptions, fornendo un potente client per inviare richieste a un server GraphQL.

Esempio di Test per una Mutation

npm install apollo-client @apollo/client jest
import { ApolloClient, InMemoryCache, gql } from "@apollo/client";
import { createHttpLink } from "apollo-link-http";
import fetch from "node-fetch";

const client = new ApolloClient({
  link: createHttpLink({ uri: "http://localhost:4000/graphql", fetch }),
  cache: new InMemoryCache(),
});

const ADD_USER = gql`
  mutation addUser($name: String!, $email: String!) {
    addUser(name: $name, email: $email) {
      id
      name
      email
    }
  }
`;

test("create a new user", async () => {
  const response = await client.mutate({
    mutation: ADD_USER,
    variables: { name: "Bob", email: "bob@example.com" },
  });

  expect(response.data.addUser.name).toBe("Bob");
  expect(response.data.addUser.email).toBe("bob@example.com");
});

3. Postman: Testing Interattivo delle API

Postman è uno strumento popolare per testare API HTTP e supporta nativamente le API GraphQL. Con Postman, puoi inviare query, mutazioni e subscriptions per verificare che i risultati siano corretti, e puoi anche automatizzare i test.

Esempio di Test di Query con Postman

  • Definisci l’endpoint GraphQL.
  • Scrivi la query direttamente nell’interfaccia di Postman.
  • Esegui la query e verifica i risultati nella scheda “Tests” utilizzando JavaScript per automatizzare la verifica.
pm.test("Status code is 200", function () {
  pm.response.to.have.status(200);
});

pm.test("Response contains user data", function () {
  const jsonData = pm.response.json();
  pm.expect(jsonData.data.user).to.exist;
  pm.expect(jsonData.data.user.name).to.eql("Alice");
});

4. Insomnia: Client API per Testing GraphQL

Insomnia è un altro strumento per testare API GraphQL, simile a Postman ma con un’interfaccia user-friendly e funzionalità avanzate come la gestione delle subscriptions e l’invio di mutazioni.

  • Offre un editor interattivo per inviare query e mutazioni.
  • Supporta headers personalizzati, utile per testare API con autenticazione JWT.

5. Supertest: Testing delle API GraphQL in Node.js

Supertest è un’altra libreria utilizzata per testare le API in Node.js. Può essere combinata con Jest per testare facilmente le API GraphQL.

Esempio di Test di un’API GraphQL con Supertest

npm install supertest jest
const request = require("supertest");
const app = require("./app"); // Assumendo che app sia il tuo server Express

const GET_USER = `
  query getUser($id: ID!) {
    user(id: $id) {
      id
      name
      email
    }
  }
`;

test("should fetch a user by id", async () => {
  const response = await request(app)
    .post("/graphql")
    .send({
      query: GET_USER,
      variables: { id: "1" },
    });

  expect(response.body.data.user).toBeDefined();
  expect(response.body.data.user.name).toBe("Alice");
});

In questo esempio, Supertest viene utilizzato per inviare una richiesta POST al server GraphQL e verificare la risposta.

6. GraphQL Playground: Debugging e Testing Interattivo

GraphQL Playground è uno strumento che ti permette di testare API GraphQL in modo interattivo direttamente dal browser o come parte del tuo progetto. Supporta le subscriptions ed è uno dei modi migliori per eseguire test manuali e verificare rapidamente se una query o una mutation funziona.

  • Autocompletamento delle query: Suggerisce campi e tipi durante la scrittura delle query.
  • Test delle subscriptions: Permette di testare subscriptions in tempo reale.

7. chai-http: Test delle API GraphQL in Mocha

Se preferisci Mocha come framework di testing, puoi usare chai-http per inviare richieste HTTP e testare le API GraphQL.

Esempio di Test con Mocha e Chai

npm install mocha chai chai-http
const chai = require("chai");
const chaiHttp = require("chai-http");
const app = require("./app");
const { expect } = chai;

chai.use(chaiHttp);

describe("GraphQL API", () => {
  it("should return a user", (done) => {
    chai
      .request(app)
      .post("/graphql")
      .send({
        query: `
          query {
            user(id: "1") {
              id
              name
              email
            }
          }
        `,
      })
      .end((err, res) => {
        expect(res.status).to.equal(200);
        expect(res.body.data.user).to.have.property("name", "Alice");
        done();
      });
  });
});

In questo esempio, Mocha e Chai vengono utilizzati per testare una query GraphQL.

Test delle Subscriptions

Le subscriptions rappresentano una sfida maggiore rispetto a query e mutazioni perché richiedono il testing di una connessione WebSocket.

Esempio di Test per una Subscription

const WebSocket = require('ws');

test('should receive a message through subscription', (done) => {
  const ws = new WebSocket('ws://localhost:4000/graphql', 'graphql

-ws');

  ws.on('open', () => {
    ws.send(JSON.stringify({
      type: 'start',
      id: '1',
      payload: {
        query: `
          subscription {
            messageAdded {
              id
              content
              author
            }
          }
        `,
      },
    }));

    // Invia una mutation per attivare la subscription
    setTimeout(() => {
      request(app)
        .post('/graphql')
        .send({
          query: `
            mutation {
              addMessage(content: "Hello World", author: "Alice") {
                id
                content
              }
            }
          `,
        });
    }, 100);
  });

  ws.on('message', (message) => {
    const data = JSON.parse(message);
    if (data.type === 'data') {
      expect(data.payload.data.messageAdded.content).toBe('Hello World');
      ws.close();
      done();
    }
  });
});

In questo esempio:

  • WebSocket viene utilizzato per testare la subscription messageAdded.
  • La subscription viene attivata inviando una mutation, e il test verifica che il client riceva correttamente l’evento.

Conclusione

Testare le API GraphQL è essenziale per garantire l’affidabilità, la sicurezza e la performance dell’applicazione. Utilizzando strumenti come Jest, Supertest, Apollo Client, e client interattivi come Postman e Insomnia, puoi coprire tutte le aree del testing, dalle query e mutazioni alle subscriptions e alla sicurezza. Implementando una strategia di testing completa, puoi evitare bug, migliorare l’esperienza utente e garantire che le tue API siano sempre pronte per l’ambiente di produzione.