1

Experimenting testing for React component built with a function. Before that I was used to do :

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

ShallowWrapper.instance() returns null for a function so now following Alex Answer I am testing the DOM directly. Below a simplified version of my React component and some tests :

React component :

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;

Test :

//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);
  });
});

This one is working well.

My issue is how to test a row click on the ReactTable component to test the handleRowSelection method?

My current test is :

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() ?
  });
});

EDIT : I think the correct way would be like that but handleRowSelection is not triggered :

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

I will try to add a simple codeSandBox

Logan Wlv
  • 3,274
  • 5
  • 32
  • 54

1 Answers1

1

Here the solution I found out, I had to inspect the classes names with Chrome then use it to simulate a click on the first row of the table :

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);
  });

Might not be the correct way to test it but this one is working.

Logan Wlv
  • 3,274
  • 5
  • 32
  • 54