【发布时间】:2019-09-25 00:07:14
【问题描述】:
Material UI 的最新版本现在有一个用于样式组件的 Hooks 替代方案,而不是 HoC。所以不是
const styles = theme => ({
...
});
export const AppBarHeader = ({ classes, title }) => (
...
);
export default withStyles(styles)(AppBarHeader);
您可以选择这样做:
const useStyles = makeStyles(theme => ({
xxxx
}));
const AppBarHeader = ({ title }) => {
const classes = useStyles();
return (
....
)
};
export default AppBarHeader;
在某些方面这更好,但与所有钩子一样,您不能再向组件注入“存根”依赖项。以前,为了使用 Enzyme 进行测试,我只测试了非样式组件:
describe("<AppBarHeader />", () => {
it("renders correctly", () => {
const component = shallow(
<AppBarHeader title="Hello" classes="{}" />
);
expect(component).toMatchSnapshot();
});
});
然而,如果你使用钩子,没有类的“存根”依赖,你会得到:
Warning: Material-UI: the `styles` argument provided is invalid.
You are providing a function without a theme in the context.
One of the parent elements needs to use a ThemeProvider.
因为您始终需要提供者。我可以去总结一下:
describe("<AppBarHeader />", () => {
it("renders correctly", () => {
const component = shallow(
<ThemeProvider theme={theme}>
<AppBarHeader title="Hello" classes="{}" />
</ThemeProvider>
).dive();
expect(component).toMatchSnapshot();
});
});
但这似乎不再渲染组件的子组件(即使使用潜水调用)。人们是怎么做到的?
【问题讨论】:
-
看来答案是 (a) 不要做浅渲染和 (b) 使用 react-testing-library 而不是 Enzyme
标签: material-ui enzyme react-hooks