Back to All Questions
Question 68 of 100
Network
Advanced
How do you intercept GraphQL requests?
The Answer
GraphQL APIs typically use a single endpoint (e.g., `/graphql`). Intercept it with `page.route()` and inspect the request body to match the specific operation name, then fulfill with appropriate mock data.
Deep Dive Explanation
The `request.postDataJSON()` method parses the GraphQL request body automatically. Always use `route.continue()` as the fallback for operations you're not mocking, otherwise all unmatched GraphQL calls will hang.
example.spec.ts
test('GraphQL interception', async ({ page }) => {
await page.route('**/graphql', async route => {
const request = route.request();
const body = request.postDataJSON();
// Match by operation name
if (body?.operationName === 'GetUserProfile') {
await route.fulfill({
status: 200,
contentType: 'application/json',
body: JSON.stringify({
data: {
user: { id: '1', name: 'Mock User', email: 'mock@test.com' }
}
}),
});
} else {
// Pass through all other GraphQL operations
await route.continue();
}
});
await page.goto('/profile');
await expect(page.getByText('Mock User')).toBeVisible();
});