简体   繁体   English

在 React 中,如何测试组件内的渲染方法

[英]In React, how to test a render method inside a component

I have a component which has a render method that is used to render a table.我有一个组件,它有一个用于渲染表格的渲染方法。 Now I need to implement a unit test in react to test that method ( renderTaskAssign() )and see if the table was rendered successfully.现在我需要实现一个单元测试来测试该方法( renderTaskAssign() )并查看表格是否成功呈现。 Can anyone tell me how to do that?谁能告诉我怎么做? Here is the detail about the class that I hope I can write test.以下是我希望我可以编写测试的类的详细信息。

class TaskAssign extends Component {
  constructor(props) {
    super(props);
    this.renderTaskAssign = this.renderTaskAssign.bind(this);
  }

  renderTaskAssign() {
    if (this.props.data_loading) {
      return (
        <div className="dataloader">
        <ClipLoader
          color={types.LOADING_DATA_COLOR}
          loading={this.props.data_loading}
        />
        </div>);
    } else {
      if (this.props.current_tasks !== '') {
        const item_list = this.props.current_tasks.map((key, index) => {
          return (
              <TableRow key={index}>
              <TableRowColumn>{this.props.current_tasks[index]['pos']}</TableRowColumn>
              <TableRowColumn>{this.props.current_tasks[index]['name']}</TableRowColumn>
              <TableRowColumn>{this.props.current_tasks[index]['completion']}</TableRowColumn>
              <TableRowColumn>{this.props.current_tasks[index]['current_task']}</TableRowColumn>
              <TableRowColumn>{this.props.current_tasks[index]['percent_complete']}</TableRowColumn>
              <TableRowColumn>{this.props.current_tasks[index]['status']}</TableRowColumn>
              <TableRowColumn>Do nothing</TableRowColumn>
              </TableRow>
          );
          })
        return (
          <Table multiSelectable>
          <TableHeader>
            <TableRow>
            <TableHeaderColumn>Pos</TableHeaderColumn>
            <TableHeaderColumn>Installer</TableHeaderColumn>
            <TableHeaderColumn>Work Progress</TableHeaderColumn>
            <TableHeaderColumn>Current Task</TableHeaderColumn>
            <TableHeaderColumn>% Completion</TableHeaderColumn>
            <TableHeaderColumn>Status</TableHeaderColumn>
            <TableHeaderColumn>Add.Info</TableHeaderColumn>
            </TableRow>
          </TableHeader>
            <TableBody>
            {item_list}
            </TableBody>
            </Table>
          );
      }
    }
  }

  render() {
    return (
      <div>
        {this.renderTaskAssign()}
      </div>
    );
  }
}

const mapStateToProps=({ task })=> {
  const { current_tasks, error, data_loading } = task;
  return { current_tasks, error, data_loading };
};

export default connect(mapStateToProps)(TaskAssign);

I tried to use enzyme to test the component, here is the test code I wrote.我尝试用酶来测试组件,这里是我写的测试代码。 I don't know how to test the table in my case我不知道如何在我的情况下测试表格

it("test renderTaskAssign method", () => {
    const renderer = new ShallowRenderer();
    renderer.render(<Provider store={store}>
    <TaskAssign />
    </Provider>);
    const result = renderer.getRenderOutput();
    const taskComponent = new result.type.WrappedComponent();
    taskComponent.props = {
      current_tasks: [
        0: {
          completion: 0.76,
          current_task: 'REASSEMBLE DOORS',
          name: 'A. Smith',
          percent_complete: 0.5,
          pos: 'A1',
          status: 'Good'
        },
        1: {
          completion: 0.66,
          current_task: 'ASEASSEMBLE DOORS',
          name: 'B. Smith',
          percent_complete: 0.7,
          pos: 'B1',
          status: 'Soso'
        }
      ]
    };
    taskComponent.renderTaskAssign()
    console.log(taskComponent.renderTaskAssign().type);
  }
);

Actually, you should test the behavior of your component, not its implementation.实际上,您应该测试组件的行为,而不是它的实现。 From the outside of your component, you should not care about if it has a renderTaskAssign or what this function does, but only what the component does/render.从组件的外部来看,您不应该关心它是否具有renderTaskAssign或此函数的作用,而应该关心组件的作用/渲染。

What it seems you want to do is test your component with specific props, without waiting for your Redux connect to inject them into your component.您似乎想要做的是使用特定的 props 测试您的组件,而无需等待您的 Redux 连接将它们注入到您的组件中。 I suggest the following, where you only test your component, not your store :我建议如下,你只测试你的组件,而不是你的商店:

class TaskAssign extends Component {
  constructor(props) {
    super(props);
    this.renderTaskAssign = this.renderTaskAssign.bind(this);
  }

  renderTaskAssign() {
      // some render code
  }

render() {
    return (
      <div>
        {this.renderTaskAssign()}
      </div>
    );
  }
}

const mapStateToProps=({ task })=&gt; {
  const { current_tasks, error, data_loading } = task;
  return { current_tasks, error, data_loading };
};

export default connect(mapStateToProps)(TaskAssign);

export const TaskAssign // <- This enables you to test your component, without the mapStateToProps connection. 

and then :进而 :

import { TaskAssign } from './'; // <-- Import the 'unconnected' version

it("test renderTaskAssign method", () => {
    const renderer = new ShallowRenderer();
    renderer.render( // <- Directly inject your props, not need for an entire store
    <TaskAssign current_tasks={[
        0: {
          completion: 0.76,
          current_task: 'REASSEMBLE DOORS',
          name: 'A. Smith',
          percent_complete: 0.5,
          pos: 'A1',
          status: 'Good'
        },
        1: {
          completion: 0.66,
          current_task: 'ASEASSEMBLE DOORS',
          name: 'B. Smith',
          percent_complete: 0.7,
          pos: 'B1',
          status: 'Soso'
        }
      ]} />
    );
    const result = renderer.getRenderOutput();

    // Test whatever you want : 
    expect(wrapper.is(Table)).toEqual(true);
    expect(wrapper.find(TableRowColumn).length).toEqual(7);
  }
);

Now, from there (and completely out of scope :-) ) :现在,从那里(完全超出范围:-)):

  • I do not get it what is the utility of your renderTaskAssign function我不明白你的renderTaskAssign函数有什么用
  • It is recommanded to use functional components when possible (no lifecycle).建议尽可能使用功能组件(无生命周期)。
  • You could replace your map with another component你可以用另一个组件替换你的地图
  • You can use babel-plugin-jsx-control-statements to simplify your JSX你可以使用 babel-plugin-jsx-control-statements 来简化你的 JSX

So, I would actually write your component something like this :所以,我实际上会像这样编写你的组件:

const TaskAssign = ({ current_tasks, data_loading }) => (
  <div>
    <Choose>
      <When condition={data_loading} />
        <div className="dataloader">
          <ClipLoader
            color={types.LOADING_DATA_COLOR}
            loading={data_loading}
          />
          </div>
      </When>
      <When condition={current_tasks !== ''}>
        <Table multiSelectable>
          <TableHeader>
            <TableRow>
            <TableHeaderColumn>Pos</TableHeaderColumn>
            <TableHeaderColumn>Installer</TableHeaderColumn>
            <TableHeaderColumn>Work Progress</TableHeaderColumn>
            <TableHeaderColumn>Current Task</TableHeaderColumn>
            <TableHeaderColumn>% Completion</TableHeaderColumn>
            <TableHeaderColumn>Status</TableHeaderColumn>
            <TableHeaderColumn>Add.Info</TableHeaderColumn>
            </TableRow>
          </TableHeader>
            <TableBody>
              <For each="task" of={current_tasks} >
                <SomeItemTableRowComponent task={task} />
              </For>
            </TableBody>
            </Table>
          </When>
        </Choose>
      </div>
    );

const mapStateToProps=({ task })=&gt; {
  const { current_tasks, error, data_loading } = task;
  return { current_tasks, error, data_loading };
};

export default connect(mapStateToProps)(TaskAssign);

export const TaskAssign

Hope that helps希望有帮助

Basically, with Enzyme you can check if the inner component is rendered.基本上,使用Enzyme您可以检查内部组件是否已呈现。 For example:例如:

it('should use Table', () => {
    const wrapper = shallow(
      <TaskAssign />
    );
    expect(wrapper.is(Table)).toBe(true);
  });

Then you can check that this component contains another component.然后您可以检查该组件是否包含另一个组件。 For example:例如:

it('should render multiple header columns', () => {
    const wrapper = mount(
      <TaskAssign />
    );
    expect(wrapper.find(TableRowColumn).length).toBe(7);
  });

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM