abhiaiyer91 / apollo-storybook-decorator

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

How to use the apollo queries to local state? #150

Open zadigus opened 3 years ago

zadigus commented 3 years ago

I have the following vue component:

<!-- Cart.vue -->
<template>
  <div>
    {{ cart.totalGrossPrice }}
  </div>
</template>

<script>
import gql from 'graphql-tag'

export default {
  apollo: {
    cart: {
      query: gql`
        query Cart {
          cart @client {
            totalGrossPrice
          }
        }
    }
  }
}
</script>

I would like to display it in my storybook. For that, I've defined a schema.graphql (the same as that of the production application):

# schema.graphql
type Cart {
  totalGrossPrice: Float!
}

and mocks:

// mocks.js
export default {
  Cart: () => {
    return {
      __typename: 'Cart',
      totalGrossPrice: 0,
      products: []
    }
  }
}

which I then wire up in my stories:

// Shop.stories.js
import Vue from 'vue'

import apolloStorybookDecorator from 'apollo-storybook-vue'
import { storiesOf } from '@storybook/vue'
import Cart from '../Cart'

import typeDefs from './schema/schema.graphql'
import mocks from './schema/mocks'

storiesOf('Shop/Cart', module)
  .addDecorator(
    apolloStorybookDecorator({
      mocks,
      typeDefs,
      Vue
    })
  )
  .add('Cart', () => {
    return {
      components: {
        Cart
      },
      template: '<cart />'
    }
  })

Now, when I run storybook and open this component, I get the following errors / warnings:

Found @client directives in a query but no ApolloClient resolvers were specified. This means ApolloClient local resolver handling has been disabled, and @client directives will be passed through to your link chain.

and

GraphQLError {message: "Unknown directive "client".", locations: Array(1), path: undefined, nodes: Array(1), source: Source, …}

and

TypeError: Cannot read property 'totalGrossPrice' of undefined

among others.

What can I do to make it work? The component works fine in the production application.

vinnyjth commented 3 years ago

I was able to get things working by adding the following snippet to my typeDefs

  directive @client on FIELD