How to Mock Apollo Client GraphQL Calls for E2E Testing in Next.js v12?

Hi everyone,

I’m working on a Next.js v12 application that uses Apollo Client for GraphQL operations, and I’m struggling with mocking GraphQL calls during E2E testing while maintaining a single Apollo Client instance.

My Current Setup:

  • Next.js v12 application with Apollo Client
  • Using getInitialProps for server-side data fetching
  • Client-side components that make additional GraphQL queries using Apollo hooks
  • The Apollo cache gets serialized from server to client during hydration
  • MSW (Mock Service Worker) is not an option for us since it is not able to intercept SSR calls at least in NextJS v12.
  • Our E2E tests are written using the WebdriverIO framework.

The Challenge:

I need to mock GraphQL calls for E2E testing, but I’m running into the issue that server-side calls (during SSR/SSG) and client-side calls happen in different execution contexts.

What I Need:

I want to mock both server-side GraphQL calls (that happen during getInitialProps/getServerSideProps) and client-side GraphQL calls (that happen in React components) using a single, unified mocking approach that maintains the same Apollo Client instance throughout the test.

Specific Questions:

  1. Is there a way to mock GraphQL responses at the network level so that both server-side and client-side calls from the same Apollo Client instance receive mocked data?
  2. Can I intercept Apollo Client’s HTTP requests during testing without compromising the single-client architecture?
  3. Are there any recommended patterns for E2E testing Next.js v12 applications with Apollo Client that preserve the unified client instance behavior?
  4. Given that MSW is not available to us, what alternative approaches exist for mocking at the network/transport layer level?
  5. Has anyone worked with custom Apollo Links for testing purposes that could intercept and mock responses while maintaining the single client instance? Specifically, I’m wondering if SchemaLink could be a viable option, and how effective it would be for mocking client-side calls in this unified approach.

The goal is to have integration tests that accurately reflect how my application behaves in production, where server-rendered data and client-side queries all flow through the same Apollo Client instance and share the same cache.

Any guidance or examples would be greatly appreciated!

Thanks in advance!