如何为使用Table组件材料UI的组件编写测试?

时间:2019-04-12 20:09:23

标签: reactjs testing enzyme

为以下代码编写测试时遇到很多麻烦:

import { Table, TableBody, TableCell, TableHead, TableRow, Tooltip } from '@material-ui/core';
import React, { Component } from 'react';

const Status = ({ id, dependency}) => {

  let text, tooltipText;

  if (id === 'something' ) {
    tooltipText = `Some helpful text.`;
    text = "undefined";
  } else if (id === 'other' ) {
    tooltipText = `Some other helpful text.`;
    text = "undefined";
  } else{
    tooltipText = `Unknown`;
    text = "unknown";
  } 
  return (
    <Tooltip title={tooltipText} >
        <span>
          {text}
        </span>
    </Tooltip>
  );
};

class StatusList extends Component {

  render() {
    const { cardTitle, dependencies, id } = this.props;

    if (!dependencies) {
      return null;
    }

    return (
      <Card title={cardTitle}>
        <Table>
          <TableHead>
            <TableRow>
              <TableCell>ID</TableCell>
              <TableCell>STATUS</TableCell>
            </TableRow>
          </TableHead>
          <TableBody>
            {dependencies.map(dep => (
              <TableRow key={dep.id}>
                <TableCell>
                  <URL to={`/${dep.id}`}>{dep.id}</URL>
                </TableCell>
                <TableCell>
                  <Status id={id} dependency={dep} />
                </TableCell>
              </TableRow>
            ))}
          </TableBody>
        </Table>
      </Card>
      );
   }
};

到目前为止,我进行了以下测试:

import { shallow } from 'enzyme';

describe('test', () => {
const props = {
    cardTitle: "Dependencies",
    dependencies: [id: 'something'],
    id: 'my-id'
};
it('renders', () => {
    const wrapper = shallow(<Status {...props} />);
    expect(wrapper.find(TableBody).find(TableRow)).toHaveLength(4);
  });
}); 

这可以正常工作,但是我现在想断言Status函数正在渲染什么-即,我想检查其中的逻辑,并确保渲染正确的tooltipText。我尝试编写以下测试:

it('renders row with expected status', () => {
    const wrapper = shallow(<StatusList {...props} />);
    expect(wrapper.find(Table).find(TableBody).find(TableRow).first().find(TableCell).find('Tooltip').props.title).toEqual('Some helpful text.');
  });

但是我得到了错误:

  

期望值等于:         “一些有用的文字。”       收到:         未定义

我不确定自己在做什么错..

1 个答案:

答案 0 :(得分:0)

使用酶的shallow()渲染组件时,仅渲染第一级,这意味着第一浅层的输出将包含<Status />组件,但不包含任何该组件的子代。

为了能够对Status的孩子做出断言,我们必须更深入地提出一个层次,然后然后做出断言:

it('renders row with expected status', () => {
    const wrapper = shallow(<StatusList {...props} />);
    const firstTableRow = wrapper.find(Table).find(TableBody).find(TableRow).first();
    const tableCell = firstTableRow.find(TableCell);
    const status = tableCell.find('Status');

    const statusWrapper = status.shallow(); // now we can dive into children!
    const tooltip = statusWrapper.find(Tooltip);

    expect(tooltip.props().title).toEqual('Some helpful text.');
});

还请记住使用.props().propName而不是.props.propName,因为.props()是包装程序的函数而不是属性。

请参阅this simplified codesandbox中包含的酶测试类似成分。