# Testing Graphql Mutation with Cypress

In this article, we will be seeing how we can write mutation to delete data in GraphQL.

### Pre-requisites

1. Idea how to write Graphql mutation
2. The Idea on how cy.request works. For more refer to documentation <https://docs.cypress.io/api/commands/request>&#x20;
3. 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

To delete some data, we will be needing some data on the server-side. We have already seen how we can insert data using mutation. We will be using the same query to insert data first

```yaml
mutation {
insert_users(objects: {id: "6db07512-4f09-44ab-ad13-10118f0832fa", name: "TestName",
rocket: "TestNameRocket"}){
returning{
id
name
rocket
}
}
}
```

This query uses three fields id which is of type uuid, name which of type string and rocket which is again of type string. Once this query is executed a user will be inserted with the provided field. Output will look something like this

```bash
{
{
"data": {
"insert_users": {
"returning": [
{
"id": "6db07512-4f09-44ab-ad13-10118f0832fa",
"name": "TestName",
"rocket": "TestNameRocket"
}
]
}
}
}
```

Once you have data created on the server-side or in the database lets try to delete the created data by writing graphql mutation

```bash
mutation {
delete_users(where: {id: {_eq: "6db07512-4f09-44ab-ad13-10118f0832fa"}}) {
returning {
id
name
rocket
}
}
}
```

{% hint style="info" %}
Keep in mind `id` is always unique.
{% endhint %}

{% code title="hello.sh" %}

```bash
{
"data": {
"delete_users": {
"returning": [
{
"id": "6db07512-4f09-44ab-ad13-10118f0832fa",
"name": "TestName",
"rocket": "TestRocket"
}
]
}
}
}
```

{% endcode %}

You can see output response have the data deleted related to specific user id

### Writing Spec to test Mutation Query

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

```bash
Cypress.Commands.add('performMutation', (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 mutation query that needs to be tested, the endpoint for API and returns the response body on execution. Creating a reusable method to create a unique id, name, and rocket at runtime

```bash
const uuid = function () {
var buf = new Uint32Array(4);
window.crypto.getRandomValues(buf);
var idx = -1;
return 'xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx'.replace(/[xy]/g, function (
newData
) {
idx++;
const r = (buf[idx >> 3] >> ((idx % 8) * 4)) & 15;
const v = newData == 'x' ? r : (r & 0x3) | 0x8;
return v.toString(16);
});
};
const randomstring = function () {
let finalString = '';
const CHARACTERS_STRING =
'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz';
for (let i = 0; i < 10; i++)
finalString += CHARACTERS_STRING.charAt(
Math.floor(Math.random() * CHARACTERS_STRING.length)
);
return finalString;
};
```

#### Writing specs

```bash
it('Test for deleting user using mutation for spacex', () => {
const name = randomstring();
const rocketName = randomstring();
const id = uuid();
const query = `mutation {
insert_users(objects: {id: "${id}", name: "${name}", rocket: "${rocketName}"}){
returning{
id
name
rocket
}
}
}`;
cy.performMutation(query, 'https://api.spacex.land/graphql/').then(
($data) => {
const response = $data.data.insert_users.returning[0];
expect(id).to.equal(response.id);
expect(name).to.equal(response.name);
expect(rocketName).to.equal(response.rocket);

}
);
const deleteMutationQuery = `mutation {
delete_users(where: {id: {_eq: "${id}"}}) {
returning {
id
name
rocket
}
}
}`;
cy.performMutation(deleteMutationQuery, 'https://api.spacex.land/graphql/').then(
($data) => {
const response = $data.data.delete_users.returning[0];
expect(id).to.equal(response.id);
expect(name).to.equal(response.name);
expect(rocketName).to.equal(response.rocket);
}
);
});
```

{% hint style="info" %}
This spec will create a user with a  unique id and delete the user with the same id and assert the fields in response.&#x20;

uuid : <https://www.npmjs.com/package/uuid>&#x20;

randomstring: <https://www.npmjs.com/package/randomstring>
{% endhint %}


---

# Agent Instructions: Querying This Documentation

If you need additional information that is not directly available in this page, you can query the documentation dynamically by asking a question.

Perform an HTTP GET request on the current page URL with the `ask` query parameter:

```
GET https://team-qatechtalks.gitbook.io/cypress-cookbook-edition-2/graphql/graphql-mutation.md?ask=<question>
```

The question should be specific, self-contained, and written in natural language.
The response will contain a direct answer to the question and relevant excerpts and sources from the documentation.

Use this mechanism when the answer is not explicitly present in the current page, you need clarification or additional context, or you want to retrieve related documentation sections.
