Che*_*erd 8 jsx reactjs jestjs
我正在使用 React 16.2 并想测试我的组件功能。
当调用其中一个函数时,它返回一个包含 Button 的元素数组,这些元素具有我想要测试的 onClick 道具。
问题是,我只能找到数组中的第一个元素。
代码如下:
Comp.js
class Comp extends Component {
renderButtons = () => {
const list = [];
list.push(<Button key="first" onClick={() => console.log('foo')}/>);
list.push(<Button key="second" onClick={() => console.log('bar')}/>);
list.push(<Button key="third" onClick={() => console.log('baz')}/>);
return list;
}
render() {
return (
<div>Empty div</div>
)
}
}
Run Code Online (Sandbox Code Playgroud)
Comp.test.js
test('.renderButtons', () => {
const comp = new Comp();
const component = renderer.create(comp.renderButtons());
const root = components.root;
// Using root.findByProps({key: 'second'}); throws an error
});
Run Code Online (Sandbox Code Playgroud)
技术栈:
React 16.2.0Jest 21.2.1React-test-renderer: 16.2.0这是一个较旧的问题,但似乎有很多观点,所以我将添加一个答案。
“key” 属性(以及“ref” 属性)是一个保留的 React 属性,如果被访问将会抛出错误。任何其他 prop 都可以在 findByProps 函数中使用。测试实例上还提供了其他功能,例如 findAllByType 。
这是一个例子:
const SimpleComponent = ({text}) => (<div>{text}</div>);
const ListComponent = () => {
const list = [];
list.push(<SimpleComponent key="first" text="the first one" />);
list.push(<SimpleComponent key="second" text="the second one" />);
list.push(<SimpleComponent key="third" text="the third one"/>);
return list;
}
test('ListComponent renders correctly', () => {
const component = renderer.create(<ListComponent/>);
const list = component.root.findAllByType(SimpleComponent);
expect(list.length).toBe(3);
expect(list[1].props.text).toBe('the second one');
const third = component.root.findByProps({text: 'the third one'});
expect(third.type).toBe(SimpleComponent);
});
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
3727 次 |
| 最近记录: |