为主题提供者开玩笑的手动模拟

时间:2019-10-30 14:00:25

标签: reactjs jestjs material-ui

我想测试一个使用Material-UI的makeStyles的React组件。

我的组件:

import React from 'react';
import { useTranslation } from 'react-i18next';
import { DefaultButton } from '../../../../components';
import { makeStyles } from '@material-ui/styles';

const useStyles = makeStyles((theme: any) => ({
  root: {},
  row: {
    marginTop: theme.spacing()
  },
  spacer: {
    flexGrow: 1
  },
}));

const UsersToolbar: React.FC<any> = (props) => {
  const classes = useStyles();
  const { t } = useTranslation();

  return (
    <div className={classes.root}>
      <div className={classes.row}>
        <span className={classes.spacer} />
        <DefaultButton id="createUserBtn">{t('Create User')}</DefaultButton>
      </div>
    </div>
  );
};

export default UsersToolbar;

我的测试:

import React from 'react';
import ReactDOM from 'react-dom';
import { createMuiTheme } from '@material-ui/core';
import { ThemeProvider } from '@material-ui/styles';
import UsersToolbar from '.';

describe('<UsersToolbar />', () => {
  it('passes smoke test', () => {
    const div = document.createElement('div');
    ReactDOM.render(
        <UsersToolbar />,
      div
    );
  });
});

我当时正在考虑使用jest.mock()并将手动模拟放到__mocks__/

我该怎么做?我试图提供在Material-UI官方主页(https://material-ui.com/guides/testing/)上提议的ThemeProvider,但没有成功。

1 个答案:

答案 0 :(得分:0)

我通过创建一个名为MockTheme的组件来解决此问题,该组件包装了需要测试的组件。结果如下所示:

import React from 'react';
import { createMuiTheme } from '@material-ui/core';
import { ThemeProvider } from '@material-ui/core/styles';

function MockTheme({ children }: any) {
  const theme = createMuiTheme({});
  return <ThemeProvider theme={theme}>{children}</ThemeProvider>;
}

export default MockTheme;

修改后的测试现在可以正常工作

import React from 'react';
import ReactDOM from 'react-dom';
import MockTheme from '../../../../theme/MockTheme';
import UsersToolbar from '.';

describe('<UsersToolbar />', () => {
  it('passes smoke test', () => {
    const div = document.createElement('div');
    ReactDOM.render(
      <MockTheme>
        <UsersToolbar />
      </MockTheme>,
      div
    );
  });
});