You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Jest运行React应用测试时出现ReferenceError: Worker is not defined错误的解决求助

Jest运行React应用测试时出现ReferenceError: Worker is not defined错误的解决求助

大家好,我最近在给React应用跑Jest测试的时候碰到了一个特别棘手的问题,想请各位帮忙分析下:

我明明测试的是一个完全没用到heic2any库的组件,却一直弹出ReferenceError: Worker is not defined的错误,甚至把测试用例里的内容全部注释掉,这个错误还是会出现,直接导致测试流程卡壳走不下去了。

下面是相关的代码和配置,麻烦各位帮我看看问题出在哪:

被测试的组件代码(ActionButton.tsx)

import { Button } from '@material-ui/core';
import { ReactElement } from 'react';
import useBreakpoint from 'src/hooks/useBreakpoint';

interface ActionButtonProps {
  isMobileOnly?: boolean;
  icon?: ReactElement;
  onClick?: () => void;
  ['data-testid']?: string
}

const ActionButton = ({ isMobileOnly = false, icon, onClick, ...rest }: ActionButtonProps) => {
  const { isMobile } = useBreakpoint();
  const text = isMobile ? 'Add' : 'Add Photo Description Set';

  if ((!isMobile && isMobileOnly) || (isMobile && !isMobileOnly)) {
    return null;
  }

  return (
    <Button
      data-testid={rest['data-testid']}
      startIcon={icon}
      variant="outlined"
      onClick={onClick}
    >
      {text}
    </Button>
  );
};

export default ActionButton;

用到heic2any的组件(另一个独立文件)

import React from 'react';
import { SxProps } from '@material-ui/system';
import { PencilAlt } from 'src/icons';
import heic2any from 'heic2any';

interface FileImageDropzoneProps extends DropzoneOptions {
  cardMediaSx?: SxProps;
}

const FileImageDropzone: React.FC<FileImageDropzoneProps> = (props) => {
  // component code goes here...
};

export default FileImageDropzone;

我的单元测试代码

import ActionButton from '../ActionButton';
import { render, screen, cleanup, fireEvent } from '@testing-library/react';
import useBreakpoint, { BreakpointHook } from 'src/hooks/useBreakpoint';
import '@testing-library/jest-dom';

afterEach(cleanup)

jest.mock('src/hooks/useBreakpoint');

const mockUseBreakpoint: jest.Mock<BreakpointHook> = useBreakpoint as jest.Mock<BreakpointHook>;

describe('ActionButton', () => {
  it('should render the compnent', () => {
    render(<ActionButton data-testid='action-button' />);
    mockUseBreakpoint.mockReturnValue({
      isMobile: true,
      isDesktop: false,
    })
    const { getByTestId } = screen
    expect(getByTestId('action-button')).toBeInTheDocument()
  });
});

我的Jest配置文件

module.exports = {
  preset: 'ts-jest',
  testEnvironment: 'jsdom',
  transform: {
    '^.+\\.tsx?$': [
      'ts-jest',
      {
        isolatedModules: true,
      },
    ],
  },
  testMatch: ['**/src/**/__tests__/**/*.test.ts?(x)'],
  moduleFileExtensions: ['ts', 'tsx', 'js', 'jsx', 'json', 'node'],
  collectCoverage: true,
  coveragePathIgnorePatterns: [
    '/node_modules/',
    '/__tests__/',
    '/dist/',
    '/coverage/',
  ],
  setupFilesAfterEnv: [
    '@testing-library/jest-dom/extend-expect',
    'jest-canvas-mock',
    '<rootDir>/jest.setup.ts',
  ],
  moduleNameMapper: {
    '^src/(.*)$': '<rootDir>/src',
  },
  moduleDirectories: ['node_modules'],
  coverageThreshold: {
    global: {
      branches: 80,
      functions: 80,
      lines: 80,
      statements: 80,
    },
  },
};

我实在想不通,明明测试的组件和heic2any没有任何关联,为什么会触发这个Worker未定义的错误?有没有大佬能帮我分析下原因,再给个可行的解决办法呀?

备注:内容来源于stack exchange,提问作者Reeem

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.04.23 07:49:20