Jest, React, TS ReferenceError: document is not defined
/**
* @jest-environment jsdom
*/
import React from "react";
import { render, screen, fireEvent, cleanup } from "@testing-library/react";
import Zustand from "../component/Zustand";
import '@testing-library/jest-dom'
afterEach(() => {
cleanup(); // Resets the DOM after each test suite
})
describe("Компонент Zustand", () => {
it("отрисовывает начальное значение счетчика", () => {
render(<Zustand />);
expect(screen.getByText(/Count: 0/i)).toBeInTheDocument();
expect(screen.getByText(/Increase/i)).toBeInTheDocument();
expect(screen.getByText(/Decrease/i)).toBeInTheDocument();
});
it("вызывает increaseCount при клике на кнопку Increase", () => {
const mockStore = require("../zustand/store").default; // Получаем мокаемый store
render(<Zustand />); // Рендерим компонент Zustand
const increaseButton = screen.getByText(/Increase/i); // Находим кнопку Increase
const resetButton = screen.getByText(/Reset/i); // Находим кнопку Reset
fireEvent.click(increaseButton); // Симулируем клик по кнопке
fireEvent.click(increaseButton); // Симулируем еще один клик по кнопке
expect(mockStore().increaseCount).toHaveBeenCalledTimes(2); // Проверяем, что функция increaseCount была вызвана дважды
expect(mockStore().resetCount).toHaveBeenCalledTimes(0); // Проверяем, что функция resetCount не была вызвана
fireEvent.click(resetButton); // Симулируем клик по кнопке Reset
expect(mockStore().resetCount).toHaveBeenCalledTimes(1); // Проверяем, что функция resetCount была вызвана один раз
expect(mockStore().increaseCount).toHaveBeenCalledTimes(2); // Проверяем, что функция increaseCount была вызвана дважды
});
});
module.exports = {
// Указываем, что тестовая среда - jsdom
testEnvironment: 'jsdom',
// Преобразование файлов с расширением .ts и .tsx с использованием ts-jest
transform: {
'^.+\\.(ts|tsx)$': 'ts-jest',
'^.+\\.css$': 'jest-css-modules-transform', // Для работы с CSS модулями
},
// Подключение расширений файлов, которые Jest будет обрабатывать
moduleFileExtensions: ['ts', 'tsx', 'js', 'jsx'],
// Игнорирование трансформации для некоторых модулей, чтобы ускорить тесты
transformIgnorePatterns: ['/node_modules/(?!@testing-library)'],
// Дополнительные опции для покрытия, если нужно
collectCoverage: true,
coverageReporters: ['json', 'lcov', 'text', 'clover'],
// Для правильного использования библиотек для работы с DOM
setupFilesAfterEnv: ['<rootDir>/src/setupTests.ts'],
// Директивы, чтобы Jest игнорировал случайные предупреждения и улучшал производительность
silent: false,
verbose: true,
};
FAIL src/tests/ZustandIncDec.test.tsx Компонент Zustand × отрисовывает начальное значение счетчика (34 ms) × вызывает increaseCount при клике на кнопку Increase (7 ms)
● Компонент Zustand › отрисовывает начальное значение счетчика
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
14 | it("отрисовывает начальное значение счетчика", () => {
15 | render(<Zustand />);
> 16 | expect(screen.getByText(/Count: 0/i)).toBeInTheDocument();
| ^
17 | expect(screen.getByText(/Increase/i)).toBeInTheDocument();
18 | expect(screen.getByText(/Decrease/i)).toBeInTheDocument();
19 | });
at node_modules/nwsapi/src/nwsapi.js:215:21
at Factory (node_modules/nwsapi/src/nwsapi.js:245:6)
at initNwsapi (node_modules/jsdom/lib/jsdom/living/helpers/selectors.js:10:10)
at exports.addNwsapi (node_modules/jsdom/lib/jsdom/living/helpers/selectors.js:38:24)
at HTMLBodyElementImpl.ElementImpl.matches (node_modules/jsdom/lib/jsdom/living/nodes/Element-impl.js:569:19)
at HTMLBodyElement.matches (node_modules/jsdom/lib/jsdom/living/generated/Element.js:655:34)
at queryAllByText (node_modules/@testing-library/dom/dist/queries/text.js:26:60)
at node_modules/@testing-library/dom/dist/query-helpers.js:74:17
at node_modules/@testing-library/dom/dist/query-helpers.js:52:17
at node_modules/@testing-library/dom/dist/query-helpers.js:95:19
at Object.<anonymous> (src/__tests__/ZustandIncDec.test.tsx:16:19)
● Компонент Zustand › вызывает increaseCount при клике на кнопку Increase
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
23 |
24 | render(<Zustand />); // Рендерим компонент Zustand
> 25 | const increaseButton = screen.getByText(/Increase/i); // Находим кнопку Increase
| ^
26 | const resetButton = screen.getByText(/Reset/i); // Находим кнопку Reset
27 |
28 | fireEvent.click(increaseButton); // Симулируем клик по кнопке
at node_modules/nwsapi/src/nwsapi.js:215:21
at Factory (node_modules/nwsapi/src/nwsapi.js:245:6)
at initNwsapi (node_modules/jsdom/lib/jsdom/living/helpers/selectors.js:10:10)
at exports.addNwsapi (node_modules/jsdom/lib/jsdom/living/helpers/selectors.js:38:24)
at HTMLBodyElementImpl.ElementImpl.matches (node_modules/jsdom/lib/jsdom/living/nodes/Element-impl.js:569:19)
28 | fireEvent.click(increaseButton); // Симулируем клик по кнопке
at node_modules/nwsapi/src/nwsapi.js:215:21
at Factory (node_modules/nwsapi/src/nwsapi.js:245:6)
at initNwsapi (node_modules/jsdom/lib/jsdom/living/helpers/selectors.js:10:10)
at exports.addNwsapi (node_modules/jsdom/lib/jsdom/living/helpers/selectors.js:38:24)
at HTMLBodyElementImpl.ElementImpl.matches (node_modules/jsdom/lib/jsdom/living/nodes/Element-impl.js:569:19)
at HTMLBodyElement.matches (node_modules/jsdom/lib/jsdom/living/generated/Element.js:655:34)
at queryAllByText (node_modules/@testing-library/dom/dist/queries/text.js:26:60)
at node_modules/@testing-library/dom/dist/query-helpers.js:74:17
at node_modules/@testing-library/dom/dist/query-helpers.js:52:17
at node_modules/@testing-library/dom/dist/query-helpers.js:95:19
at Object.<anonymous> (src/__tests__/ZustandIncDec.test.tsx:25:35)
уже все перепробовал игрался с jsdom уже делал разные виды конфигураций ts конфигурацию json в package.json пихал конфигурацию 35 раз уже переустанавливал jest и другие зависимости ничего не помогает не знаю что не так
Ответы (3 шт):
I've got the same issue, when I use a previous package-lock it works fine + npm ci, but doing a fresh install I get the same error. From package-lock nothing jest related seems to have changed.
Jest config is set to jsdom, tried adding the rule to the test file same thing.
возможно, проблема кроется в новой версий какой-то из зависимостей, которые используются jest.
я откатил все зависимости, которые используются в jest, и так же сам jest на одну версию назад, удалил папку coverage
, node_modules
, package-lock.json
и выполнил npm i
, и проблема изчезла.
Here ya go, broken release. solutions here https://github.com/dperini/nwsapi/issues/135