DEV Community

Richard Nguyen
Richard Nguyen

Posted on

How can I test Gatsby components using PageProps with Jest?

I'm currently developing a Gatsby application using Typescript. There is one task that I need to use some internal props from Gatsby. These internal props come from PageProps interface from Gatsby.

This is my code:

// src/pages/post.tsx
import React from "react";
import { graphql, PageProps} from "gatsby";

import { useLocalSearch } from "@hooks";
import { BlogQuery } from "@generated/graphql";

export const query = graphql`
  query BlogQuery {
    latest: allMdx {
      edges {
        node {
          fields {
            slug
          }
          frontmatter {
            title
            tags
            description
            categories
            thumbnail {
              childImageSharp {
                fluid(maxWidth: 1040, quality: 100) {
                  ...GatsbyImageSharpFluid
                }
              }
            }
            date
          }
          timeToRead
          excerpt
        }
      }
    }
  }
`;

const Post: React.FC<PageProps<BlogQuery>> = props => {
  const {
    location,
    navigate,
    data: { latest },
  } = props;
  console.log(props);

  const [localQuery, setQuery, result] = useLocalSearch(location.search);

  const onChangeValue = (e: React.ChangeEvent<HTMLInputElement>): void => {
    navigate(e.target.value ? `/post/?search=${e.target.value}` : ``);
    setQuery(e.target.value);
  };

  return (
    <OtherComponents />
    <StyledSearchContainer>
      <StyledSearchWrapper>
        <StyledSearch
          id="search"
          type="search"
          value={localQuery}
          onChange={onChangeValue}
          placeholder="Search posts"
        />
      </StyledSearchWrapper>
    </StyledSearchContainer>
  );
}

The BlogQuery is automatically generated by graphql-codegen.

My other page tests follow Gatsby's testing page queries and they work perfectly. But they only use one prop each while this page uses more than one prop. So can I test this component? (I tried to log all props and copy them, but it didn't help at all).

Thank you.

Oldest comments (0)