Code Monkey home page Code Monkey logo

storybook-addon-relay's Introduction

storybook-addon-relay

npm version

A Storybook add-on to write stories for Relay components.

github_demo.webm

Installation

Install the @imchhh/storybook-addon-relay package using the package manager of your choice:

yarn add -D @imchhh/storybook-addon-relay

Add @imchhh/storybook-addon-relay to the addons list in your .storybook/main.c?(j|t)s file:

const config: StorybookConfig = {
  addons: [
    // ...
    '@imchhh/storybook-addon-relay',
  ],
};

Usage

Add a relay field to your story's parameters.

export const Default = {
  parameters: {
    relay: {
      query: graphql`...`,
      getReferenceEntry: (data) => ['data', data.node],
      variables: {},
      mockResolvers: {},
    },
  },
};
  • query: A GraphQLTaggedNode returned by the Relay's graphql template literal. You should pass the query operation that uses the @relay_test_operation directive.
  • getReferenceEntry: A function that returns an entry to be added to the story's args. It takes the result of the useLazyLoadQuery hook with the query passed as a parameter and returns an entry to be added to the story's args.
  • variables: Optional. Variables to pass to the query.
  • mockResolvers: Optional. A mock resolver object passed to the relay-test-utils' MockPayloadGenerator.generate function.
  • generateFunction: Optional. A function to execute instead of the default MockPayloadGenerator.generate function.

Here is a minimal example:

// UserAvatar.tsx
export const UserAvatar = (props) => {
  const data = useFragment(
    graphql`
      fragment UserAvatar on User {
        profileImageUrl
      }
    `,
    props.user,
  );

  return <img src={data.profileImageUrl} alt="" />;
};

// UserAvatar.stories.tsx
import { StoryObj } from '@storybook/react';
import { graphql } from 'react-relay';
import { UserAvatar } from './UserAvatar';

export default {
  component: UserAvatar,
};

export const Default: StoryObj = {
  parameters: {
    relay: {
      query: graphql`
        query UserAvatarStoryQuery @relay_test_operation {
          node(id: "test-id") {
            ... on User {
              ...UserAvatar
            }
          }
        }
      `,
      getReferenceEntry: queryResult => ['user', queryResult.node],
      mockResolvers: {
        User: () => ({
          profileImageUrl: 'https://source.unsplash.com/random/400x400',
        }),
      },
    },
  },
};

TypeScript (Optional)

If you are using TypeScript 4.9 or later, you can use the WithRelayParameters interface and the satisfies keyword to get type-safe:

// UserAvatar.stories.tsx
import { WithRelayParameters } from '@imchhh/storybook-addon-relay';
import { StoryObj } from '@storybook/react';
import { graphql } from 'react-relay';
import { UserAvatarStoryQuery } from '~/path/of/relay/artifacts';
import { UserAvatar } from './UserAvatar';

export default {
  component: UserAvatar,
};

export const Default: StoryObj = {
  parameters: {
    relay: {
      query: graphql`
        query UserAvatarStoryQuery @relay_test_operation {
          node(id: "test-id") {
            ... on User {
              ...UserAvatar
            }
          }
        }
      `,
      // Now `queryResult` is typed!
      getReferenceEntry: queryResult => ['user', queryResult.node],
      mockResolvers: {
        User: () => ({
          profileImageUrl: 'https://source.unsplash.com/random/400x400',
        }),
      },
    } satisfies WithRelayParameters<UserAvatarStoryQuery>,
  },
};

And you can pass the Resolvers type, which generated via GraphQL Code Generator, as the second type parameter to WithRelayParameters.

// UserAvatar.stories.tsx
import { WithRelayParameters } from '@imchhh/storybook-addon-relay';
import { StoryObj } from '@storybook/react';
import { graphql } from 'react-relay';
import { Resolvers } from '~/path/of/codegen/generated';
import { UserAvatarStoryQuery } from '~/path/of/relay/artifacts';
import { UserAvatar } from './UserAvatar';

export default {
  component: UserAvatar,
};

export const Default: StoryObj = {
  parameters: {
    relay: {
      query: graphql`
        query UserAvatarStoryQuery @relay_test_operation {
          node(id: "test-id") {
            ... on User {
              ...UserAvatar
            }
          }
        }
      `,
      getReferenceEntry: queryResult => ['user', queryResult.node],
      // Now `mockResolvers` is typed!
      mockResolvers: {
        User: () => ({
          profileImageUrl: 'https://source.unsplash.com/random/400x400',
        }),
      },
    } satisfies WithRelayParameters<UserAvatarStoryQuery, Resolvers>,
  },
};

These are totally optional, so feel free to skip them

Contribute

I don't have any plans to write or set up a contribution guide. If this library doesn't solve your problem or isn't sufficient, please create an issue and describe your situation or suggestion. I would appreciate it very much.

License

MIT

storybook-addon-relay's People

Contributors

iamchanii avatar jakobkhansen avatar miketamis avatar pikachews avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar

storybook-addon-relay's Issues

`type-fest`'s `PartialDeep` does not appear to work for objects within an array

InferMockResolvers appears to utilize PartialDeep to allow specifying only desired fields to mock with a custom value, however if the field is under an array type, then PartialDeep does not appear to properly augment the type.

For example, given this mock where all the fields are mocked:
image

If I take out any of the fields from an object under edges:
image
image

If I replace PartialDeep with, for example, ts-toolbelt's Object.Partial<T, 'deep'>, the type error goes away.

License?

Hey,

can a LICENSE be added to this repo to make it clear that it is free to use (if that is the case ;))? Such as MIT license?

Thanks!

Support for useQueryLoader / usePreloadedQuery

Hi,

This library has been very useful for me for the past months and am using it for a lot of my components, I find it very well designed and with a clean api.

What do you think of testing components using useQueryLoader/usePreloadedQuery - do you imagine it would be a good idea to find a way to also mock graphql requests for those ?

Thanks for the great work !

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.