How to test GraphQL with Codeception in PHP

Posted on 15. December 2022

GraphQL is a query language for APIs. It was developed by Facebook and is often used as an alternative to REST APIs - but you can define the specific data you want to retrieve from the API.

But how to test GraphQL with Codeception in PHP?

Spoiler: You do not need an extension.

1. Queries, mutations and variables

In GraphQL, a query is a request for data from an API. It is used to retrieve information from the server. A mutation, on the other hand, is a request to change or update data on the server.

The following query retrieves the name and email address from the user with the id 1.

query {
  user(id: 1) {
    name
    email
  }
}

In the real world, you do not want to use the variable 1 directly in the query. Think about a text which needs to be escaped first because it contains special chars like " or ( so the query does not get messed up.

In GraphQL, you can pass variables as arguments to a query or mutation. These variables can be used to provide dynamic values in the query or mutation, rather than hard-coding them. For example, you might use a variable like this:

query ($userId: ID!) {
  user(id: $userId) {
    name
    email
  }
}

In this query, the $userId variable is used as the argument to the user field. When the query is executed, the value of the $userId variable will be used as the id argument for the user field.

2. How to test

To test a GraphQL API with Codeception, you can use the Codeception Module REST. This module allows you to send HTTP requests to an API and make assertions on the response.

Also, the above information is important because we do not want to hack together a query string which will be sent.

We can define an array which will be sent by the API testing module where the variables will be escaped automatically.

$query = [  
  'query' => '
    query ($userId: ID!) {
      user(id: $userId) {
        name
        email
      }
    }',
  'variables' => [
    'id' => 1,
  ]
];

$I->sendPost("/graphql", $query);

$I->seeResponseCodeIs(\Codeception\Util\HttpCode::OK);

On sendPost, the variables will be escaped automatically by the function encodeApplicationJson.

Mutations will be tested the same way.

You can now also check for the response data by using the assertion assertJsonStringEqualsJsonString.

Happy testing 🤞

Made with ♥️ and Gatsby © 2024