gpt4 book ai didi

reactjs - 如何使用 React 渲染器在 Jest 中测试 JSX 元素数组

转载 作者:行者123 更新时间:2023-12-03 13:38:20 25 4
gpt4 key购买 nike

我正在使用 React 16.2,并且想测试我的组件功能。
当调用其中一个函数时,它返回一个带有按钮的元素数组,其中有一个我想测试的 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>
)
}
}

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

技术堆栈:

  • React 16.2.0
  • Jest 21.2.1
  • react 测试渲染器:16.2.0

最佳答案

这是一个较旧的问题,但似乎得到了很多浏览,因此我将添加一个答案。

“key”属性(以及“ref”属性)是一个保留的 React 属性,如果访问它会抛出错误。任何其他 prop 都可以在 findByProps 函数中使用。 Test Instance 上提供了其他功能,例如 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);
});

关于reactjs - 如何使用 React 渲染器在 Jest 中测试 JSX 元素数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48076699/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com