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

如何在React Testing Library测试中使用React Redux useDispatch钩子?

测试Redux Dispatch后的React组件

我想要测试使用Redux dispatch后的React组件,目前使用的是test-utils.ts文件中的自定义render函数:

import { ReactElement } from 'react'
import { render, RenderOptions } from '@testing-library/react'

import { Provider } from 'react-redux'
import { store } from './store/store'
import AppTheme from './theme/AppTheme'

type childrenType = {
    children?: string | JSX.Element | JSX.Element[] | undefined
}

const Providers = ({ children }: childrenType) => {
    return (
        <Provider store={store}>
            <AppTheme>
                {children}
            </AppTheme>
        </Provider>
    )
}

const customRender = (
    ui: ReactElement,
    options?: Omit<RenderOptions, 'wrapper'>

) => render(ui, { wrapper: Providers, ...options })

export * from '@testing-library/react'
export { customRender as render }

现在我希望在测试中渲染组件前,分发一个action来改变状态,测试代码如下:

test('renders files section', () => {
    // Do something to dispatch an action...

    render(<ContentSection />)

    const headerElement = screen.getByRole('heading', { level: 2, name: 'Files:' })
    expect(headerElement).toBeInTheDocument()
})

解决方案

你的自定义render函数直接使用了全局导出的store,因此可以直接在测试中导入该store,在渲染组件前调用dispatch方法分发action:

  1. 在测试文件中导入store和目标action创建函数:
import { store } from '../path/to/store/store';
import { yourTargetAction } from '../path/to/your/actions'; // 替换为你实际的action创建函数
  1. 修改测试代码,在render前执行dispatch:
test('renders files section', () => {
    // 分发action改变Redux状态
    store.dispatch(yourTargetAction(/* 传入action需要的参数 */));

    render(<ContentSection />);

    const headerElement = screen.getByRole('heading', { level: 2, name: 'Files:' });
    expect(headerElement).toBeInTheDocument();
});

额外注意:避免测试间状态污染

如果多个测试共用同一个store,前一个测试的状态可能会干扰后续测试结果。建议在每个测试执行前重置store状态,比如添加beforeEach钩子:

beforeEach(() => {
    // 调用重置状态的action,或根据你的store实现方式重置初始状态
    store.dispatch(resetAppState());
});

内容的提问来源于stack exchange,提问作者Bartłomiej Sikora

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.02 16:55:03