TechBuzzPro

How to Test Gatsby Sites: Unit, E2E, & Accessibility

· 5 min read · Apps & Browsers

In this article
  1. What You'll Need
  2. Step-by-Step
  3. Common Mistakes
  4. Tips
  5. Troubleshooting
  6. Frequently Asked Questions

This guide walks you through setting up and running unit tests, end-to-end (E2E) tests, and accessibility checks for a Gatsby website. By the end, you'll have a repeatable testing workflow that catches logic errors, broken user flows, and common accessibility issues before they reach production.

What You'll Need

  • A Gatsby project (v4 or v5) with package.json and a src directory
  • Node.js (v18 or later) and npm/yarn installed
  • Basic familiarity with the command line
  • Optional: a GitHub account if you want CI integration

Step-by-Step

1. Set Up Unit Testing with Jest and Testing Library

  1. Install dependencies: npm install --save-dev jest babel-jest @testing-library/react @testing-library/jest-dom @testing-library/user-event jest-environment-jsdom
  2. Add a jest.config.js file at the project root with:
    module.exports = {
      testEnvironment: 'jsdom',
      transform: {
        '^.+\\.jsx?$': '/jest-preprocess.js',
      },
      moduleNameMapper: {
        '^gatsby-page-utils/(.*)$': 'gatsby-page-utils/dist/$1',
        '^gatsby-core-utils/(.*)$': 'gatsby-core-utils/dist/$1',
        '^gatsby-shared/(.*)$': 'gatsby-shared/dist/$1',
        '^gatsby$': '/node_modules/gatsby/index.js',
        '^.+\\.(css|scss|svg|png|jpg)$': 'identity-obj-proxy',
      },
      setupFiles: ['/loadershim.js'],
      setupFilesAfterEnv: ['/setup-test-env.js'],
      testPathIgnorePatterns: ['node_modules', '\\.cache', 'public'],
    }
  3. Create jest-preprocess.js with Babel configuration that handles Gatsby's ES modules:
    const babelOptions = {
      presets: ['babel-preset-gatsby'],
    }
    module.exports = require('babel-jest').default.createTransformer(babelOptions)
  4. Create loadershim.js to mock Gatsby's global __PATH_PREFIX__:
    global.__PATH_PREFIX__ = ''
    global.__BASE_PATH__ = ''
  5. Create setup-test-env.js to extend Jest with Testing Library matchers:
    import '@testing-library/jest-dom'
  6. Add a test script to package.json: "test": "jest"
  7. Write your first unit test. For a component like src/components/header.js, create src/components/__tests__/header.test.js:
    import React from 'react'
    import { render, screen } from '@testing-library/react'
    import Header from '../header'
    
    test('renders site title', () => {
      render(
    ) expect(screen.getByText('My Site')).toBeInTheDocument() })
  8. Run npm test to verify everything works.

2. Set Up End-to-End Testing with Cypress

  1. Install Cypress: npm install --save-dev cypress @testing-library/cypress
  2. Add scripts to package.json:
    "test:e2e": "cypress run",
    "test:e2e:open": "cypress open"
  3. Run npx cypress open once to generate the cypress folder structure.
  4. Configure Cypress to use your Gatsby dev server. In cypress.config.js:
    const { defineConfig } = require('cypress')
    
    module.exports = defineConfig({
      e2e: {
        baseUrl: 'http://localhost:8000',
        setupNodeEvents(on, config) {},
      },
    })
  5. Add a test file, e.g., cypress/e2e/home.cy.js:
    describe('Home page', () => {
      it('loads and shows the header', () => {
        cy.visit('/')
        cy.get('header').should('be.visible')
        cy.contains('My Site').should('exist')
      })
    })
  6. Before running E2E tests, start the Gatsby dev server in a separate terminal: gatsby develop
  7. Run npm run test:e2e to execute tests headlessly.

3. Set Up Accessibility Testing with axe-core

  1. Install the axe-core accessibility engine: npm install --save-dev @axe-core/cypress
  2. In cypress/support/e2e.js, add:
    import '@testing-library/cypress/add-commands'
    import '@axe-core/cypress/add-commands'
  3. Add an accessibility check to your E2E test:
    it('has no detectable accessibility violations', () => {
      cy.visit('/')
      cy.injectAxe()
      cy.checkA11y()
    })
  4. Run the test again. If violations are found, Cypress will list them with selectors and impact levels.

4. Run All Tests Together

  1. Add a combined script: "test:all": "npm test && npm run test:e2e"
  2. Run npm run test:all to execute unit, E2E, and accessibility tests in sequence.

Common Mistakes

  • Forgetting to mock Gatsby's Link component in unit tests – this causes failures because Gatsby's Link relies on the gatsby runtime. Use jest.mock('gatsby', ...) to replace it with a simple anchor.
  • Not starting the dev server before running Cypress – Cypress will fail with a connection refused error.
  • Testing only the happy path – you should also test error states and empty data scenarios.
  • Ignoring accessibility violations – even minor issues like missing form labels can block users with screen readers.
  • Using CSS selectors that are too brittle – prefer roles and accessible names in both Cypress and Testing Library.

Tips

  • Run unit tests in watch mode during development: npm test -- --watch
  • Use cy.findByRole('button', { name: /submit/i }) instead of cy.get('button') for better accessibility and maintainability.
  • For accessibility, set the baseUrl to the production build (gatsby build && gatsby serve) to catch issues that only appear in production.
  • Add a CI pipeline (e.g., GitHub Actions) that runs all tests on every pull request. Use gatsby build first, then run Cypress against the served build.
  • Keep test fixtures small and realistic. Use mock data that mimics real content structure.

Troubleshooting

  • Jest fails with "Cannot find module 'gatsby'" – Ensure your moduleNameMapper includes the Gatsby mapping as shown above. Also check that gatsby is in your dependencies.
  • Cypress cannot connect to the dev server – Verify the dev server is running on port 8000. If you changed the port, update baseUrl accordingly.
  • Accessibility test reports many violations – Start by fixing critical and serious issues. Use cy.checkA11y(null, { includedImpacts: ['critical', 'serious'] }) to focus on the most important.
  • Tests pass locally but fail in CI – Ensure your CI environment has enough memory and that you're using the same Node version. Add CYPRESS_CACHE_FOLDER if needed.
  • Unit tests fail due to GraphQL queries – Mock the useStaticQuery hook with a jest mock that returns your test data.

Frequently Asked Questions

  1. Do I need to test every component? – No, focus on components with logic (state, event handlers, conditional rendering) and those used across multiple pages. Simple presentational components can be covered by E2E tests.
  2. Can I use Jest for E2E testing instead of Cypress? – Jest is not designed for E2E. It runs in a simulated DOM, not a real browser. Use Cypress or Playwright for true E2E.
  3. How do I test Gatsby's GraphQL queries? – Unit tests mock the query results. For integration, use Gatsby's gatsby develop to query real data, but that's more of an E2E concern.
  4. What if my site uses client-side routes? – Cypress can visit those routes directly, but ensure you use cy.visit('/some-route') after the initial load. For Gatsby, client-only routes need special handling – you may need to set matchPath or use gatsby-plugin-create-client-paths.
  5. Is axe-core enough for accessibility? – Axe-core catches about 30-50% of common issues automatically. For full coverage, combine with manual testing and keyboard navigation checks.
  6. How often should I run these tests? – Run unit tests on every commit, E2E and accessibility tests at least once per PR and before every release. In CI, run all of them.