react-testing-library: ReferenceError: document is not defined

hello, when i run yarn test, it comes out ReferenceError: document is not defined and node_modules are all lasted version. anyone can help? thanks a lot.

ReferenceError: document is not defined

       7 | describe('基础 react 单元测试', () => {
       8 |   it('home 组件测试', () => {
    >  9 |     const { getByTestId } = render(<TestExample />);
         |                             ^
      10 |     expect(getByTestId('home-ul').children.length).toBe(3);

      at Object.render (node_modules/@testing-library/react/dist/index.js:68:5)
      at Object.it (tests/unit/example.spec.tsx:9:29)

package.json

"scripts": { "test": "jest" }

jest.config.js

module.exports = {
  setupFilesAfterEnv: [
    '@testing-library/react/cleanup-after-each',
    '@testing-library/jest-dom/extend-expect'
  ],
  testMatch: [
    '**/?(*.)spec.ts?(x)'
  ],
  globals: {
    'ts-jest': {
      tsConfig: 'tsconfig.json',
      diagnostics: false,
    },
  },
  testEnvironment: 'node',
  preset: 'ts-jest',
}

component and unit test

import React from 'react';
const TestExample = () => {
  return (
      <ul data-testid="home-ul">
        <li>a item</li>
        <li>b item</li>
        <li>c item</li>
      </ul>
  );
};
export default TestExample;

// example.spec.tsx
import React from 'react';
import { render, cleanup } from '@testing-library/react';
import TestExample from '../../src/web/components/test-example';

afterEach(cleanup);

describe('基础 react 单元测试', () => {
  it('home 组件测试', () => {
    const { getByTestId } = render(<TestExample />);
    expect(getByTestId('home-ul').children.length).toBe(3);
  });
});

About this issue

  • Original URL
  • State: closed
  • Created 5 years ago
  • Reactions: 20
  • Comments: 19 (4 by maintainers)

Commits related to this issue

Most upvoted comments

Hi @lawler61,

React Testing Library needs a DOM to operate. Change your jest config testEnvironment to jsdom and you’ll be set.

I’m not sure if this has changed since the suggested solution, or if was implied by @kentcdodds when they suggested setting the testEnvironment to jsdom, but for anyone coming to this, to set the testEnvironment, you use the following line in your jest.config.js

testEnvironment: 'jest-environment-jsdom',

Just in case someone runs into this issue. I am learning testing in react and I just ran into this issue. I resolved it by going to node_modules folder, jest folder, package.json file. I just added one property.

"testEnvironment": "jsdom"

It works perfectly. I know editing node_modules folder is a no no, but just for the sake of learning it works.

If you checkout the Jest docs for test environment you can add a docblock in the specific test file to change the envrironment e.g. changing the .ts file to node would be:

Docblock:

/**
 * @jest-environment node || jsdom
 */

My test file.ts:

/**
 * @jest-environment node 
 */

describe('api-client', () => {
  it('should intercept a 401 status code', (done) => {
    const statusCode = 401
    const testError = [
      { code: 'AUTHENTICATION_FAILURE', message: 'Authentication Failure' },
    ]
    const scope = nock(apiUrl!).get('/products').reply(statusCode, testError)

    fetchProducts()
      .then()
      .catch((error) => {
        expect(error.response.status).toBe(statusCode)
        expect(sessionStorage.removeItem).toHaveBeenCalledTimes(1)
        scope.done()
        done()
      })
  })
});

primero: yarn add -D @testing-library/react , @testing-library/jest-dom, “yarn add -D jest-environment-jsdom” crie um arquivo de configuração “jest.setup.ts”

segundo: no seu arquivo jest.config.js adicione isso “dentro de module.export” -> testEnvironment: ‘jsdom’,

terceito: no seu arquivo jest.config.js adicione “dentro de module.export” -> setupFilesAfterEnv

quarto: parâmetro do “setupFilesAfterEnv” é esté [‘caminho do jest.setup.ts’]

depois disso tudo -> yarn jest --clearCache só roda o jest agora

Had the same issue. This code block

/**
* @jest-environment jsdom
*/

MUST BE ON TOP OF FILE. If you put it below the import statement it won’t work 😄

ReferenceError: document is not defined

Just in case someone is having simliar issue, and have tired the solution above and it didn’t work, I solved mine by put a docblock at the top of my test file.

/** * @jest-environment jsdom */

That is the docblock

Is there a step I might be missing? I have testEnvironment: jsdom configured but I still get window is not defined or document is not defined. To be clear I’m not using document or window on my test file but the source code I’m trying to test uses it.

Thanks

If you rely on an edit to node_modules, tests on other machines machines (including coworkers and CI services) will likely not work properly, as they won’t receive edits on ignored files. Additionally, newer packages like Yarn Berry do not support editing node_modules by default, as it’s not used in installation anymore.

Instead, if you’re running jest directly, you should add "testEnvironment": "jsdom" to your own Jest config.

If you’re using create-react-app, make sure you’re not using --env=node in your test scripts.

In case anybody else is confused about this and happens upon it: jsdom was previously the default for testEnvironment config option in jest, and that was changed to node in jest v27… which is coincidentally right before the jest authors started publishing upgrade guides 😜 So this is a likely thing to encounter when upgrading from jest 26.x or earlier to jest 27.x or later.

(note: you may also have to add jest-environment-jsdom to your package.json, as it’s no longer included by default)

Hi @joeldbirch, thanks for your question 😃 My suggestion might be a hack but I’d think of separating the “server” component and the “client” component to two different components since they have two different functionalities. That way, your server component actually renders the client component only if the window is defined. So in your tests you can test your “server” component by removing the global.window as you did, and you’ll test your “client” component regularly 😃

  1. install “npm i jest-environment-jsdom”

  2. (testEnvironment: “jsdom”) in jest.config.js

I had the same issue and resolved it by providing jest , an environment with installing jest-environment-jsdom and providing the test environment in jest.config.js

{ "testEnvironment": "jsdom" }

Also putting it inside package.json file , worked fine as well .

"jest": {
    "testEnvironment": "jsdom"
  },

I’m getting this error in svelte test as well. No idea how to fix.