使用withStyles(material-ui)单元测试组件时,无效的React钩子

时间:2020-02-27 17:08:03

标签: reactjs jestjs material-ui enzyme

我正在尝试对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)
    });
});

在运行测试时,这将引发无效的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', () => {

当我用普通组件碰到它们时,我能够修复它们,但似乎无法在这样的单元测试中解决它。有什么想法吗?

0 个答案:

没有答案