代码之家  ›  专栏  ›  技术社区  ›  Daniel

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

  •  1
  • Daniel  · 技术社区  · 8 年前

    我用盖茨比和杰斯特做测试。默认情况下,Gatsby处理GraphQL数据获取,根据我的发现,它没有为在单元测试中测试GraphQL查询提供任何解决方案。

    有办法吗?现在我只是模拟测试组件本身的查询,但是我希望能够测试查询的工作,而不需要在GraphiQL中手动执行。

    我的代码如下:

    页面内容.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页面内容

    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();
      });
    });
    
    0 回复  |  直到 8 年前
        1
  •  0
  •   ehrencrona    6 年前

    我写了一篇 plugin that enables testing of Gatsby components with GraphQL queries . 如果安装它,您可以通过替换模拟数据来检索实际的Graph QL数据

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

    具有

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

    gatsby build gatsby develop )

    推荐文章