Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Call GraphQL endpoints using Cypress .request

I have googled cypress request with graphql but I see lots of people mentioning mock up server, stub and so on. But I am not able to find a ful example of how to use GraphQL with cy.request.

like image 625
Tsuna Avatar asked Apr 23 '18 19:04

Tsuna


2 Answers

maybe you can this this try when using cy.request pretty much like the usual way you use restful in cy.request

example your query name is findUser with variable of username your query should look something like findUser(username:"hello"){id, name} and so on

but instead of just this, you need to pass it as json if it is a query then it'll be {"query": findUser(username:"hello"){id, name}} this will actually be your body.

an example is below...

const query = `{
  findUser(username:"hello") {
    id
  }
}`;
    
cy.request({
  url: 'http://localhost/graphql/',  // graphql endpoint
  body: { query },                   // or { query: query } depending if you are writing with es6
  failOnStatusCode: false            // not a must but in case the fail code is not 200 / 400
}).then((res) => {
  cy.log(res);
});
like image 174
Dora Avatar answered Oct 21 '22 18:10

Dora


The chosen answer worked for me as soon as I added method: "post"

const query = `
  query getItems {
    items {
      items {
        id
      }
    }
  }
`;

cy.request({
  method: "post",
  url: 'http://localhost:4000/graphql',
  body: { query },
}).then((res) => {
  console.log(res.body);
});
like image 43
Christine Urban Avatar answered Oct 21 '22 19:10

Christine Urban