DEV Community πŸ‘©β€πŸ’»πŸ‘¨β€πŸ’»

DEV Community πŸ‘©β€πŸ’»πŸ‘¨β€πŸ’» is a community of 964,423 amazing developers

We're a place where coders share, stay up-to-date and grow their careers.

Create account Log in
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.

Top comments (0)

🌚 Life is too short to browse without dark mode