Jest测试Apollo Provider报错:TypeError: this.client.watchQuery is not a function
Hey there! Let's work through these two Apollo Client testing issues you're facing step by step.
First Error: Invariant Violation (Missing Client Context)
The initial error you hit:
Invariant Violation: Could not find "client" in the context of Query or as passed props. Wrap the root component in an
This happens because your <MandateBatch> component uses Apollo Client features (like Query components or useQuery hooks) but wasn't wrapped in an <ApolloProvider> that provides a client instance to the React context. You already took the right first step by adding the provider in your test—now let's fix the second error blocking you.
Second Error: TypeError (watchQuery is not a function)
The follow-up error:
TypeError: this.client.watchQuery is not a function
This almost always means the clientForApollo you're passing to <ApolloProvider> isn't a valid Apollo Client instance (real or properly mocked). Here are two reliable fixes:
Option 1: Use Apollo's Official Mock Client (Recommended)
For Apollo Client 3+, use the MockApolloClient from the official testing package to create a valid mock client. This ensures all required methods like watchQuery exist out of the box:
import { MockApolloClient } from '@apollo/client/testing'; import { InMemoryCache } from '@apollo/client'; // Initialize a proper mock client const clientForApollo = new MockApolloClient({ cache: new InMemoryCache(), });
You can also add mocked query responses using setRequestHandler if your component makes specific data requests.
Option 2: Manually Mock the Client (For Simple Use Cases)
If you need a lightweight manual mock, make sure to define every client method your component uses as a function (even if they're empty mocks):
// Manual mock with required methods implemented const clientForApollo = { watchQuery: jest.fn(() => ({ subscribe: jest.fn(), result: jest.fn().mockResolvedValue({ data: {} }), // Add other methods your component relies on (query, mutate, etc.) })), };
Never pass an empty object or incomplete mock—Apollo expects certain core methods to exist on the client instance.
Double-Check Your Test Setup
Confirm your clientForApollo is properly initialized before passing it to the provider. Your test snippet is on the right track, just ensure the client is valid:
it('should close the overlay when the close button is clicked', () => { // Ensure clientForApollo is initialized correctly here const mandateBatchWrapper = mount( <ApolloProvider client={clientForApollo}> <MandateBatch data={data} // Add any other required props for your component /> </ApolloProvider> ); // Rest of your test logic });
By fixing the clientForApollo instance to be a valid mock or real Apollo Client, both errors should be resolved.
内容的提问来源于stack exchange,提问作者sonal

