apollo-client-integrations: Help understanding this error - "Error: ApolloNextAppProvider cannot be used outside of the Next App Router!" in unit tests

Hello!

We’ve been using @apollo/experimental-nextjs-app-support for a few months now with no issue; however, after the update from v0.8.0 to v.0.9.0+ we have breaking unit tests with this error: Error: ApolloNextAppProvider cannot be used outside of the Next App Router!

This seems to be related to how we test components that require the ApolloWrapper/Provider. For context, we’re using Mock Service Worker, Vitest, Next App router. We have a custom renderer function as a testing utility that allows us to wrap components in Providers that might be needed. In many of our cases we need to mount components with the ApolloWrapper so we can mock graphql calls inside our tests. Below I will add the error output that we are seeing. I will also post some code snippets and the versions we’re running.

The error we see are these:

Error: Error: Uncaught [Error: ApolloNextAppProvider cannot be used outside of the Next App Router!]
    at reportException (...node_modules/jsdom/lib/jsdom/living/helpers/runtime-script-errors.js:66:24)
    at innerInvokeEventListeners (...node_modules/jsdom/lib/jsdom/living/events/EventTarget-impl.js:353:9)
    at invokeEventListeners (...node_modules/jsdom/lib/jsdom/living/events/EventTarget-impl.js:286:3)
    at HTMLUnknownElementImpl._dispatch (.../node_modules/jsdom/lib/jsdom/living/events/EventTarget-impl.js:233:9)
    at HTMLUnknownElementImpl.dispatchEvent (...node_modules/jsdom/lib/jsdom/living/events/EventTarget-impl.js:104:17)
    at HTMLUnknownElement.dispatchEvent (...node_modules/jsdom/lib/jsdom/living/generated/EventTarget.js:241:34)
    at Object.invokeGuardedCallbackDev (...node_modules/react-dom/cjs/react-dom.development.js:4213:16)
    at invokeGuardedCallback (.node_modules/react-dom/cjs/react-dom.development.js:4277:31)
    at beginWork$1 (...node_modules/react-dom/cjs/react-dom.development.js:27451:..7)
    at performUnitOfWork (.node_modules/react-dom/cjs/react-dom.development.js:26560:12)

Error: The above error occurred in the <ManualDataTransportSSRImpl> component:

    at ManualDataTransportSSRImpl (/node_modules/@apollo/client-react-streaming/dist/manual-transport.ssr.js:113:3)
    at ApolloProvider (/node_modules/@apollo/client/react/context/ApolloProvider.js:6:21)
    at WrappedApolloProvider3 (node_modules/@apollo/client-react-streaming/dist/index.ssr.js:311:5)
    at ApolloProvider (/.../ApolloProvider.tsx:36:27)
    at AllTheProviders (.../config/react_testing_library/test_utils.tsx:7:28)

Consider adding an error boundary to your tree to customize error handling behavior.
Visit https://reactjs.org/link/error-boundaries to learn more about error boundaries.

The strategy we use for simplifying the testing boilerplate for Wrappers/Providers comes right from the RTL docs for creating a custom renderer. This has worked thus far perfectly. After the version bump, this render function is throwing the error mentioned above.

When inside the unit test file, if I remove this custom render function and replace it with the RTL render function and I don’t mount ApolloWrapper, my tests will pass, provided that I change the mocking structure of the network calls.

// ./test_utils
import { render, RenderOptions } from '@testing-library/react';
import { ReactElement, ReactNode } from 'react';
import ApolloWrapper from '@/.../ApolloProvider';

const AllTheProviders = ({ children }: { children: ReactNode }) => {
  return (
    // Add any providers for tests here
    <ApolloWrapper>{children}</ApolloWrapper>
  );
};

const customRender = (ui: ReactElement, options?: RenderOptions) =>
  render(ui, { wrapper: AllTheProviders, ...options });

// re-export everything
export * from '@testing-library/react';

// override render method
export { customRender as render };

In our tests look like this. All the tests that we have that require the ApolloWrapper/Provider fail with the error.

import { render, screen } from 'config/react_testing_library/test_utils';
import Component from '@/components/Component';

describe('Component', () => {
  it('should render Component item', () => {
    render(<Component />);
    expect(screen.findAllByRole('test')).toBeDefined();
  });

});

Here’s what our ApolloProvider looks like for additional context. The implementation still seems to work locally. We’re just having issues with our tests after the version.


'use client';
import { onError } from '@apollo/client/link/error';

import { ReactNode } from 'react';
import { ApolloLink, HttpLink } from '@apollo/client';
import {
  ApolloNextAppProvider,
  NextSSRInMemoryCache,
  NextSSRApolloClient,
  SSRMultipartLink,
} from '@apollo/experimental-nextjs-app-support/ssr';

export const makeClient = () => {
  const httpLink = new HttpLink({
    uri: process.env.URI,
  });

  const errorLink = onError(({ graphQLErrors, networkError, operation }) =>
    ... // parsing
  );

  return new NextSSRApolloClient({
    // cache knows how to store the normalized cache in a way that can be then reused by the ApolloNextAppProvider to restore the cache on the browser side
    cache: new NextSSRInMemoryCache(),
    link:
      typeof window === 'undefined'
        ? ApolloLink.from([
            // use this with stripDefer set to true so that fragments are marked with the @defer directive from your queries during SSR
            new SSRMultipartLink({
              stripDefer: true,
            }),
            httpLink,
          ])
        : ApolloLink.from([errorLink, httpLink]),
    name: HELLO,
    version: process.env.ENV_VAR,
  });
};

const ApolloProvider = ({ children }: { children: ReactNode }) => {
  // provider ensures that all client components have access to the same Apollo client instance by sharing it
  return <ApolloNextAppProvider makeClient={makeClient}>{children}</ApolloNextAppProvider>;
};

export default ApolloProvider;

// ./package.json

    "@apollo/client": "^3.9.11",
    "@apollo/experimental-nextjs-app-support": "^0.10.0",
    "react": "18.2.0",
    "react-dom": "18.2.0",
    "next": "^14.2.1",
    "graphql": "^16.8.1",
    "@testing-library/jest-dom": "^6.4.2",
    "@testing-library/react": "^15.0.2",
    "@vitejs/plugin-react": "^4.2.1",
    "@vitest/coverage-v8": "^1.5.0",
    "@vitest/ui": "^1.3.1",
    "msw": "^2.2.3",

Thanks! Let me know if I should add more context.

About this issue

  • Original URL
  • State: closed
  • Created 3 years ago
  • Comments: 16 (8 by maintainers)

Most upvoted comments

@phryneas @kettanaito it looks like this works! Thanks so much for jumping in here.

Just for context in case anyone reads this thread, I updated both packages and then added the browser resolve condition to my vitest.config.

// package.json
"@apollo/experimental-nextjs-app-support": "^0.10.1",
...
  "msw": "^2.3.0",
// vitest.config.ts

export default defineConfig({
  resolve: {
    // This line is important so the "browser build" of dependencies is used
    // and not the "SSR build", which would contain "streaming-to-the-browser"
    // specific code
    conditions: ['browser'],
  },

msw@2.3.0 has been released, including the fix for this. Please update and let me know!

Since it’s working for you now, I’m gonna close the issue 😃

Also worth mentioning, despite setting "browser" in vitest.config.js, Vite is smart and will use node export condition as the fallback since the browser condition is an explicit null for msw/node. Keep that in mind. Not all tools have that fallback mechanism. If they don’t you have to provide it yourself.

This has been released as 0.10.1 on our side, but we still need to verify the full story once the msw release is out, so keeping this open 😃

The changes are not ready yet. Wait for the next MSW minor release until trying anything. I need to wrap a few things and then the package will be there.

You will still need resolve.conditions:['browser'] - it’s just that MSW now supports that in vitest.

I am confused about that dist/ssr/next.ssr.js file in your error message. I’m pretty sure we never had a file with that name, I just went through a bunch of versions of the package.

Could you please change ^0.0.0-commit-ef5e30b to 0.0.0-commit-ef5e30b? The ^ will just pick up anything that is alphabetically higher, which could be any other pull request.

We’ve had a fantastic discussion with @phryneas and we’ve found a solution to this. He’s working on the pull requests, I will review those and release the fix shortly. Stay tuned.