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

运行React组件测试用例时出现TypeError: Cannot read property 'prototype' of undefined错误如何解决?

Fixing TypeError: Cannot read property 'prototype' of undefined in Enzyme/React Tests

I’ve run into this exact error multiple times when working with Enzyme and React tests—let’s break down the fixes step by step:

The Root Cause

This error almost always stems from a missing or mismatched Enzyme adapter for your React version. Enzyme requires an adapter tailored to your React version to interact with React’s internal APIs correctly; without it, you’ll get this "prototype undefined" crash.

Step 1: Install the Correct Enzyme Adapter

First, install the adapter that matches your React version:

  • For React 16:
    npm install enzyme-adapter-react-16 --save-dev
  • For React 17 (official Enzyme doesn’t support 17 natively):
    npm install @wojtekmaj/enzyme-adapter-react-17 --save-dev
  • For React 18:
    npm install @wojtekmaj/enzyme-adapter-react-18 --save-dev

Step 2: Configure the Adapter in Your Test

Add the adapter configuration at the top of your test file (or a global setup file like setupTests.js if you want it applied to all tests):

import React from 'react';
import { render } from 'enzyme';
import Enzyme from 'enzyme';
// Import the adapter you installed
import Adapter from 'enzyme-adapter-react-16'; 

// Configure Enzyme with the adapter
Enzyme.configure({ adapter: new Adapter() });

import FileUpload from '../Components/Elements/fileUpload';

Step 3: Fix Test Structure

In your current code, you’re rendering the component outside the it block (directly in the describe block). This runs before Enzyme is fully configured, which can also trigger the error. Move the render call inside your test case:

describe('FileUpload component', ()=>{
  it('Test init status', function() {
    // Render the component inside the test block
    const wrapper = render(<FileUpload />); 
    expect(wrapper.find('input').length).toBe(2);
    expect(wrapper.find('input').text()).toEqual('');
  });
});

Bonus: Verify Package Compatibility

Double-check that your enzyme, react, and react-dom versions are compatible. For example:

  • Enzyme 3.x works with React 16.x
  • Enzyme 3.x + the community adapters work with React 17/18

After making these changes, your test should run without the prototype error.

内容的提问来源于stack exchange,提问作者Ravi Kumar Gopalakrishnan

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.20 12:08:10