求使用Cypress .request调用GraphQL接口的完整实现示例
Using
cy.request() to Call GraphQL APIs in Cypress (Full Example) Got it, let’s walk through exactly how to send real GraphQL queries and mutations with Cypress’s cy.request() command—no mocks or stubs required. This is the full, working example you’ve been looking for.
Basic GraphQL Query Example
Say your GraphQL endpoint lives at https://your-api-domain.com/graphql, and you want to fetch a user’s details by their ID. Here’s a complete test case:
describe('GraphQL API Integration Tests', () => { it('successfully fetches a user via GraphQL query', () => { // Define your GraphQL query (you can format this for readability) const getUserQuery = ` query GetUser($userId: ID!) { user(id: $userId) { id fullName email createdAt } } `; // Send the request using cy.request() cy.request({ method: 'POST', url: 'https://your-api-domain.com/graphql', // Replace with your actual endpoint headers: { 'Content-Type': 'application/json', 'Authorization': 'Bearer YOUR_AUTH_TOKEN' // Add this if your API requires auth }, body: { query: getUserQuery, variables: { userId: 'user_123' // Replace with a valid user ID from your API } } }).then((response) => { // Assert the request returned a 200 OK status expect(response.status).to.eq(200); // Validate the returned data matches what you expect expect(response.body.data.user.id).to.eq('user_123'); expect(response.body.data.user).to.have.all.keys('fullName', 'email', 'createdAt'); // Optional: Log the response to the Cypress console for debugging cy.log('Fetched user data:', response.body.data.user); }); }); });
GraphQL Mutation Example
If you need to modify data (like creating a new user), here’s how to send a mutation with cy.request():
it('creates a new user via GraphQL mutation', () => { const createUserMutation = ` mutation CreateUser($input: CreateUserInput!) { createUser(input: $input) { id fullName email } } `; cy.request({ method: 'POST', url: 'https://your-api-domain.com/graphql', headers: { 'Content-Type': 'application/json', 'Authorization': 'Bearer YOUR_AUTH_TOKEN' }, body: { query: createUserMutation, variables: { input: { fullName: 'Jane Smith', email: 'jane.smith@example.com', password: 'securePassword123' } } } }).then((response) => { expect(response.status).to.eq(200); expect(response.body.data.createUser.fullName).to.eq('Jane Smith'); expect(response.body.data.createUser.email).to.eq('jane.smith@example.com'); // Make sure no GraphQL errors were returned (even 200s can have errors!) expect(response.body.errors).to.be.undefined; }); });
Key Tips for Success
- Headers Matter: Always include
Content-Type: application/json—GraphQL APIs expect JSON-formatted request bodies. Add anAuthorizationheader if your API uses tokens or other auth methods. - Use Variables: Avoid hardcoding values directly in your queries/mutations. Variables make tests more reusable and easier to maintain.
- Check for GraphQL Errors: Even if the HTTP status is 200, the GraphQL operation might fail (e.g., invalid input). Always check
response.body.errorsto catch these issues. - Debugging: Use
cy.log()orconsole.log()inside the.then()block to inspect response data when troubleshooting.
内容的提问来源于stack exchange,提问作者Tsuna
相关产品推荐
相关产品推荐

