How to use GraphQL mutation and queries for Cypress Automation tests

Bothi Palani
2 min readSep 28, 2023

--

When I was working for one of the clients, I had to use GraphQL mutation and queries in our automation tests to make it more robust and faster.

For example, if you are automating retail web application then your test has to do pre-condition setup like creating catalogue of products in each category and dummy users etc.

This can be achieved by using Front end of your application or ingesting data into the Database using API request.

We prefered to use GraphQL mutation to create the data in our automation framework.

How to setup GraphQL within Cypress Framework ?

Create a common method for GraphQL mutations ( api request )

Cypress.Commands.add('apiRequest', (body, authToken) =>
cy.request({
method: 'POST',
url: graphQLEndPoint,
headers: { Authorization: `${authToken}` },
body,
})
.then(({ status, body: resBody }) => {
expect(status).to.be.equal(200);
// It return the first value after data object. it skip the key of data.
return Object.values(resBody.data)[0];
})
);

You also need to have type definition for the apiRequest, add in the e2e.ts

apiRequest<T>(
inputs: { variables?: string; query: string },
authToken?: string,
): Cypress.Chainable<T>;

Create the GraphQL mutation in a module so it can be called from anywhere in the framework

createProduct: (
productID: string,
productName: string,
productPrice: number,
productCategry: string,
) => ({
query: `mutation createProduct($input: createProductInput!) {
createProduct(input: $input) {
id
product_id
product_name
product_price
product_category
date_created
user_created
}
}`,
variables: JSON.stringify({
input: {
product_id: productID,
product_name: productName,
product_price: productPrice,
product_category: productCategry,
},
}),
}),

Invoke the mutation to create the product, you can either store the response in a file or in an object so it can be used for the successive steps of your test.

cy.apiRequest<WithExtraBodyAndData<ProductDetails>>(
mutations.createProduct(
productId,
productName,
productPrice,
productCategry,
),
).then(response => {
expect(response.body.data.createProduct)
.to.have.property('product_id');
});

--

--

Bothi Palani
Bothi Palani

Written by Bothi Palani

Senior SDET & Test Automation Consultant

No responses yet