简体   繁体   中英

Storybook Mock GraphQL (Gatsby)

I am using Gatsby to create a blog. Gatsby can use markdown with GraphQL to "automagically" create post pages for you. I was wondering using the Gatsby example here .

In storybook UI what is the best way to "mock" out the graphql query and replace it with our markdown data. So that I can test this component in Storybook UI. For example if I have a blog template that looks something like:

import { graphql } from 'gatsby';
import React from 'react';

export default function Template({
  data, // this prop will be injected by the GraphQL query below.
}) {
  const { markdownRemark } = data; // data.markdownRemark holds your post data
  const { frontmatter, html } = markdownRemark;
  return (
    <div className="blog-post-container">
      <div className="blog-post">
        <h1>{frontmatter.title}</h1>
        <h2>{frontmatter.date}</h2>
        <div
          className="blog-post-content"
          dangerouslySetInnerHTML={{ __html: html }}
        />
      </div>
    </div>
  );
}
export const pageQuery = graphql`
  query($slug: String!) {
    markdownRemark(frontmatter: { slug: { eq: $slug } }) {
      html
      frontmatter {
        date(formatString: "MMMM DD, YYYY")
        slug
        title
      }
    }
  }
`;

Thanks in advance

You can probably modify the webpack configuration of Storybook to use the NormalModuleReplacementPlugin to mock the whole gatsby package. Then export a graphql method from your mock that you can manipulate in your stories.

Alternatively, split your component into a pure component and a component that performs the query and just use the pure component as suggested in https://www.gatsbyjs.org/docs/unit-testing/

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM