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
- Fix yarn test with advice from https://github.com/testing-library/react-testing-library/issues/422 — committed to rubyforgood/casa by compwron 3 years ago
- jest 가 작동하지 않는 문제를 해결한다. - npx jest 입력 시 테스트 코드에서 import 를 사용 할 수 없다는 오류 메세지가 계속 노출됨(참고이미지: https://i.stack.imgur.com/kmWMC.png) - App 파일에 있는 css 임포트를 제거하니 다른 오류메세지가 찍힘. ReferenceError: document is n... — committed to CodeSoom/project-react-4-Hamill210 by deleted user 3 years ago
- build: configure jest to use render see https://github.com/testing-library/react-testing-library/issues/422 for fix with jsdom — committed to dictybase-playground/dicty-components by ayaanqui 2 years ago
Hi @lawler61,
React Testing Library needs a DOM to operate. Change your jest config
testEnvironmenttojsdomand 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
testEnvironmenttojsdom, but for anyone coming to this, to set thetestEnvironment, you use the following line in yourjest.config.jstestEnvironment: '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.
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
.tsfile tonodewould be:Docblock:
My test file.ts:
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
MUST BE ON TOP OF FILE. If you put it below the
importstatement 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: jsdomconfigured but I still getwindow is not definedordocument 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 editingnode_modulesby default, as it’s not used in installation anymore.Instead, if you’re running
jestdirectly, you should add"testEnvironment": "jsdom"to your own Jest config.If you’re using
create-react-app, make sure you’re not using--env=nodein your test scripts.In case anybody else is confused about this and happens upon it:
jsdomwas previously the default fortestEnvironmentconfig option in jest, and that was changed tonodein 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-jsdomto 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.windowas you did, and you’ll test your “client” component regularly 😃install “npm i jest-environment-jsdom”
(testEnvironment: “jsdom”) in jest.config.js
I had the same issue and resolved it by providing jest , an environment with installing
jest-environment-jsdomand providing the test environment injest.config.jsAlso putting it inside
package.jsonfile , worked fine as well .I’m getting this error in svelte test as well. No idea how to fix.