如何基于材料ui测试组件?

时间:2018-04-11 11:12:03

标签: javascript reactjs material-ui jestjs enzyme

我有以下组件,即使用https://material-ui-next.com/构建。

import React from 'react';
import { AppBar, Toolbar } from 'material-ui';
import { Typography } from 'material-ui';
import { MuiThemeProvider, createMuiTheme } from 'material-ui/styles';
import {lightBlue} from 'material-ui/colors';

const theme = createMuiTheme({
  palette: {
    primary: {
      main:lightBlue['A700']
    },
    text: {
      primary: '#fff',
    }
  },
});

const View = (props) => (
  <MuiThemeProvider theme={theme}>
    <AppBar position="static">
      <Toolbar>
      <Typography variant="title">
        {props.title}
      </Typography>          
      </Toolbar>
    </AppBar>
  </MuiThemeProvider>
);
export default View;  

我正在尝试为它编写测试:

import React from 'react';
import { shallow } from 'enzyme';
import View from '../Views/View';
import { Typography } from 'material-ui';

it('renders', () => {
  const wrapper = shallow(<View title='Welcome' />);
  expect(wrapper.find('Typography').text()).toEqual('Welcome');
});  

如何为使用material-ui组件的组件编写测试?在上面的例子中,我试图弄清楚,如果组件包含Welcome 我读过https://material-ui-next.com/guides/testing/,但不清楚,我该怎么写测试。

1 个答案:

答案 0 :(得分:1)

UPD:API从shallow更改为mount

您是否尝试过使用他们的API described here? 可能你的测试看起来像这样:

import React from 'react';
import { createMount } from 'material-ui/test-utils';
import View from '../Views/View';
import { Typography } from 'material-ui';

it('renders', () => {
  const mount = createMount();
  const wrapper = mount(<View title='Welcome' />);
  expect(wrapper.find('Typography').text()).toEqual('Welcome');
});