reactjs - 使用 withStyles (material-ui) 对组件进行单元测试时,React 挂钩无效
问题描述
我正在尝试对使用来自 material-ui 的 withStyles 的组件进行单元测试。我正在定义下面的样式。
import { makeStyles, Theme, createStyles } from "@material-ui/core";
const myStyle = (theme: Theme) => createStyles({
root: {
display: 'flex'
},
content: {
flexGrow: 1,
backgroundColor: theme.palette.background.default,
padding: theme.spacing(3)
},
drawer: {
width: 240
}
});
export function useStyles() {
return makeStyles(myStyle);
}
它被一个名为 MainPage 的组件消耗,如下所示
export const MainPage = () => {
const classes = useStyles();
return (
<ErrorBoundary>
<DynamicFormWrapper
baseUrl={'https://.......'}
classes={classes()}
/>
</ErrorBoundary>
);
};
我在树的下方有一个组件,它依赖于看起来像这样的样式
type FormProps = {
names: string[];
} & WithStyles;
export class SideMenu extends React.Component<FormProps> {
private names: string[];
constructor(props) {
super(props);
this.names= props.names;
}
render() {
//omitted
}
}
在尝试测试该组件时,我需要将样式作为道具传递,并尝试这样做
import * as React from 'react';
import { configure, shallow } from 'enzyme';
import * as Adapter from 'enzyme-adapter-react-16';
import { SideMenu } from '../src/components/SideMenu';
import { useStyles } from '../src/js/styles'
configure({ adapter: new Adapter() });
describe('SideMenu', () => {
let wrapper;
beforeEach(() => {
const style = useStyles();
wrapper = shallow(<SideMenu names={['test1', 'test2', 'test3']} classes={style()} />);
});
it('Should render', () => {
expect(wrapper)
});
});
运行测试时,这将引发 Invalid Hook 错误
Invalid hook call. Hooks can only be called inside of the body of a function component. This could happen for one of the following yada yada
16 | beforeEach(() => {
17 | const style = useStyles();
> 18 | wrapper = shallow(<SideMenu names={['test1', 'test2', 'test3']} classes={style()} />);
| ^
19 | });
20 |
21 | it('Should render', () => {
当我使用普通组件遇到它们时,我能够修复它们,但在像这样的单元测试中似乎无法解决它。有任何想法吗?
解决方案
推荐阅读
- twitter - Twitter 是否提供任何 API 来回复推文或获取回复列表
- android - 如果他不验证电子邮件,我们如何删除 firebase 用户?
- java - 无法使用所需功能使用 Microsoft Edge 创建新会话
- laravel - 如何用foreach存储?
- python - Windows Sphinx 安装失败...出了什么问题?
- azure-devops - 从 Power BI Desktop 连接到 Azure DevOps
- c++ - 在 C++ 中存储邻接矩阵的输入
- sql - 在左连接中选择取决于另一个表中字段总和的行?
- aws-lambda - 有没有办法限制谁可以管理 lambda 别名
- html - 如何允许用户为在画布 2d 中输入的数据选择颜色