简体   繁体   English

如何在 Gatsby 中对 GraphQL 查询进行单元测试

[英]How to unit test GraphQL queries in Gatsby

I'm using Gatsby and Jest for testing.我正在使用 Gatsby 和 Jest 进行测试。 By default Gatsby handles the GraphQL data fetching, and from what I've found it doesn't provide any solution for testing its GraphQL queries in unit tests.默认情况下,Gatsby 处理 GraphQL 数据获取,据我所知,它没有提供任何解决方案来在单元测试中测试其 GraphQL 查询。

Is there a way to do this?有没有办法做到这一点? Right now I'm just mocking the queries the test the component itself, but I want to be able to test queries work without manually doing so in GraphiQL.现在我只是模拟查询来测试组件本身,但我希望能够测试查询工作而无需在 GraphiQL 中手动执行此操作。

Here's what my code looks like:这是我的代码的样子:

PageContent.jsx页面内容.jsx

import PropTypes from 'prop-types';
import React from 'react';

const PageContent = ({ data: { markdownRemark: { html } } }) => (
  <div>
    {html}
  </div>
);

PageContent.propTypes = {
  data: PropTypes.shape({
    markdownRemark: PropTypes.shape({
      html: PropTypes.string.isRequired,
    }).isRequired,
  }).isRequired,
};

export const query = graphql`
  query PageContent($id: ID!) {
    markdownRemark(frontmatter: { id: $id }) {
      html
    }
  }
`;

export default PageContent;

PageContent.test.jsx PageContent.test.jsx

import PageContent from 'templates/PageContent';

describe("<PageContent>", () => {
  let mountedComponent;
  let props;

  const getComponent = () => {
    if (!mountedComponent) {
      mountedComponent = shallow(<PageContent {...props} />);
    }
    return mountedComponent;
  };

  beforeEach(() => {
    mountedComponent = undefined;
    props = {
      data: {
        markdownRemark: {
          html: '<div>test</div>',
        },
      },
    };
  });

  it("renders a <div> as the root element", () => {
    expect(getComponent().is('div')).toBeTruthy();
  });

  it("renders `props.data.markdownRemark.html`", () => {
    expect(getComponent().contains(props.data.markdownRemark.html)).toBeTruthy();
  });
});

I've written a plugin that enables testing of Gatsby components with GraphQL queries .我编写了一个插件,可以使用 GraphQL 查询测试 Gatsby 组件 If you install it you can retrieve the actual Graph QL data by replacing your mocked data如果你安装它,你可以通过替换你的模拟数据来检索实际的 Graph QL 数据

  data: {
        markdownRemark: {
          html: '<div>test</div>',
        },
      }

with

  data: await getPageQueryData(`/path/to/your/page`)

It will then pull the data from the latest time you built your project (using gatsby build or gatsby develop )然后它将从您构建项目的最新时间中提取数据(使用gatsby buildgatsby develop

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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