【发布时间】: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