GraphQL Testing with @playwright/test

Cerosh Jacob
2 min readSep 19, 2023

--

Photo by Markus Spiske on Unsplash

GraphQL queries allow for efficient and flexible data retrieval from servers, avoiding over-fetching and under-fetching problems. They use the query keyword and dynamic values to specify the data shape and depth. Mutations modify server-side data using the mutation keyword and specified fields and data. They can include client variables for dynamic values.

Types define data shapes that can be queried or mutated and are a crucial part of the schema that specifies API data and operations. They are defined using SDL or programming language syntax.

Fields are units of data queried within an object type, representing object properties. Each object type in the schema has its fields that the client can request. With these key concepts, clients can effectively retrieve and modify data from servers.

import { test, expect } from '@playwright/test';
test('should be able to add a new Character', async ({ request }) => {
const response = await request.post('<https://rahulshettyacademy.com/gq/graphql>', {
data: {
query: `mutation{
createLocation(location:{
name:"Cerosh"
type:"Hero"
dimension:"Malayalam"
}){
id
}
}`
}
});
expect(response.ok()).toBeTruthy();
expect(response.status()).toBe(200);
});

this code defines a test case that sends a GraphQL mutation to a specified endpoint to create a new character (location) with specific properties. It then verifies that the mutation request was successful (HTTP status code 200) and checks whether the response is as expected.

test('should be able to get one character by id', async ({ request }) => {
const response = await request.post('<https://rahulshettyacademy.com/gq/graphql>', {
data: {
query: `{
location(locationId:1428){
id
name
created
}
}`
}
});
expect(response.ok()).toBeTruthy();
expect(response.status()).toBe(200);
});

this code defines a test case that sends a GraphQL query to a specified endpoint and checks whether the response is successful (HTTP status code 200) and whether it contains the expected data fields specified in the GraphQL query.

My recent publication compiled a comprehensive collection of 100 similar typescript programs. Each program not only elucidates essential Typescript concepts and expounds upon the significance of test automation but also provides practical guidance on its implementation using Playwright. This resource will undoubtedly be valuable if you look deeper into similar topics.

--

--