如何使用Jest测试材料UI表的数据输出

时间:2018-12-17 19:01:28

标签: reactjs jestjs material-ui

我使用了material-ui

中的下表
import React from 'react';
import PropTypes from 'prop-types';
import { withStyles } from '@material-ui/core/styles';
import Table from '@material-ui/core/Table';
import TableBody from '@material-ui/core/TableBody';
import TableCell from '@material-ui/core/TableCell';
import TableHead from '@material-ui/core/TableHead';
import TableRow from '@material-ui/core/TableRow';
import Paper from '@material-ui/core/Paper';

const styles = theme => ({
  root: {
    width: '100%',
    marginTop: theme.spacing.unit * 3,
    overflowX: 'auto',
  },
  table: {
    minWidth: 700,
  },
});

let id = 0;
function createData(name, calories, fat, carbs, protein) {
  id += 1;
  return { id, name, calories, fat, carbs, protein };
}

const rows = [
  createData('Frozen yoghurt', 159, 6.0, 24, 4.0),
  createData('Ice cream sandwich', 237, 9.0, 37, 4.3),
  createData('Eclair', 262, 16.0, 24, 6.0),
  createData('Cupcake', 305, 3.7, 67, 4.3),
  createData('Gingerbread', 356, 16.0, 49, 3.9),
];

function SimpleTable(props) {
  const { classes } = props;

  return (
    <Paper className={classes.root}>
      <Table className={classes.table}>
        <TableHead>
          <TableRow>
            <TableCell>Dessert (100g serving)</TableCell>
            <TableCell numeric>Calories</TableCell>
            <TableCell numeric>Fat (g)</TableCell>
            <TableCell numeric>Carbs (g)</TableCell>
            <TableCell numeric>Protein (g)</TableCell>
          </TableRow>
        </TableHead>
        <TableBody>
          {rows.map(row => {
            return (
              <TableRow key={row.id}>
                <TableCell component="th" scope="row">
                  {row.name}
                </TableCell>
                <TableCell numeric>{row.calories}</TableCell>
                <TableCell numeric>{row.fat}</TableCell>
                <TableCell numeric>{row.carbs}</TableCell>
                <TableCell numeric>{row.protein}</TableCell>
              </TableRow>
            );
          })}
        </TableBody>
      </Table>
    </Paper>
  );
}

SimpleTable.propTypes = {
  classes: PropTypes.object.isRequired,
};

export default withStyles(styles)(SimpleTable);

我正在尝试测试显示的数据。例如,测试是否显示标题name``calories``fat``carbsprotein,并测试输入的每一行数据。

I have something like the following
it('testing', () => {
  const wrapper = mount(<SimpleTable />);

  expect(wrapper).toMatchSnapshot();
  expect(wrapper.find(TableCell).get(1)).stringMatching('Calories');
});

这将返回以下内容

<WithStyles(TableCell)><b>Calories</b></WithStyles(TableCell)>

如何测试每个字符串而不是整个上面的行?例如类似expect(wrapper.find(TabkeCell)).get(1)).toEqual('calories')

上面也返回了同一行

1 个答案:

答案 0 :(得分:2)

在特定元素上调用.html().text()将剥夺HOC包装程序(例如WithStyles)。

expect(wrapper.find(TableCell)).get(1).text()).toEqual('Calories')

但是,手动测试toMatchSnapshot()已涵盖的内容是否有任何价值?

如果您认为快照太冗长,以至于没有人会调查(使用默认酶的实现是如此!),您可以

 expect(wrapper.html()).toMatchSnapshot();