我有一个包含在 Material-UI withStyles
HOC 和 React memo
HOC 中的组件。
我无法测试此组件,因为我无法调用dive()
:
ShallowWrapper::dive() can only be called on components
我目前知道的唯一选择是独立export Demo
和export default withStyles(styles)(Demo)
. 这使我可以测试未包含在withStyles
. 我想避免这种方法。
如果我删除 memo(),我可以测试该组件。同样,如果我删除 withStyles(),我也可以测试该组件。这些 HOC 的组合使我的组件无法测试。
有哪些可用的策略来有效地测试这个组件?
演示.js
import React, { memo } from "react";
import MUIIconButton from "@material-ui/core/IconButton";
import { withStyles } from "@material-ui/core/styles";
import Tooltip from "@material-ui/core/Tooltip";
import Typography from "@material-ui/core/Typography";
const styles = () => ({
root: {
backgroundColor: "red"
/* more styles... */
}
});
const Demo = memo(({ label, classes }) => (
<div className={classes.root}>
<Tooltip disableFocusListener title={label}>
<Typography>label</Typography>
</Tooltip>
</div>
));
export default withStyles(styles)(Demo);
demo.test.js
import React from "react";
import Adapter from "enzyme-adapter-react-16";
import { configure, shallow } from "enzyme";
import Demo from "./demo";
import MUIIconButton from "@material-ui/core/IconButton";
import Tooltip from "@material-ui/core/Tooltip";
configure({ adapter: new Adapter() });
describe("Demo", () => {
it("Should have a tooltip with label", () => {
const tooltip = "My tooltip";
const el = shallow(<Demo label={tooltip} />).dive();
expect(el.find(Tooltip).props().title).toEqual(tooltip);
});
});
完整的工作沙箱