abhiaiyer91 / apollo-storybook-decorator

Wrap your storybook environment with Apollo Client, provide mocks for isolated UI testing with GraphQL
332 stars 34 forks source link

Idea: Save yourself from redeclaring your schema #54

Open ThisIsMissEm opened 6 years ago

ThisIsMissEm commented 6 years ago

import { print, printSchema } from "graphql";
import { introspectSchema } from "graphql-tools";

const ENDPOINT = 'https://my.graphql.example/graphql'

const fetcher = async ({ query: queryDocument, variables, operationName, context }) => {
  const fetchResult = await fetch(ENDPOINT, {
    method: 'POST',
    headers: {
      'Content-Type': 'application/json',
    },
    body: JSON.stringify({ query: print(queryDocument), variables, operationName })
  });
  return fetchResult.json();
};

const typeDefs = await = introspectSchema(fetcher).then(printSchema);

storiesOf('Apollo Client', module).addDecorator(
  apolloStorybookDecorator({
    typeDefs,
    mocks,
  })
);```

Came up with this for a coworker, but we ended up switching to MockProvider for now.
abhiaiyer91 commented 5 years ago

This is great! Especially if users have stable schemas somewhere!

abhiaiyer91 commented 5 years ago

Curious if we just show this approach or do we build it in!

ThisIsMissEm commented 5 years ago

I'd be inclined to build it in; maybe you could do something like a "record" mode which captures the responses from the origin & caches them locally on disk.

But I think being able to specify a "schema URL" would help greatly for people just getting started

abhiaiyer91 commented 5 years ago

yeah that'd be great, just need to figure out how to do async work inside a decorator!

pzi commented 4 years ago

Found this article really helpful: https://www.freecodecamp.org/news/a-new-approach-to-mocking-graphql-data-1ef49de3d491/

Using both the MockedProvider for mock data and custom Loading and Error providers for those states is quite nice.