Adopting GraphQL and implementing GraphQL testing have become critical in the API-first landscape.
The skyrocketing demand for modern software has put the importance of maintainable, functional, and scalable code on top. To enable independent evolution and decouple the front end from the backend, manual and automated API testing needs to take place for SOAP and REST architecture styles.
Amazon, Facebook, AirBnB, GitHub, and many other tech companies are adopting GraphQL as an alternative to the traditional REST and SOAP APIs.
As the GraphQL architecture continues to gain traction, making sure they are thoroughly, extensively, and automatically tested is pivotal to ensure performant APIs and business flows continuity.
In this article, we'll explore how GraphQL works as well as the importance, and best practices of GraphQL testing.
GraphQL came out as the solution to a more fluent and customized way for complex API data retrieval. With traditional REST, the large number of requests and endpoints add complexity and redundant data to API interactions.
Essentially, GraphQL is a query language and server-ride runtime for APIs that allow clients to request multiple resources via types and fields.
Here’s how requests look under REST vs GraphQL. We’ll use the use case of interacting with a post on a social media platform:
REST: Multiple endpoints
GraphQL: Single endpoint
The basic idea behind GraphQL is mutations and queries that specify and retrieve exactly the data you need and nothing else.
Here’s an example of a GraphQL query and mutation.
Query | Mutation |
query { findAllBooks { id title isbn pageCount author { id firstName lastName } } } | mutation { deleteBook(id:3) } |
The clients send queries to the server by describing the required data and its format without over or under-fetching.
Below are some key reasons why GraphQL has gained popularity compared to REST:
This makes it faster than REST APIs as it doesn’t have to make multiple calls to different endpoints to get your data.
This approach involves using a client library specific to the programming language you are using. The client library will handle the request and response objects, and provide a convenient way to call the GraphQL API. Examples of client libraries include Apollo Client for JavaScript, Apollo Android for Android, and graphql-java for Java.
GraphQL API can also be called using a REST client such as Postman or Insomnia. To do this, you set the request URL to the GraphQL endpoint and specify the GraphQL query as the request body. The response will be in JSON format, which you can parse and use in your application.
Command-line tools such as Curl, or HTTPie are used to make HTTP requests to the GraphQL API. You can make requests and parse the response in a command-line environment.
GraphiQL or GraphQL Playground provides a visual interface for writing GraphQL queries. You can use these tools to explore and test GraphQL APIs, as well as to create and execute queries.
GraphQL API testing checks the correctness of the schemas, queries, and mutations created for an API. To maintain the API’s reliability and performance, below are what needs to be tested:
GraphQL API testing means writing test cases to query and mutate nested data. Take a quick look at how components on a Facebook feed are nested:
Much like shadow DOM, interlinked data gradually become disastrous, especially since traditional REST APIs require multiple separate query parameters and endpoints to communicate.
Read more: API Testing Tips | How To Test APIs | Software Testing Basics (katalon.com)
If you’ve been using REST, here’s how GraphQL testing differs:
There are several aspects of a GraphQL API that should be verified through testing:
These tests can be organized following the test pyramid model, which defines different levels and scopes of testing:
Read more: Unit Testing vs Integration Testing: What are the key differences?
While GraphQL's dynamic nature is conducive to client-driven data retrieval, it presents challenges in covering all possible test scenarios. It is therefore suggested to start with scenarios with realistic and representative queries that clients may use in production. For example, in an e-commerce website, APIs for authentification, product searching, cart, or checkout are cases that should be prioritized.
Testing GraphQL can be complex as a single query can request multiple levels of nested data. Considering the batched data and dependencies between fields, it's important to ensure that the test data covers combinations of nested and batched queries to thoroughly validate the behavior of the GraphQL API.
When testing GraphQL APIs that rely on external web services, it is recommended to simulate responses instead of testing against production instances. This approach ensures that tests do not impact the production environment and can be run repeatedly without incurring unnecessary costs or delays.
Not every API testing tool or library has supported GraphQL just yet. Below is a mix of EasyGraph, Katalon, Postman and how they are used to create and test GraphQL endpoints.
EasyGraphQL is a Javascript library for GraphQL API. With EasyGraphQL, you can:
Below is an example of an EasyGraphQL assertion:
Katalon is a test automation platform to help QA teams plan, design, run and debug automated API and UI integration test cases. Additionally, Script Mode is available for users to write queries and mutations in Java/Groovy.
Katalon provides robust support for API testing, including the ability to test GraphQL, REST and SOAP APIs. Its integrations with GraphQL tools like Postman, Swagger, and SoapUI allow you to import existing API specifications and test your new API schema along with legacy API assets on one platform.
Read More: 15 Best Postman Alternatives For API Testing
Web elements such as dropdowns, input fields, or buttons are organized within an Object Repository. This is key to updating locators and properties globally, across test cases
A keyword library and test recorder are available also for easy drag and drop. Imagine being able to spin up an automation script from your manual tests in minutes.
Katalon enables automating API tests with varying data scenarios by supporting multiple data formats (CSV, Excel), and databases (MySQL, Oracle, SQL Server). Testers can define variables in test scripts, objects or request attributes and bind them to the corresponding data fields from external data sources.
Katalon has all the features built-in to facilitate end-to-end continuous test automation: From writing tests using either low-code or full-code methods to executing in CLI mode across environments to gaining visibility from comprehensive reporting. No installations or integration workarounds are needed.
Katalon's integrations with tools such as Circle CI, Jenkins, and GitLab allow test cases to be automated and run as part of the CI/CD pipeline. Wiring up UI and API tests to automatically trigger and run ensures that integration issues are detected and addressed early.
Rest Assured is a Java-based library commonly used for testing REST APIs. However, it can also be used for testing GraphQL APIs as long as the GraphQL query(request) in itself is not a JSON payload:
Karate is a GraphQL testing framework that makes it easy to test GraphQL APIs. It supports JSON and allows you to easily include variables in your queries. You can pass the GraphQL Query as it is and validate the response using Karate’s match assertions.
With Postman, you can quickly create and send GraphQL queries, including queries with variables. You can also organize your queries into collections to manage and run multiple requests at once. Postman provides a user-friendly interface for exploring and testing GraphQL APIs, and it allows you to easily view and analyze the responses to your queries.
From the viewpoint of the client side, queries, and mutations are the most common types of GraphQL operations. Following the CRUD model (create, read, update, and delete), a query is similar to a GET request and maps to the "read" operation in CRUD, while mutations correspond to the other operations and are used to create, update, or delete data on the server.
To create a GraphQL test request, simply insert the query into the GET query parameter. However, testing GraphQL mutations only supports the POST method.
It's important to test queries and mutations as it involves adding or accessing data in databases. Mutations modify data in the database and return us a value. Mutations can edit and manipulate the data from the server side.
Because GraphQL responses are in JSON format, you have the option to verify a GraphQL response against a JSON schema, which allows for error troubleshooting without the need for a HAR file.
It's also possible to verify a GraphQL request body against a GraphQL schema to ensure the request is valid before being sent to the server. The server handles the verification process, and the response section will provide the validation results if you use keywords in the Verification tab. Alternatively, the Log Viewer will display the validation results if you use keywords in a test case.
Read more for further instructions: GraphQL in Katalon Studio
There are 2 main differences between the 2 methods:
Both GraphQL and REST API development lifecycle approaches are useful depending on the specific need of your project.
GraphQL is a better fit for projects where the client needs a lot of control over the data being fetched from the server. It's also ideal in the case of using multiple data sources. GraphQL simplifies the task of collecting data from different APIs and resolving the data to the client in one request
In contrast, REST APIs are more suitable for projects with simpler data structures. REST is also more suitable for projects where caching is important. Since a REST API provides many endpoints, you can easily configure a web cache to match certain URL patterns, HTTP methods, or specific resources.