next.jsjestjs

ReferenceError: document is not defined in Jest while testing React component in a Next.js projec


I'm trying to write a unit test for a React component in my Next.js project using Jest and React Testing Library. However, I'm encountering the following error when running the test:

`Testing Home Component › renders a heading

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.

ReferenceError: document is not defined`

Here is my test code:

Home.test.tsx

import { render, screen } from "@testing-library/react";
import Home from "./Home"; // Adjust based on your file structure

describe("Testing Home Component", () => {
  it("renders a heading", () => {
    render(<Home />);
    const text = screen.getByText(/Home/i);
    expect(text).toBeInTheDocument();
  });
});

Home.tsx

'use client'

import React from 'react'

const Home = () => {
  return (
    <div>
      Home
    </div>
  )
}

export default Home

I tried running a Jest test for a React component in a Next.js project using @testing-library/react. The test renders the Home component and checks if a heading containing the text "Home" is present in the document.

Here is the test I used:

import { render, screen } from "@testing-library/react";
import Home from "./Home"; // Adjust based on your file structure

describe("Testing Home Component", () => {
  it("renders a heading", () => {
    render(<Home />);
    const text = screen.getByText(/Home/i);
    expect(text).toBeInTheDocument();
  });
});

I expected the test to pass successfully, meaning the Home component would render, and the heading with the text "Home" would be found in the document. However, I encountered the following error:

ReferenceError: document is not defined


Solution

  • It seems to be related to https://www.npmjs.com/package/nwsapi. Please check https://github.com/dperini/nwsapi/issues/135