【问题标题】:Testing React component built with a function测试使用函数构建的 React 组件
【发布时间】:2020-02-05 12:26:31
【问题描述】:

对使用函数构建的 React 组件进行实验测试。在此之前我习惯这样做:

 const animalsTable = shallow(<Animals/*props*//>); 
 animalsTable.instance().functionToTest();

ShallowWrapper.instance() returns null 用于函数,所以现在跟随Alex Answer 我正在直接测试 DOM。 下面是我的 React 组件的简化版本和一些测试:

反应组件:

import React, {useState, useEffect} from 'react';
import ReactTable from 'react-table';

const AnimalsTable = ({animals}) => {
  const [animals, setAnimals] = useState(animals);
  const [messageHelper, setMessageHelper] = useState('');

  //some functions

  useEffect(() => {
    //some functions calls
  }, []);

  return (
    <div>
      <ReactTable id="animals-table" 
      //some props
      getTrProps= {(state, rowInfo) => {
        return {
          onClick: (_event) => {
            handleRowSelection(rowInfo);
          }
        };
      }}
      />
      <p id="message-helper">{messageHelper}</p>
    </div>
  );
};

export default AnimalsTable;

测试:

//imports
describe('AnimalsTable.computeMessageHelper', () => {
  it('It should display the correct message', () => {
    const expectedResult = 'Select the correct animal';

    const animalsTable = mount(<AnimalsTable //props/>);

    const message = animalsTable.find('#message-helper').props().children;

    expect(message).to.equal(expectedResult);
  });
});

这个很好用。

我的问题是如何测试一行点击ReactTable组件来测试handleRowSelection方法?

我目前的测试是:

describe('AnimalsTable.handleRowSelection', () => {
  it('When a selection occurs should change the animal state', () => {
    const animalsTable = mount(<AnimalsTable //props/>);

    const getTrProps = channelsSelectionTable.find('#animals-table').props().getTrProps;

    //what to do from here to trigger onClick() ?
  });
});

编辑: 我认为正确的方法是这样,但不会触发 handleRowSelection :

const animalsTable= mount(<AnimalsTable //props />);
const rows = animalsTable.find('div.rt-tr-group');
rows.at(0).simulate('click');

我会尝试添加一个简单的codeSandBox

【问题讨论】:

  • 浅渲染只渲染一层所以可能不是 ReactTable,也许试试render 代替?
  • 是的,之前我使用的是基于类的组件,我使用的是 Shallow,现在我正在使用 mount()

标签: reactjs enzyme react-hooks react-table


【解决方案1】:

这是我找到的解决方案,我必须用 Chrome 检查类名,然后用它来模拟对表格第一行的点击:

it('When an animal selection occurs, it change the checkbox state', () => {
    const animalsTable = mount(<AnimalsTable //props/>);

    const rows = animalsTable.find('div.rt-tr.-odd');
    rows.at(0).simulate('click');

    const checkBoxResult = animalsTable.find('input[type="checkbox"]')
                                          .at(0).props().checked;

    expect(checkBoxResult).to.equal(true);
  });

可能不是正确的测试方法,但这个方法有效。

【讨论】:

    猜你喜欢
    • 2015-10-11
    • 1970-01-01
    • 2021-11-17
    • 2018-07-25
    • 2014-10-21
    • 1970-01-01
    • 2019-08-06
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多