如何在React测试中Mock useSelector获取的两个Redux状态?
如何Mock Redux的useSelector状态
这里提供两种实用方案来Mock组件中通过useSelector获取的Redux状态:
方案一:直接Mock useSelector 函数
用JestMockreact-redux中的useSelector,让它返回预设的测试数据,适合快速隔离Redux依赖的简单测试场景。
修改后的测试代码如下:
import { render } from '@testing-library/react'; import LocationHistory from 'Components/location-history'; // Mock react-redux的useSelector,保留其他原有导出 jest.mock('react-redux', () => ({ ...jest.requireActual('react-redux'), useSelector: jest.fn() })); describe('Location component', () => { test('Renders component', () => { const { useSelector } = require('react-redux'); // 自定义Mock状态,让useSelector返回对应值 useSelector.mockImplementation((selector) => { const mockState = { page: { pinnedLocations: ['北京', '上海'] }, user: { name: '测试用户', id: 123 } }; return selector(mockState); }); const { container, getByText } = render(<LocationHistory />); const title = getByText('Location Pattern'); expect(container).toBeInTheDocument(); expect(title).toBeInTheDocument(); }); });
方案二:创建测试专用Redux Store
如果需要更贴近真实运行环境,或者组件依赖Redux的其他特性(如dispatch),可以创建一个带预设初始状态的测试Store,用Provider包裹组件。
修改后的测试代码如下:
import { Provider } from 'react-redux'; import { configureStore } from '@reduxjs/toolkit'; import LocationHistory from 'Components/location-history'; import { render } from '@testing-library/react'; // 导入你的根reducer import rootReducer from '../redux/reducers'; describe('Location component', () => { test('Renders component', () => { // 创建测试Store,传入预设初始状态 const testStore = configureStore({ reducer: rootReducer, preloadedState: { page: { pinnedLocations: ['广州', '深圳'] }, user: { name: '测试用户', id: 456 } } }); const { container, getByText } = render( <Provider store={testStore}> <LocationHistory /> </Provider> ); const title = getByText('Location Pattern'); expect(container).toBeInTheDocument(); expect(title).toBeInTheDocument(); }); });
注意事项
- 方案一适合快速测试独立组件,完全隔离Redux;
- 方案二更贴近真实场景,适合需要验证Redux交互逻辑的测试;
- 若使用Redux Toolkit,优先用
configureStore创建测试Store,它自带默认中间件配置,无需额外设置。
内容的提问来源于stack exchange,提问作者Ryru Lobo
相关产品推荐
相关产品推荐

