React组件Jest单元测试因MUI SvgIcon报错:useContext空值读取错误
MUI组件单元测试useContext报错问题解决
我在测试一个基于MUI实现的React组件,添加MUI的SvgIcon(RefreshIcon)后,单元测试抛出错误:TypeError: Cannot read properties of null (reading 'useContext')。为避免无效Hook调用,我已使用如下代码将组件包裹:
// Create a theme for the ThemeProvider const theme = createTheme(); // Utility function to render the component with necessary providers (to avoid invalid hook calls) const renderWithProviders = (ui: React.ReactElement) => { return render( <ThemeProvider theme={theme}> <BrowserRouter>{ui}</BrowserRouter> </ThemeProvider> ); };
需要添加IconContext.Provider来包裹UI。MUI的SvgIcon内部依赖IconContext,单元测试时如果没有这个上下文提供者,就会触发useContext读取null的报错。
修改后的renderWithProviders函数如下:
import { IconContext } from '@mui/material/icons'; // Create a theme for the ThemeProvider const theme = createTheme(); // Utility function to render the component with necessary providers (to avoid invalid hook calls) const renderWithProviders = (ui: React.ReactElement) => { return render( <ThemeProvider theme={theme}> <BrowserRouter> <IconContext.Provider value={{}}> {ui} </IconContext.Provider> </BrowserRouter> </ThemeProvider> ); };
说明:IconContext.Provider需要传入一个value对象,即使是空对象也能满足SvgIcon的上下文需求,避免出现null读取错误。如果组件还用到MUI其他通用组件(如Button、Typography),现有的ThemeProvider已经足够,仅针对SvgIcon需要补充这个额外的Provider。
内容的提问来源于stack exchange,提问作者amnahn
相关产品推荐
相关产品推荐

