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

Enzyme单元测试中before each()报错问题求助

Troubleshooting Enzyme before each() Error for Nested Logout Component

Let's break down why your nested Logout component is throwing a before each() hook error, while your flat Input component works fine. The root issue almost always boils down to missing dependencies that the Logout component expects from its parent context, props, or external state managers—things your Input component doesn’t rely on. Here’s how to fix this step by step:

First: Get the Exact Error Message

Right now you only know the hook failed, but not why. Let’s add a quick debug to reveal the root cause:

beforeEach(() => {
  try {
    render()
  } catch (err) {
    console.error("🚨 Render failed with error:", err)
    throw err // Re-throw so the test still fails, but we get details
  }
})

Run your tests again—this will print the exact error (e.g., "Cannot read property 'user' of undefined" or "useContext must be used within a Provider") which will point us to the fix.

Common Fixes Based on Error Type

1. Missing Required Props

If the error says a prop is undefined (like onLogout or user), your Logout component expects props that its parent Navbar normally passes. Just mock those props in your test:

import React from 'react'
import { shallow } from 'enzyme'
import Logout from 'components/Navbar/Logout'

describe('(Component) Logout', () => {
  let _wrapper
  // Mock the props your Logout component needs
  const mockProps = {
    onLogout: jest.fn(), // Mock a function for click handlers
    user: { id: 1, name: "Test User" } // Mock user data if needed
  }

  const render = () => {
    _wrapper = shallow(<Logout {...mockProps} />) // Pass mock props
  }

  beforeEach(() => {
    render()
  })

  it('Tests Logout component rendering', () => {
    expect(_wrapper.find('.logout').length).to.equal(1)
    expect(_wrapper.find('div').length).to.equal(1)
    expect(_wrapper.find('i').length).to.equal(1)
  })
})

2. Missing React Context

If the error mentions useContext or a missing Provider, your Logout component is using a Context (like AuthContext) that’s normally provided by a parent component. Wrap your Logout in the Context Provider in your test:

import React from 'react'
import { shallow } from 'enzyme'
import Logout from 'components/Navbar/Logout'
import { AuthContext } from '../contexts/Auth' // Import your Context

describe('(Component) Logout', () => {
  let _wrapper
  const mockContext = {
    user: { id: 1 },
    logout: jest.fn() // Mock the context functions your component uses
  }

  const render = () => {
    // Wrap Logout in the Context Provider, then use .dive() to access the Logout component
    _wrapper = shallow(
      <AuthContext.Provider value={mockContext}>
        <Logout />
      </AuthContext.Provider>
    ).dive()
  }

  beforeEach(() => {
    render()
  })

  it('Tests Logout component rendering', () => {
    expect(_wrapper.find('.logout').length).to.equal(1)
    expect(_wrapper.find('div').length).to.equal(1)
    expect(_wrapper.find('i').length).to.equal(1)
  })
})

3. Redux connect Wrapper

If your Logout is wrapped in Redux’s connect(), testing the connected component directly requires a Redux store. Instead, test the raw, unconnected component (better practice anyway, since it lets you control props):

  • In your Logout.js, export both the raw component and the connected version:
    import { connect } from 'react-redux'
    
    // Export the raw component for testing
    export const Logout = ({ user, logout }) => {
      // Component logic here
    }
    
    // Default export for use in your app
    export default connect(mapStateToProps, mapDispatchToProps)(Logout)
    
  • In your test, import the raw component:
    import { Logout } from 'components/Navbar/Logout' // Import the named export
    
    // Then pass mock props like we did in the first fix
    const mockProps = {
      user: { id: 1 },
      logout: jest.fn()
    }
    
    _wrapper = shallow(<Logout {...mockProps} />)
    

4. Global Dependencies (e.g., React Router)

If your Logout uses hooks like useHistory from React Router, mock those dependencies at the top of your test file:

// Mock React Router's useHistory
jest.mock('react-router-dom', () => ({
  ...jest.requireActual('react-router-dom'),
  useHistory: () => ({
    push: jest.fn()
  })
}))

// Rest of your test code here

Final Notes

Once you fix the dependency causing the before each() error, your rendering tests should pass just like your Input component tests. The key difference is that nested components often rely on parent-provided data or context that flat components don’t—your test needs to replicate that environment.

内容的提问来源于stack exchange,提问作者aaayumi

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.15 08:19:03