1

I'm working on a React project that uses Storybook to mock components. We recently introduced Apollo react hooks (i.e. useQuery) to fetch data for some components. Example:

const Component = () => {
  const { loading, error, data } = useQuery(GET_THING);
  if (loading) return 'Loading!';
  if (!loading && error) return 'Error!';
  return <ComponentChild data={data} />;
}

export default Component;

How can I mock up <Component /> in Storybook? The documentation I can find seems to rely on Apollo <Query /> components rather than hooks.

Or is the answer simply to move these data-fetching steps into parent "wrapper" components and only mock the child component? I'd rather not do that, because there are cases in which I'd like to mock a parent component that has, for example, a grandchild component with its own useQuery hook. Pulling all the downstream data-fetching into a wrapper way up in the component hierarchy feels like a violation of the principle that things should be as atomistic and modular as possible.

ACPrice
  • 667
  • 2
  • 10
  • 25

1 Answers1

0

You can wrap your Component in a MockedProvider:

import { MockedProvider } from '@apollo/react-testing';

const mocks = [
  {
    request: {
      query: GET_THING,
    },
    result: {
      data: {
        yourData: { name: 'Storybook Data' },
      },
    },
  },
];

<MockedProvider mocks={mocks}>
    <Component />
</MockedProvider>,

See: https://www.apollographql.com/docs/react/development-testing/testing/#mockedprovider

David
  • 743
  • 4
  • 7
  • Oh, very nice, thanks! Not sure how I missed that. Will try it out. – ACPrice Apr 10 '20 at 01:08
  • Didn't work for me. data is never returned, see https://github.com/apollographql/react-apollo/issues/3967 – MLyck May 13 '20 at 20:03
  • 1
    I think the problem is, that the data structure you return as a mock, does not match the query data structure. I was able to get back the data, when returning it in the exact same structure as in the query. See: https://codesandbox.io/s/determined-villani-gv98t?file=/src/App.js – David May 15 '20 at 02:02