簡體   English   中英

React 在 Jest 測試中未定義

[英]React is undefind in Jest tests

我想用 Jest 和 React 測試庫的單元測試來覆蓋我的代碼。 但我有一個問題 - 因為React變量未定義,所以執行測試時出錯。

這是我的配置:

const { pathsToModuleNameMapper } = require('ts-jest');
const { defaults } = require('jest-config');

module.exports = {
    preset: 'ts-jest',
    testEnvironment: 'jsdom',
    moduleDirectories: ['./node_modules', 'src'],
    moduleFileExtensions: [...defaults.moduleFileExtensions, 'ts', 'tsx'],
    setupFiles: ["<rootDir>/tests/setupFiles.js"],
    setupFilesAfterEnv: ['<rootDir>/tests/jest-setup.ts'],
    transform: {
        '^.+\\.(js|jsx)?$': 'babel-jest'
    },
    "moduleNameMapper": {
        "^@domain": "<rootDir>/src/domain",
        "^@service": "<rootDir>/src/service",
        "^@utils": "<rootDir>/src/utils",
        "^@view": "<rootDir>/src/view",
        "^.+\\.(css|scss)$": "<rootDir>/tests/styleMock.js",
        "^@components": "<rootDir>/src/components",
        "^@resources": "<rootDir>/resources"
    },
};

測試腳本

import React from 'react';
import { render, waitFor } from '@testing-library/react';
import '@testing-library/jest-dom';

import '../../utils.js';
import '../../../src/locale/ru.js';

import AloneTable from '../../../src/view/aloneTable/AloneTable';

describe('Page AloneTableView', () => {
    test('Render check', async () => {
        const tmp = render(<AloneTable/>);
        await waitFor(() => expect(tmp.asFragment()).toMatchSnapshot());
        await waitFor(() => expect(tmp.getByText('...')).toBeInTheDocument());
    });
});

這就是開玩笑拋出的錯誤

    TypeError: Cannot read properties of undefined (reading 'Component')

    > 24 | class ErrorBoundary extends React.Component<{ children: ReactNode }, { hasError: boolean }> {

如果我只使用Component而不是React.Component出現另一個錯誤

    TypeError: Cannot read properties of undefined (reading 'createElement')

      152 | const emptyFiller = (
    > 153 |     <VFlexBox align="center" justify="center" cls="grid__empty-filler">
          |     ^

在這種情況下,我不知道如何解決它。 據我了解,react 正在調用createElement ,因為我不直接使用它。

您能否描述一下,我該如何解決這個問題?

這可能是錯誤的答案,但我有一個修復。 我可以通過在tsconfig.json中進行以下更改來解決此問題:

{
  "compilerOptions": {
    "jsx": "react-jsx", // previously was "react"

希望有人能盡快給出正確的答案。

編輯...這是我的最終臨時解決方案,我為更改 jsx 模式的測試創建了一個新的 tsconfig

jest.config.ts

import type { Config } from "@jest/types";
const config: Config.InitialOptions = {
  preset: "ts-jest",
  setupFilesAfterEnv: ["<rootDir>/jest-setup.ts"],
  testEnvironment: "jsdom",
  testEnvironmentOptions: { browsers: ["chrome", "firefox", "safari"] },
  globals: {
    "ts-jest": {
      tsconfig: "tsconfig.test.json", // new tsconfig just for tests!
    },
  },
};
export default config;

tsconfig.test.json

{
    "extends": "./tsconfig.json",
    "compilerOptions": {
        "jsx": "react-jsx", // override here so that the tests work, but original code stays the same
    }
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM