Demystifying GraphQL - Tester’s edition

Demystifying GraphQL – Tester’s edition

It is high time we put out an edition of the GraphQL tutorial for our QA teams. There is a lot of material and more confusion on how to create GraphQL APIs on the internet. As if the idea of REST was easy for teams to understand – the definition of REST has always stopped just at the abbreviation, Representational State Transfer. Developers and Testers alike don’t really understand the concept. We know how to create REST APIs and how to test them and that works for us.

And while we were already fighting to understand REST APIs, we are told that there is a new kid on the block. Many companies including Coursera have moved onto GraphQL. You have to know how to test this new API that twitter and Starbucks are using to pull data. 

So here we go, a simplified version of the GraphQL story for the testing community. 

We will follow a simple sequence of steps to first understand about APIs and REST APIs. Then we travel to the realms of GraphQL and understand how they are different. Finally we create a master plan to test them. Well, aren’t we here to do just that. 

API ? What is that?

API is the acronym for Application Programming Interface, which is a software intermediary that allows two applications to talk to each other. 

Each time you use an app like Facebook, send an instant message, or check the weather on your phone, you’re using an API.

Let us take the example of a restaurant : 

Graph ql

Stick man representing a waiter. Boxes representing other elements.

Assume you are in a restaurant and you have the menu in your hands. 

For the restaurant kitchen to understand what you want to eat/order, you need to communicate this to Kitchen via the menu. 

Here we have two different systems – You & the restaurant kitchen. 

The waiter is the API, takes orders from you, passes it to the kitchen, gets the food to your table. 

So now, we know briefly about what an API is. It helps two systems communicate. 

Now we will try and understand what a REST API is. 

Building a REST API in 5 minutes

To understand the life of a “Waiter”, you have to understand the restaurant ecosystem. 

Let us build a tiny little REST API using nodejs and express.js

You don’t know nodejs and expressjs ? Don’t worry. The objective of this simple project is to simply show you the API that we create using these frameworks. 

Just follow these simple steps. 

What this essentially means is, we will be deploying our API on express js server. 

Step 1

Download and install NodeJS. 
https://nodejs.org/en/download/

Step 2

Check if node and node package manager are installed

Open your command prompt or terminal and type the following commands one by one

npm -v

node -v

If these statements give you valid results, you have node and node package manager(npm) installed.

Step 3

Create a folder “REST_API”

cd REST_API

npm init

When you are prompted for the below, hit enter

This generates a package.json file inside your REST_API folder.

Run the commands

 npm install -g express-generator  
npm install express –save

Express is a really cool Node framework that’s designed to help JavaScript developers create servers really quickly. NodeJS may be server side.

Step 4

Open the folder REST_API in VS Code. If you don’t have it, install it from here

Then create the app.js file or whatever you prefer naming it (default is index.js) and add in the following code.

.


We just created a Waiter in the restaurant. 

Now let us tell the waiter what to get from the kitchen by adding the following code.

.

We have now specified what the Waiter needs to fetch.

Let us sit at the table and order → Run this simple application 

Open the terminal and run the command

npm app.js

You will see the message – “Server running on port 3000”

On any browser, go to the address, http://localhost:3000/url

You should see the below.

What we did here is

  1. We created a simple waiter for our restaurant
  2. We told the waiter what to get 

Since this is a simple app, the return result is also placed in the same app.js but for an actual application, the results would be fetched out of the database.

I hope this explanation for creating a simple REST API was easy to understand. 

The objective is to show you what an actual REST API is. 

Now that we know what REST API is, let us understand what a GraphQL API is all about. 

Assume we need 10 items to be fetched from the kitchen. 

With REST API , we will need to tell the waiter multiple times to get different items. 

We will be making multiple calls to the application on the other end – which is mostly a database.

We solve this by creating a GraphQL API. A GraphQL API will be able to fetch all what we need in a single call. 

GraphQL follows WYAIWYG pattern – What You Ask Is What You Get.

To understand this, let us first build a simple GraphQL API. This is not a comprehensive tutorial on GraphQL APIs and hence we won’t be getting into its specifics. All we care about is understanding how to test API. For this, we need to visualize this animal called GraphQL. 

A simple GraphQL application 

Users — Movies — Reviews

There are multiple users. 

A user can watch multiple movies and write multiple reviews. 

We will just create a simple API to fetch the list of users. Instead of creating a database, we will just add all details to a javascript file called fakeDatabase.js and use this as our database. 

We will be using a simple GraphQL framework called graphql-yoga.

Step 1

Create a folder called GraphQLProject

cd GraphQLProject 

npm init

npm install graphql-yoga

Step 2

Create a sampleData.js file inside the src folder with the following contents. If there is no src folder, create it.

This is our sample – fake database.

Step 3

Create an index.js file within the src folder and add the following content to it.

Step 4

Now open the terminal and run the command 

node src/index.js

Our GraphQL server is running at port 4000 this time.

Open localhost:4000 in your browser

This is a user interface you can use to send queries to the GraphQL server.

We will write a simple Query to fetch all users.

This will fetch us the results as below

Congratulations. 

We just created a GraphQL API that fetches a list of users from the database, in this case a fake database.

Now let us understand how to test this. 

Testing a GraphQL API

Options: RestAssured, RestSharp, KarateTestGraphQL

Steps to test on Rest Assured 

Rest Assured for GraphQL code sample

We will be testing the GraphQL API at this link 
https://api.spacex.land/graphql/

Play around with the SpaceX GraphQL API at the above link.

The code sample can be obtained at https://github.com/maheshtestsigma/RestAssuredForGraphQL

Steps to run this code

  1. Download folder or Git clone https://github.com/maheshtestsigma/RestAssuredForGraphQL.git
  2. Open this code on Intellij IDEA or Eclipse
  3. Allow Eclipse or Intellij to import the dependencies
  4. Open the BasicGraphQLTest.java
  5. Run it

The results are as follows:

Steps to test on Rest Sharp

  1. Convert the GraphQL query into Stringified JSON format – click here to do it online
  2. Secondly, pass the converted String as Body parameters to the Request
  3. Validate the response

  1. [SetUp]
  2.       public void Setup()
  3.       {
  4.           _restClient = new RestClient(“http://localhost:4000”);
  5.       }
  6.       [Test]
  7.       public void TestGraphQL()
  8.       {
  9.          //Arrange
  10.           _restRequest = new RestRequest(“/graphql” , Method.POST);
  11.           _restRequest.AddHeader(“Content-Type”, “application/json”);
  12.           _restRequest.AddParameter(“application/json”,
  13.               “{\”query\”:”query{\n  users{\n    name\n  }\n}”,
  14.               ParameterType.RequestBody);
  15.          //Act
  16.           _restResponse  = _restClient.Execute(_restRequest);
  17.          //Assert
  18.          //do validation
  19.           Console.WriteLine(“Printing results for fun : “+_restResponse.Content);
  20.           }

Steps to test on TestGraphQL

Add the below maven dependency to your Java project and you are done.


Test automation made easy

Start your smart continuous testing journey today with Testsigma.

SHARE THIS BLOG

RELATED POSTS