故事书模拟 GraphQL (Gatsby)

Storybook Mock GraphQL (Gatsby)

我正在使用 Gatsby 创建博客。 Gatsby 可以使用 Markdown 和 GraphQL 来“自动”为您创建 post 页面。我想知道使用 Gatsby example here.

在故事书中UI“模拟”graphql 查询并将其替换为我们的降价数据的最佳方法是什么。这样我就可以在 Storybook UI 中测试这个组件了。例如,如果我有一个类似于以下内容的博客模板:

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
      }
    }
  }
`;

提前致谢

您或许可以修改 the webpack configuration of Storybook to use the NormalModuleReplacementPlugin 来模拟整个 gatsby 包。然后从您的模拟中导出一个 graphql 方法,您可以在故事中对其进行操作。

或者,将您的组件拆分为一个纯组件和一个执行查询的组件,并按照 https://www.gatsbyjs.org/docs/unit-testing/

中的建议使用纯组件