How to unit test GraphQL queries in Gatsby

梦想与她 提交于 2021-02-19 03:13:55

问题


I'm using Gatsby and Jest for testing. 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.

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.

Here's what my code looks like:

PageContent.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();
  });
});

回答1:


I've written a plugin that enables testing of Gatsby components with GraphQL queries. If you install it you can retrieve the actual Graph QL data by replacing your mocked data

  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)



来源:https://stackoverflow.com/questions/51738301/how-to-unit-test-graphql-queries-in-gatsby

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!