如何用React Testing Library和Jest测试agGrid的onGridSizeChanged事件
解决agGrid onGridSizeChanged无法在React测试中触发的问题
agGrid的onGridSizeChanged事件并非直接响应window resize,而是通过ResizeObserver监听自身容器的尺寸变化,测试环境中不会自动触发,需要手动模拟或调用API触发。以下是两种可行的测试方案:
方案1:通过Grid API手动触发(单元测试首选)
这种方式无需渲染真实agGrid,通过mock获取grid API直接触发事件,适合单元测试快速验证业务逻辑。
测试代码示例:
import { render } from '@testing-library/react'; import YourComponent from './YourComponent'; import { AGGridReact } from 'ag-grid-react'; // Mock ag-grid-react组件 jest.mock('ag-grid-react'); test('onGridSizeChanged 事件触发正常', () => { const mockOnGridSizeChanged = jest.fn(); let mockGridApi; // 配置mock,在onGridReady回调中传入模拟的grid API AGGridReact.mockImplementation((props) => { if (props.onGridReady) { mockGridApi = { dispatchEvent: jest.fn() }; props.onGridReady({ api: mockGridApi }); } return <div />; }); // 渲染组件 render(<YourComponent onGridSizeChanged={mockOnGridSizeChanged} />); // 手动触发gridSizeChanged事件 mockGridApi.dispatchEvent({ type: 'gridSizeChanged' }); // 断言回调被调用 expect(mockOnGridSizeChanged).toHaveBeenCalled(); });
方案2:模拟容器尺寸变化(集成测试用)
如果需要验证真实渲染场景下的尺寸响应,可以模拟容器尺寸修改并通知grid刷新。
步骤1:调整组件代码(添加测试标识)
给grid容器加上data-testid方便测试定位:
return ( <div className='ag-theme-alpine'> <div className='gridStylings' data-testid="grid-container"> <AGGridReact rowData={rowData} columnDefs={columndef} onGridReady={onGridReady} onGridSizeChanged={onGridSizeChanged} /> </div> </div> );
步骤2:暴露gridApi给测试
用useImperativeHandle把gridApi暴露出去:
import { useRef, useImperativeHandle, forwardRef } from 'react'; const YourComponent = forwardRef((props, ref) => { const gridApiRef = useRef(null); const onGridReady = useCallback((params) => { gridApiRef.current = params.api; }, []); // 暴露gridApi给测试用的ref useImperativeHandle(ref, () => ({ gridApi: gridApiRef.current, })); // ... 其他业务代码 return ( // ... 组件内容 ); }); export default YourComponent;
步骤3:编写测试用例
import { render, screen, waitFor } from '@testing-library/react'; import YourComponent from './YourComponent'; import React from 'react'; test('容器尺寸变化时触发onGridSizeChanged', async () => { const mockOnGridSizeChanged = jest.fn(); const componentRef = React.createRef(); // 渲染组件并传入ref render( <YourComponent ref={componentRef} onGridSizeChanged={mockOnGridSizeChanged} /> ); // 等待grid容器加载完成 const gridContainer = await screen.findByTestId('grid-container'); // 修改容器尺寸 gridContainer.style.width = '900px'; gridContainer.style.height = '600px'; // 获取gridApi并刷新尺寸 const gridApi = componentRef.current.gridApi; gridApi.refreshSize(); // 断言回调被触发 await waitFor(() => { expect(mockOnGridSizeChanged).toHaveBeenCalled(); }); });
内容的提问来源于stack exchange,提问作者supriya kajana
相关产品推荐
相关产品推荐

