Testing Graphql with Cypress

Graphql is a query language for API. GraphQL gives you what you ask for what you want in a single query.

Pre-requisites

  • Idea how to write Graphql query

  • The idea on how cy.request works. For more refer to documentation https://docs.cypress.io/api/commands/request

  • You can use open source graphql playground to practice queries https://api.spacex.land/graphql/.

  • We will be using this open-source API to automate using Cypress.

Writing Query

We will be seeing very super simple query to automate

// Some code

{
users(limit: 2) {
id
name
rocket
}
}

This query will return two users from the server. Id in output response will be unique always and name and rocket can be any random data.

The Output will look something like this

// Some code
{
"data": {
"users": [
{
"id": "2f553874-6dbb-4cf8-b86e-dd76d2ee24fd",
"name": "sone random name",
"rocket": "some random rocket"
},
{
"id": "63227b88-c031-4bba-a39c-ae400c427727",
"name": "sone random name",
"rocket": "some random rocket"
}
]
}
}

Writing Spec to test Query

Create custom command to get user data in support/command.js

// Some code

Cypress.Commands.add('getUserInfo', (query : string, url: string) => {
if (!query) throw new Error('You need to provide valid query string');
if (!url) throw new Error('You need to provide valid endpoint');
cy.request({
url: url,
method: 'POST',
headers: {
'Content-Type': 'application/json',
},
body: {
query: query,
},
}).then(({ body }) => {
return body;
});
});

This method will be accepting query that needs to be tested and the URI and return the response body.

Writing specs

// Some code
it('Test to fetch users from spacex endpoint', () => {
const query = `{
users(limit: 2) {
id
name
rocket
}
}`;
cy.getUserInfo(
query,
'https://api.spacex.land/graphql/'
).then(($data) => {
expect($data.data.users).to.have.length(2);
});
});

This spec will make a request to the Spacex endpoint and assert the response. As we are requesting data from the server for 2 users, the output response should have 2 users present in it.

Last updated

Was this helpful?