question-mark
Stuck on an issue?

Lightrun Answers was designed to reduce the constant googling that comes with debugging 3rd party libraries. It collects links to all the places you might be looking at while hunting down a tough bug.

And, if you’re still stuck at the end, we’re happy to hop on a call to see how we can help out.

`import { MockedProvider } from '@apollo/client/testing';` throws error when run with `jest`

See original GitHub issue

Intended outcome: To test a Next.js <Page /> component which is nested under an <ApolloProvider /> using a <MockedProvider />.

// tests/pages/index.test.tsx
import { render } from '@testing-library/react';
import { MockedProvider } from '@apollo/client/testing';
import IndexPage from 'src/pages/index';

describe('pages: /', () => {
  it('renders without crashing', () => {
    const { getByText } = render(
      <MockedProvider>
        <IndexPage characters={[{ id: '1', name: 'Rick' }]} />
      </MockedProvider>,
    );

    expect(getByText('Rick')).toBeInTheDocument();
  });
});
// src/pages/index.tsx
import React from 'react';
import { NextPage } from 'next';
import { ApolloPageContext } from 'next-with-apollo';
import { useLazyQuery } from '@apollo/client';
import CharactersQueries from 'src/lib/gql/Characters/Queries';
import { Character } from 'src/lib/gql/Characters/schema';
import { sendAppInsightsEvent } from 'src/lib/utils/Global';
import Card from 'src/components/Global/general/Card/Card';
import Button from 'src/components/Global/general/Button/Button';

export const htmlHeadTitle = 'Member App - Hub';

const getInitialProps = async (context: ApolloPageContext) => {
  const { apolloClient } = context;
  const { data } = await apolloClient.query({ query: CharactersQueries.list });

  return { htmlHeadTitle, characters: data.characters.results };
};

interface PageProps {
  characters: Character[];
}

const MemberAppHome: NextPage<PageProps> = ({ characters }) => {
  return (
    <>
      <h1>This is the Member Hub index page.</h1>
      <p>
        <span role="img" aria-label="howdy!">
          🤠
        </span>
        {' '}
        howdy!
      </p>
      <button type="button" onClick={() => sendAppInsightsEvent({ name: 'Test event' })}>
        Send test event to app insights
      </button>
      <br />
      <br />
      {characters && (
        // eslint-disable-next-line no-use-before-define
        <div style={{ display: 'flex', flexWrap: 'wrap' }}>{characters.map(CharacterCard)}</div>
      )}
    </>
  );
};

const CharacterCard = ({ id, name }: Character) => {
  const [getImage, { loading, error, data }] = useLazyQuery(CharactersQueries.getImage, {
    variables: { id },
  });

  return (
    <Card key={id}>
      {loading && (
        <>
          Loading image...
          <br />
          <progress />
        </>
      )}
      {error && (
        <pre>
          Error:
          {error.message}
        </pre>
      )}
      {data && <img src={data.character.image} alt="character" />}
      <h4>{name}</h4>
      {!data && <Button onClick={(e) => getImage()}>Load Image</Button>}
    </Card>
  );
};

MemberAppHome.getInitialProps = getInitialProps;
export default MemberAppHome;

Actual outcome:

 FAIL  tests/pages/index.test.tsx
  ● Test suite failed to run

    TypeError: Object prototype may only be an Object or null: undefined
        at setPrototypeOf (<anonymous>)

      1 | import { render } from '@testing-library/react';
    > 2 | import { MockedProvider } from '@apollo/client/testing';
        | ^
      3 | import IndexPage from 'src/pages/index';
      4 | 
      5 | describe('pages: /', () => {

      at Object.__extends (node_modules/tslib/tslib.js:69:9)
      at node_modules/@apollo/client/utilities/testing/mocking/MockedProvider.js:8:5
      at Object.<anonymous> (node_modules/@apollo/client/utilities/testing/mocking/MockedProvider.js:32:2)
      at Object.<anonymous> (tests/pages/index.test.tsx:2:1)

How to reproduce the issue: https://github.com/adam-zhu/member-hub npm i && npm run test tests/pages/index.test.tsx

Versions

"@apollo/client": "^3.2.5",
"@testing-library/dom": "^7.26.6",
"@testing-library/jest-dom": "^5.11.5",
"@testing-library/react": "^11.1.2",
"babel-jest": "^26.6.3",
"jest": "^26.6.3",
"next": "^10.0.1",
"ts-jest": "^26.4.4",
"webpack": "^4.44.1"

Issue Analytics

  • State:closed
  • Created 3 years ago
  • Reactions:8
  • Comments:12 (1 by maintainers)

github_iconTop GitHub Comments

3reactions
adam-zhucommented, Nov 20, 2020

Very interested in this. We adopted ApolloClient under the documentation’s promise that we’d be able to test our implementation.

2reactions
guiaramoscommented, Jan 13, 2021

@guiaramos Here is a super slimmed down version of the repo where I think you should be able to reproduce the error: https://github.com/tcannon91/apollo-mock-failure

I have taken over this issue from the OP. Tried to remove all extra dependencies on the repo but leave the ts config intact for debugging purposes. My team and I tried the aliasing strategy mentioned by @phegman but didn’t have any luck. I also tried to remove any aliasing code just to remove that as a dependency – we don’t have to use the aliasing if that will unblock us 😃

@tcannon91 ohh nice, I was able to fix it on your repo by doing the following changes:

jest.config.js

- moduleDirectories: ['node_modules', './'],
+ moduleDirectories: ['node_modules', 'src'],

BUT, there is a problem on @apollo/cllient current versions as described here https://github.com/apollographql/apollo-client/issues/7348

SO, to get it working, you can pin the deps to "@apollo/client": "3.2.4" and don’t forget to rm -rf node_modules && rm -rf package-lock.json and npm i

it should work fine now…

Read more comments on GitHub >

github_iconTop Results From Across the Web

Testing React components - Apollo GraphQL Docs
Using MockedProvider and associated APIs. This article describes best practices for testing React components that use Apollo Client. The examples below use Jest...
Read more >
Testing function that use useQuery @apollo/client with Jest
I am trying to unit test my function that call useQuery from @apollo/client. Here's what I have done. getPixelID.ts import { useQuery }...
Read more >
A Guide to Unit Testing React Apollo Components - DoltHub
jest.setup.ts import "@testing-library/jest-dom/extend-expect"; ... import { MockedProvider } from "@apollo/client/testing"; import { render } ...
Read more >
test suite failed to run typeerror: class extends value undefined ...
However, whenever I try to run my test suite I get the following error ... seem to import MockedProvider from @apollo/client/testing in typescript...
Read more >
Testing React components - Apollo GraphQL Docs
Components utilizing React with Apollo Client are no exception. ... dog.test.js import { MockedProvider } from '@apollo/client/testing'; // The component ...
Read more >

github_iconTop Related Medium Post

No results found

github_iconTop Related StackOverflow Question

No results found

github_iconTroubleshoot Live Code

Lightrun enables developers to add logs, metrics and snapshots to live code - no restarts or redeploys required.
Start Free

github_iconTop Related Reddit Thread

No results found

github_iconTop Related Hackernoon Post

No results found

github_iconTop Related Tweet

No results found

github_iconTop Related Dev.to Post

No results found

github_iconTop Related Hashnode Post

No results found