'How can I pass the `Graphql` mutation query in cypress req and get the data back in response?

How can I pass the Graphql mutation query in cypress req and get the data back in the response ? I am getting an error like Validation error of type FieldUndefined: Field 'mutation' in type Query undefined @CreateOrganizationTeam '

let author = 'Main Author';
let teamname = 'Green Team';
let query = `mutation CreateOrganizationTeam($input: {category: "", author:${author}, isActive: false, orgId: 10, teamName: ${teamname}}) {
  createOrganizationTeam(input: $input) {
    author
    isActive
    teamName
  }
}`;



/* Cypress test to verify the GraphQl response data  */
Then('I access the graphQL end point', () => {
  cy.request({
    method: 'POST',
    url: 'https://some-end-point/api',
    headers: {
      'content-type': 'application/json'
    },
    body: JSON.stringify({
      query,
      variables: {
        input: {
          author,
          isActive,
          teamName,
        }
      }
    })
  }).then((response)=>{
    console.log("GraphQL resp output:"+response.body.data);
  });
});


Solution 1:[1]

Another way of doing it is create the field specifier separately, that way you can see exactly why you need to quote the string values.

const fields = {
  category: "", 
  author: "Main Author", 
  isActive: false, 
  orgId: 10, 
  teamName: "Green Team"
}

let query = `mutation CreateOrganizationTeam($input: ${JSON.stringify(fields)) {...

Solution 2:[2]

I think you need to quote the templated variables,

let query = `mutation CreateOrganizationTeam($input: {  
  category: "",   
  author:"${author}",       // quotes around the templated string
  isActive: false,   
  orgId: 10,   
  teamName: "${teamname}"   // quotes around the templated string
}) {

In the response you may need .json()

.then(r => r.json())
.then(data => {
  console.log("GraphQL resp output:", data);
})

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Jumaane
Solution 2 Fody