React-apollo: Could not find "client" in the context of ApolloConsumer when using react-apollo 2.5.3 with MockedProvider

Created on 25 Mar 2019  路  45Comments  路  Source: apollographql/react-apollo

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:
image

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

bug confirmed

Most helpful comment

I managed to fix this error by ensuring "react-apollo" was on the same version as @apollo/react-hooks and @apollo/react-testing.

Currently using:
@apollo/react-hooks": "^3.1.2",
@apollo/react-testing": "^3.1.2",
"react-apollo": "^3.1.2"

All 45 comments

Hi there! Same case importing { withApollo } from react-apollo. Just updated to 2.5.3 this morning with the exact same output as @bkuzma.
" Invariant Violation: Could not find "client" in the context of ApolloConsumer. Wrap the root component in an ..."

Yup, I see it too - not during test. Trying to upgrade to solve the ignored "network-only" fetching issue...

I have the same issue with "react-apollo": "2.5.3" and I use react-testing-library for my tests.

I'm looking into this, and should have a fix ready shortly. We're going to move React Apollo's testing utilities to a new package when react-apollo 3 lands, to help avoid issues like this (that are caused by rollup bundle differences). More details shortly - thanks!

We got this too, and pinning "react-apollo": "2.5.2" solved the issue

Still running into this using v2.5.5. I'm not using MockedProvider. I'm running a pretty plain react-native expo project but using Offix instead of plain apollo-client. Pinning to 2.5.2 works for now.

I just tried upgrading to v2.5.5 and immediately started getting this error. Reverted back to v2.5.2 as other suggested and it solved the problem.

Hmm... I wonder if the other issues here are because in certain situations, the react-apollo used is not the .cjs version, which is what was used in the fix in #2907. E.g. if you're using the MockedProvider in a styleguide via webpack, the react-apollo that's bundled will be the .esm version, meaning the same issue rears its head in a different way.

@jure I recall receiving errors when using the MockedProvider in Storybook.

This exact error also occurs on 2.5.5 when building a production version with webpack, non-production version works as expected. Pinning to v2.5.2 works for production builds as suggested by @jgroh9 .
The production code doesn't include MockedProvider anywhere in the code.

Also happening on 2.5.6

@hwillson should another issue be opened for the most recent version (2.5.6), since this one is closed?

Same, "downgrade" to 2.5.2 fixed this issue for me as well

also happen in 3.0.1

I have same problem 3.0.1

I have same problem in 3.0.1, downgrading to 3.0.0 resolves my problem

Had the same problem at 2.5.8, upgrading to 3.0.0 fixed it.

Echoing the same issue. I ran npm i to update some packages and started having this issue, ended up locking to 3.0.0 for now.

It appears this issue also exists in 3.1.0.

Hi, for people stuck like me: if you use [email protected], you also need to import MockedProvider from react-apollo/test-utils, otherwise you still get this issue.
Conversely, if you use v3.x.x, you need to import MockedProvider from the newer @apollo/react-testing instead.

Also broken for me in 3.1.0 on the latest version of react (16.9.0).

Downgrading to 3.0.0 worked as well for me

I had the same issue, bumping these to the same version fixed it:

"@apollo/react-components": "^3.1.0",
"@apollo/react-hooks": "^3.1.0",
"@apollo/react-testing": "^3.1.0",

@CarlGranstrom Thanks, my issue was that react-hooks and react-testing were on separate versions. Bumping both to 3.1.0 fixed the problem. 馃帀

@CarlGranstrom those ^ might mislead someone. carats in package.json

Having this issue on 3.1.1, all packages are locked at the same version

I have an issue with this as well in testing.
We are using
@apollo/react-hooks": "^3.1.1",
@apollo/react-testing": "^3.1.2",
"react-apollo": "^2.0.4"
We are trying to migrate the old code slowly to hooks

I managed to fix this error by ensuring "react-apollo" was on the same version as @apollo/react-hooks and @apollo/react-testing.

Currently using:
@apollo/react-hooks": "^3.1.2",
@apollo/react-testing": "^3.1.2",
"react-apollo": "^3.1.2"

I upgraded @apollo/react-hooks and react-apollo to ^3.1.2, still had issue, I was wondering if it caused by I also have react-apollo-hooks under ^0.5.0 in package.json

re-install the version back to ^3.0.0 solves the issue

I have the same issues. But I managed to fix it by the following steps
1 rm -rf node_modules
2 npm install react-apollo
3 npm install @apollo/react-testing

Reason:
when installing react-apollo, the following libs will be added automatically
"@apollo/react-common": "^3.1.3",
"@apollo/react-components": "^3.1.3",
"@apollo/react-hoc": "^3.1.3",
"@apollo/react-hooks": "^3.1.3",
"@apollo/react-ssr": "^3.1.3"
and then you can just add @apollo/react-testing with the same version of above packages.

thanks @rickzant, deleting node_modules and reinstalling these two libraries worked for me.

I got this error after adding @apollo/react-testing while @apollo/react-hooks has already been in the project for some time.

Updating @apollo/react-hooks to match the same version of @apollo/react-test solved the issue for me. (both now 3.1.3)

i have everything on 3.1.3 and i'm seeing this error. had to go down to 3.0.0 on everything to get past it for now.

I just wanted to chime in and say that my fix was to replace 'react-apollo-hooks' (deprecated) with '@apollo/react-hooks'.

I found I got my error because of mixed import of ApolloProvider, userQuery. ApolloProvider is imported from react-apollo, userQuery from react-hooks; after all imported from react-hooks, the error disappeared.

Matching semver for @apollo/react-hooks and @apollo/react-testing versions (3.1.3) fixed this error for me.

Fixed I changed all to use ''@apollo/client' instead 'react-hooks'

I changed everything over to @apollo/client too and it worked.

For some reason, adding react-test-renderer to my devDependencies fixed the problem

After having delete all node_modules and reinstalled react-apollo and @apollo/react-testing, after being sure that they are all ^3.1.3, tried @apollo/client, and everything else, I am still having this error

I believe mixing usage of react-apollo and @apollo/react-hooks is one of reasons.
I'm testing the following solution to have two ApolloProviders, which makes it work.

import { ApolloProvider } from "react-apollo";
import { ApolloProvider as ApolloHookProvider } from '@apollo/react-hooks';
...
<ApolloProvider client={client}>
        <ApolloHookProvider client={client}>
               {component is mixing import { useQuery } from '@apollo/react-hooks';
                or using import { Query } from "react-apollo"; }
        </ApolloHookProvider>
</ApolloProvider>

I want use both with hook and component like @kai-chu mentioned but I tried your tip still error like title. How to fix it?

@huykon can u tell me the versions of both so that I can check as well.

I have a solution, that works for me in 100% cases. I use @apollo/react-hooks Copy source code from mockedProvider and change ApolloProvider from @apollo/react-common to

import {ApolloProvider} from "@apollo/react-hooks"

I faced this issue.

I'm using:

@apollo/react-common 3.1.4
@apollo/react-hooks 3.1.3
@apollo/react-testing 3.1.4 ==> to use `MockedProvider`

My fix was to make sure to use at least react-hooks 3.1.5.

@apollo/react-hooks ^3.1.5

Then that error suddenly disappears.

Was this page helpful?
0 / 5 - 0 ratings