Ask questionsCould not find "client" in the context of ApolloConsumer when using react-apollo 2.5.3 with MockedProvider
Intended outcome:
I have a React component that makes use of <ApolloConsumer> in order to access its client render prop and explicitly call client.query when a user action occurs. In order to test my component in my Jest/Enzyme test suite, I wrap it in <MockedProvider> and mount it with Enzyme. My tests should run with no issue.
Example component:
import React, { Component } from "react";
import { graphql, ApolloConsumer } from "react-apollo";
import gql from "graphql-tag";
export const query = gql`
query ErrorTemplate {
people {
id
name
}
}
`;
class App extends Component {
constructor(props) {
super(props);
this.state = {
people: []
};
}
render() {
return (
<ApolloConsumer>
{(client) => (
<main>
<button onClick={(event) => {
client.query({
query
}).then(response => {
this.setState({ people: response.data.people });
});
}}>Fetch People</button>
<ul>
{this.state.people.map(person => <li key={person.id}>{person.name}</li>)}
</ul>
</main>
)}
</ApolloConsumer>
);
}
}
export default App;
Example tests:
import React from "react";
import { MockedProvider } from "react-apollo/test-utils";
import Enzyme, { mount } from "enzyme";
import Adapter from "enzyme-adapter-react-16";
Enzyme.configure({ adapter: new Adapter() });
import App, { query } from "./App";
const mock = {
request: {
query
},
result: {
people: [
{ id: 1, name: 'John Smith' },
{ id: 2, name: 'Sara Smith' },
{ id: 3, name: 'Budd Deey' },
]
}
};
describe("App", () => {
it("mounts", () => {
const app = mount(
<MockedProvider addTypename={false} mocks={[mock]}>
<App />
</MockedProvider>
);
});
});
Actual outcome:
My test fails with a message saying: Invariant Violation: Could not find "client" in the context of ApolloConsumer. Wrap the root component in an <ApolloProvider>.
Screenshot:

How to reproduce the issue:
Reproduction: https://github.com/bkuzma/react-apollo-error-template/tree/context-error-example
If you look at the commit history of the context-error-example branch, the single test passes in the second to last commit (412d2d57f52d2b10c1620dd2259bd8269eab74e5), but when I update react-apollo to 2.5.3 in the last commit (26474d6aab4cbdca7d9c08c9af386f4be8f0a2de), the test fails with the same error described above.
Version
Answer
questions
quentincrinon
I have the same issue with "react-apollo": "2.5.3" and I use react-testing-library for my tests.
Related questions