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.
Asked
Active
Viewed 1.3k times
13

Dan Dascalescu
- 143,271
- 52
- 317
- 404

Tsuna
- 2,098
- 6
- 24
- 46
2 Answers
26
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);
});

Audwin Oyong
- 2,247
- 3
- 15
- 32

Dora
- 6,776
- 14
- 51
- 99
-
1nice this does work, thx a lot. I even tried using `graphql-request` which doesn't work as good as expected – Tsuna Apr 24 '18 at 19:53
-
Were you able to have this work with a mutation? I can't seem to work it out. Any ideas? – james emanon Jun 22 '18 at 20:14
-
1@jamesemanon this works with mutation too, the same as query. Do you want to make a post so I can give you sample codes? – Dora Jun 23 '18 at 17:06
-
Yeah, that would be great if you could! Also, I'm trying to figure out how to do a react-dropzone "click" image upload. This seems to be an issue with cypress, no? – james emanon Jun 24 '18 at 06:22
-
1@jamesemanon give me the URL of your question post so I can give you a sample code. As for image upload, I am not that far yet but maybe you can take a look at these two posts which I hope would help. https://stackoverflow.com/questions/47074225/how-to-test-file-inputs-with-cypress and https://github.com/cypress-io/cypress/issues/170 – Dora Jun 25 '18 at 16:11
-
1https://stackoverflow.com/questions/51012988/cypress-w-graphql-having-issues-getting-auth-with-testing-via-ui-better-way-t – james emanon Jun 25 '18 at 17:14
2
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);
});

Christine Urban
- 241
- 2
- 5