Экспериментальное тестирование для компонента React, созданного с помощью функции. До этого я выполнял:
const animalsTable = shallow(<Animals/*props*//>);
animalsTable.instance().functionToTest();
ShallowWrapper.instance() returns null
для функции, поэтому теперь следую Alex Answer Я тестирую DOM напрямую. Ниже приведена упрощенная версия моего компонента React и некоторых тестов:
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');
попробую добавить простой код SandBox