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