乐闻世界logo
搜索文章和话题

How to stub a call to graphql using cypress?

1个答案

1

When using Cypress for frontend automated testing, intercepting and simulating GraphQL calls is a common technique that helps verify the application's behavior under various scenarios. Below is a step-by-step guide and example demonstrating how to intercept GraphQL calls with Cypress.

Step 1: Setting Up the Interceptor

First, you need to set up an interceptor in your Cypress test to capture HTTP calls to GraphQL. Since GraphQL typically sends requests using the POST method, you can use the cy.intercept() method to intercept these requests.

javascript
describe('GraphQL Interception', () => { beforeEach(() => { cy.intercept('POST', '/graphql', (req) => { // Check if the request body contains a specific GraphQL operation name if (req.body.operationName === 'GetUserData') { // Simulate a response req.reply({ data: { user: { id: '1', name: 'Alice', email: 'alice@example.com' } } }); } }).as('graphql'); }); it('loads user data', () => { // This triggers the GraphQL call, such as visiting a page or loading a component cy.visit('/user-profile'); // Verify that the interceptor successfully captured the request cy.wait('@graphql').its('response.body').should('have.property', 'data'); cy.get('.user-name').should('contain', 'Alice'); // Assuming the returned data is displayed in an element on the page }); });

Step 2: Checking Request Content and Simulating Responses

Within cy.intercept(), you can access the request object req, allowing you to modify the response based on the request body content (e.g., operation name or query string). In the example above, we check if the operation name is GetUserData; if it matches, we send a simulated successful response.

Step 3: Testing and Verification

In the test case, we trigger the GraphQL call by visiting a page or performing an action, then use cy.wait() to confirm that our interceptor captured the request and can validate changes to page elements or states based on the simulated response.

Example Explanation

In the example above, we assume a GraphQL request for user data and simulate a response containing user data. The test ensures that when the request is intercepted and returns simulated data, the page correctly displays the user's name.

By doing this, you can control and test the application's behavior under various backend data and states without relying on real backend services. This is highly beneficial for quickly iterating and identifying frontend issues during development and testing phases.

2024年6月29日 12:07 回复

你的答案