首页 > 解决方案 > 使用 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', () => {

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

标签: reactjsjestjsmaterial-uienzyme

解决方案


推荐阅读