Jest Test in Next.js Fails with “ReferenceError: document is not defined”

I’m working on a Next.js app and trying to write a Jest test for a simple button component. However, when I run the test, I get this error:

ReferenceError: document is not defined
The error below may be caused by using the wrong test environment, see https://jestjs.io/docs/configuration#testenvironment-string.    
Consider using the "jsdom" test environment.

Here’s my setup:
package.json

{
  "name": "help-center-app",
  "version": "0.1.0",
  "private": true,
  "scripts": {
    "dev": "next dev",
    "build": "next build",
    "start": "next start",
    "lint": "next lint",
    "test": "jest"
  },
  "dependencies": {
    "next": "14.2.18",
    "react": "^18",
    "react-dom": "^18",
    "ts-node": "^10.9.2"
  },
  "devDependencies": {
    "@testing-library/jest-dom": "^6.6.3",
    "@testing-library/react": "^16.0.1",
    "@testing-library/user-event": "^14.5.2",
    "@types/jest": "^29.5.14",
    "@types/node": "^20",
    "@types/react": "^18",
    "@types/react-dom": "^18",
    "eslint": "^8",
    "eslint-config-next": "14.2.18",
    "jest": "^29.7.0",
    "jest-environment-jsdom": "^29.7.0",
    "ts-jest": "^29.2.5",
    "typescript": "^5"
  }
}

jest.config.ts

import type { Config } from 'jest';
import nextJest from 'next/jest';

const createJestConfig = nextJest({ dir: './' });

const config: Config = {
  clearMocks: true,
  coverageProvider: 'v8',
  testEnvironment: 'jsdom',
};

export default createJestConfig(config);

Test file

import Button from '@/app/components/Button';
import '@testing-library/jest-dom';
import { render, screen } from '@testing-library/react';

describe('Button component', () => {
  it('renders a button with the btn classname', () => {
    render(<Button />);

    const buttonElement = screen.getByRole('button', { name: /Click me/i });

    expect(buttonElement).toBeInTheDocument();
    expect(buttonElement).toHaveClass('btn');
  });
});

I suspect there’s an issue with my Jest configuration or the environment setup, but I can’t pinpoint it.

How can I resolve this error and ensure my tests run correctly?