0
votes

I want to add a cy.signUp command to Cypress in the commands.js file. The frontend app uses Graphql with React to communicate with the backend app.

I can't figure out a way to use a mutation inside of the commands.js file since the documentation only offers to use it with React.

How can I use graphql inside of this file to add a new command based on a mutation?

2
Does this answer your question? Call GraphQL endpoints using Cypress .request - jonrsharpe
Or stackoverflow.com/q/51012988/3001761 maybe - basically look at the request that's being made and create the same thing with cy.request. - jonrsharpe
@jonrsharpe I saw that post, but it's a workaround, not a solution actually using Graphql - Graham Slick
What do you think "actually using Graphql" means? It's just a query language, in this case using HTTP as the transport and likely following the conventions in graphql.org/learn/serving-over-http. - jonrsharpe
Based on the link I guess by "the actual mutation" you mean Apollo; note that's just a JS library for creating the query with various clients to make the requests, I don't know if there's a Cypress client to use cy.request for transport. You could decouple your tests from GraphQL entirely by using the UI to log in - I know the Cypress folks consider that an anti-pattern, but your users shouldn't have to care how you're organising the API so neither should your E2E tests. - jonrsharpe

2 Answers

0
votes

Here is what has worked for me:

const mutation = `
mutation {
  // whatever you have for the mutation
}
`
cy.request({
  url: '/',
  method: 'POST',
  body: {
    query: mutation
  }
});
0
votes

I recently had this issue and I was able to resolve this by adding a command in the command.js in cypress's support folder.

Cypress.Commands.add('apiMutation', (mutations) => {
    cy.request({
        method:'POST',
        url:'api/graphql',
        body: { query : "mutation" + mutations }         
    })
})

The problem is that cy.request requires you to have a query inside the body or ofcourse that's what I feel.

You can override this by add the word mutation inside the body before the actual query(mutation). Like below

body: { query : "mutation" + mutations }

And you can make your request like:

describe("Reservation Validations", () => {
     it("should return a valid addAdditions mutation", () => {
        cy.apiMutation('{addAdditions(reservationId: 1001 reservedResourceId: 100 additions: { resourceId: 10 quantity: 12 }){resourceId  type resortArticle}}'
        ).then((Response) => {
            expect(Response.body.data).to.have.property("addAdditions")
            expect(Response.body.data.addAdditions).to.not.be.undefined
        })
    })
})