DEV Community

Richard Nguyen
Richard Nguyen

Posted on

1 1

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.

AWS GenAI LIVE image

Real challenges. Real solutions. Real talk.

From technical discussions to philosophical debates, AWS and AWS Partners examine the impact and evolution of gen AI.

Learn more

Top comments (0)

Sentry image

See why 4M developers consider Sentry, “not bad.”

Fixing code doesn’t have to be the worst part of your day. Learn how Sentry can help.

Learn more

👋 Kindness is contagious

Please leave a ❤️ or a friendly comment on this post if you found it helpful!

Okay