How to Test Gatsby Sites: Unit, E2E, & Accessibility
In this article
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.jsonand asrcdirectory - 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
- Install dependencies:
npm install --save-dev jest babel-jest @testing-library/react @testing-library/jest-dom @testing-library/user-event jest-environment-jsdom - Add a
jest.config.jsfile 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'], } - Create
jest-preprocess.jswith Babel configuration that handles Gatsby's ES modules:const babelOptions = { presets: ['babel-preset-gatsby'], } module.exports = require('babel-jest').default.createTransformer(babelOptions) - Create
loadershim.jsto mock Gatsby's global__PATH_PREFIX__:global.__PATH_PREFIX__ = '' global.__BASE_PATH__ = ''
- Create
setup-test-env.jsto extend Jest with Testing Library matchers:import '@testing-library/jest-dom'
- Add a test script to
package.json:"test": "jest" - Write your first unit test. For a component like
src/components/header.js, createsrc/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() }) - Run
npm testto verify everything works.
2. Set Up End-to-End Testing with Cypress
- Install Cypress:
npm install --save-dev cypress @testing-library/cypress - Add scripts to
package.json:"test:e2e": "cypress run", "test:e2e:open": "cypress open"
- Run
npx cypress openonce to generate thecypressfolder structure. - 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) {}, }, }) - 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') }) }) - Before running E2E tests, start the Gatsby dev server in a separate terminal:
gatsby develop - Run
npm run test:e2eto execute tests headlessly.
3. Set Up Accessibility Testing with axe-core
- Install the axe-core accessibility engine:
npm install --save-dev @axe-core/cypress - In
cypress/support/e2e.js, add:import '@testing-library/cypress/add-commands' import '@axe-core/cypress/add-commands'
- Add an accessibility check to your E2E test:
it('has no detectable accessibility violations', () => { cy.visit('/') cy.injectAxe() cy.checkA11y() }) - Run the test again. If violations are found, Cypress will list them with selectors and impact levels.
4. Run All Tests Together
- Add a combined script:
"test:all": "npm test && npm run test:e2e" - Run
npm run test:allto execute unit, E2E, and accessibility tests in sequence.
Common Mistakes
- Forgetting to mock Gatsby's
Linkcomponent in unit tests – this causes failures because Gatsby's Link relies on thegatsbyruntime. Usejest.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 ofcy.get('button')for better accessibility and maintainability. - For accessibility, set the
baseUrlto 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 buildfirst, 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
moduleNameMapperincludes the Gatsby mapping as shown above. Also check thatgatsbyis 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
baseUrlaccordingly. - 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_FOLDERif needed. - Unit tests fail due to GraphQL queries – Mock the
useStaticQueryhook with a jest mock that returns your test data.
Frequently Asked Questions
- 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.
- 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.
- How do I test Gatsby's GraphQL queries? – Unit tests mock the query results. For integration, use Gatsby's
gatsby developto query real data, but that's more of an E2E concern. - 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 setmatchPathor usegatsby-plugin-create-client-paths. - 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.
- 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.