question-mark
Stuck on an issue?

Lightrun Answers was designed to reduce the constant googling that comes with debugging 3rd party libraries. It collects links to all the places you might be looking at while hunting down a tough bug.

And, if you’re still stuck at the end, we’re happy to hop on a call to see how we can help out.

docs: update Testing Components with GraphQL

See original GitHub issue

The Testing Components with GraphQL guide is outdated since the Gatsby Default Starter switched to useStaticQuery.

Summary

When a learner wants to get started with testing Gatsby, the first step is to go through the Unit Testing guide. The guide is essentially a walk-through of the required setup and config to get started with Jest (custom config, mocks, etc.).

The next step is to learn about Testing Components with GraphQL. This guides builds on the previous one and adds specs to test Gatsby StaticQuery queries.

The issue is that the example site being tested is the gatsby-starter-default, which doesn’t have any StaticQuery queries since it switched entirely to the newer useStaticQuery.

Testing useStaticQuery is a little bit different from testing StaticQuery. An example can be found online at Mock Gatsby’s useStaticQuery with Jest.

Note: a recent PR (#18202) already added a note about testing ùseStaticQuery somewhere further in the guide

Motivation

Updating the guide would further help people learn how to test Gatsby, and remove the frustration of following a guide and getting unexpected errors.

Steps to resolve this issue

It seems that there are two possible paths to solving this issue:

  1. Rewrite the guide to add query testing for the gatsby-starter-default. In this case, the sections about testing StaticQuery wouldn’t belong in this guide anymore
  2. Make a new example site (for example examples/using-tests-for-graphql) that includes both StaticQuery and useStaticQuery and rewrite the guide to explain how to test both methods

Draft the doc

Open a pull request

  • Open a pull request with your work including the words “closes #[this issue’s number]” in the pull request description

Issue Analytics

  • State:closed
  • Created 4 years ago
  • Reactions:6
  • Comments:6 (1 by maintainers)

github_iconTop GitHub Comments

2reactions
tbrlpldcommented, Jul 1, 2020

I just ran into that issue too. This is really confusing, especially as a beginner to Gatsby.

Thankfully this issue exists and pointed me in the right direction. I was able to adjust the test from StaticQuery to useStaticQuery (which is actually used in the components created by the current starter template).

In case anybody else is running into this issue while learning, I was able to redefine the test like so:

/* eslint-env jest */

import React from 'react'
import renderer from 'react-test-renderer'
import { useStaticQuery } from 'gatsby'

import Index from '../index'

beforeEach(() => {
  useStaticQuery
    .mockImplementationOnce(() => { // Mock for use in Layout
      return {
        site: {
          siteMetadata: {
            title: 'Gatsby Default Starter'
          }
        }
      }
    })
    .mockImplementationOnce(() => { // Mock for use in SEO
      return {
        site: {
          siteMetadata: {
            title: 'Gatsby Default Starter',
            description: 'Kick off your next, great Gatsby project with this default starter. This barebones starter ships with the main Gatsby configuration files you might need.',
            author: '@gatsbyjs'
          }
        }
      }
    })
    .mockImplementationOnce(() => { // Mock for use in Image
      return {
        placeholderImage: {
          childImageSharp: {
            fluid: {
              base64: 'data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAABQAAAAUCAIAAAAC64paAAAACXBIWXMAAAsSAAALEgHS3X78AAACYklEQVQ4y42Uy28SQRjA+dM8efDmwYN6qF6qiSY+Y/WgQRMibY00TaWNBSRSCraYQtHl/bR0KyxQWCgWWAqU8izl/Sq7rLNsRHlVJpvJtzPfb77nDIOcZHSoqZSrp4+KtXIziubaLRysMCZiCYqOoVnhjNEi8RcztdxxeTzc6VBfT+5O2Vhpb+vw4wMdZ0ppWvP9xzLeJoDNThf2W+Nz1+XzNxQubSToSKKW+BDc+WOnkshhSVgeCiGpViZMEg1oxc26Knt+ae3bEtJTZwzE1kXLccG0+sOOlrcvZXvsczPkITfsa20vwIKnhsh+BnjUarT74Gb13CY7KBVJMv3z4N1NszQYsMWM62HNrCis/GxXn0iYls23uz5LPBcv0bH8hUH2XRoM85ySXv7JBtO87jMIvWq+H5GoYIHCLA1ZxD6Qap3Ak8IKfW7TJ50lK6uP9E6RgndHaODtCJ6Z5RyHfnE7j6gRbcKlCYNSt+rtETHTpUGgEP8FYmdNqd/Mo7aiVWTfuH2L9xASvfxxlqr01EYkrJszvNkgW9bH0OuFr+99m+y9IOeyU6zIp/Hubp/yMEztlzFPwOhdvq+nIoS1JNn4t2sugCmVsDvPe2KKolnZLCxhOcAKQRDDXTQaVi46lqYhIBwHTrl3oWqhMRDtaJge37lOBMKo4tfbqhVX0J7snTsWps8uZWuoOQY6CcjpSIF55UvmqNgr5wUwtV1IVdnXtnSfPEB2qjDNqnvczRl0m+j6Jn5lXb6nAQJqinmN0ZEBj03YLzghY8PnTRz80o/GRJZpOLCb0PM9BN7pvUEjx28V00WUg9jIVwAAAABJRU5ErkJggg==',
              aspectRatio: 1,
              src: '/static/6d91c86c0fde632ba4cd01062fd9ccfa/630fb/gatsby-astronaut.png',
              srcSet: '/static/6d91c86c0fde632ba4cd01062fd9ccfa/5db04/gatsby-astronaut.png 75w,\n/static/6d91c86c0fde632ba4cd01062fd9ccfa/6d161/gatsby-astronaut.png 150w,\n/static/6d91c86c0fde632ba4cd01062fd9ccfa/630fb/gatsby-astronaut.png 300w,\n/static/6d91c86c0fde632ba4cd01062fd9ccfa/62b1f/gatsby-astronaut.png 450w,\n/static/6d91c86c0fde632ba4cd01062fd9ccfa/2a4de/gatsby-astronaut.png 600w,\n/static/6d91c86c0fde632ba4cd01062fd9ccfa/ee604/gatsby-astronaut.png 800w',
              sizes: '(max-width: 300px) 100vw, 300px'
            }
          }
        }
      }
    })
})

describe('Index', () => {
  it('renders correctly', () => {
    const tree = renderer.create(<Index />).toJSON()
    expect(tree).toMatchSnapshot()
  })
})

To get the returned mock data, I went to http://localhost:8000/___graphql and ran the queries that are defined in each component (Layout, SEO and Image). For the image component, the ...GatsbyImageSharpFluid fragment needs to be replaced with

      base64
      aspectRatio
      src
      srcSet
      sizes

This is already suggested on the docs page in question.

The fact that I am mocking the same function three times is probably not the most elegant, but it solved my issue without getting into many other issues. The issue is that the function that needs to mocking is used in many place when testing a whole page.

I guess a more elegant solution would be to mock the different components that are using the useStaticQuery and test these components in isolation elsewhere.

2reactions
ghostcommented, Oct 30, 2020

@robinmetral I’m not so sure about that Mocking example you linked. The author is setting up spies and doesn’t provide a complete example. Searching GH I already see 109 instances of that pattern and many seem to be doing it differently. On top of that I don’t see the author explaining spies/mocks may need to be reset in a teardown of some sort such as afterEach.

I feel at a minimum the takeaway here is that Gatsby’s using-jest example should be updated to show a specific example of testing with useStaticQuery especially given it’s the method provided now in the default starter as you mention. Perhaps using a composition library such as the one I mention in a related issue or, possibly better yet, using react-hooks-testing-library as shown here.

EDIT Article updated spies example with feedback.

Read more comments on GitHub >

github_iconTop Results From Across the Web

Testing React components - Apollo GraphQL Docs
This article describes best practices for testing React components that use Apollo Client. The examples below use Jest and React Testing Library, ...
Read more >
Testing React components - Apollo GraphQL Docs
This behavior affects how tests should be written for components that use Apollo Client with React. This guide will explain step-by-step how to...
Read more >
A Guide to Unit Testing React Apollo Components - DoltHub
Our components with queries come with a queries.ts file, which defines the shape of the GraphQL queries and mutations using graphql-tag. We also ......
Read more >
Testing Apollo Components using react-testing-library
Boilerplate. MockProvider requires explicitly defining query variables, the graphql document used in the component, and a complete json response ...
Read more >
Working with GraphQL | Cypress Documentation
Best practices to alias multiple GraphQL queries or mutations for a group of tests. · Overriding an existing intercept to modify the query...
Read more >

github_iconTop Related Medium Post

No results found

github_iconTop Related StackOverflow Question

No results found

github_iconTroubleshoot Live Code

Lightrun enables developers to add logs, metrics and snapshots to live code - no restarts or redeploys required.
Start Free

github_iconTop Related Reddit Thread

No results found

github_iconTop Related Hackernoon Post

No results found

github_iconTop Related Tweet

No results found

github_iconTop Related Dev.to Post

No results found

github_iconTop Related Hashnode Post

No results found