我有这样一个组成部分:
import React, { Component } from 'react';
export class TopicsList extends Component {
constructor(props) {
super(props);
this.state = {
topics: [...],
};
this.references = [];
}
getOrCreateRef(id) {
if (!this.references.hasOwnProperty(id)) {
this.references[id] = React.createRef();
}
return this.references[id];
}
render() {
const {
topics
} = this.state;
return (
<div>
<ul>
{topics.map((topic) => (
<TopicItem
key={topic.id}
topic={topic}
ref={this.getOrCreateRef(topic.id)}
/>
)
)}
</ul>
</div>
)
}
}
const TopicItem = React.forwardRef((props, ref) => {
return (
<li
>
<p>{props.name}</p>
<i
className="fal fa-plus"
/>
</li>
);
});
我编写了测试以测试将显示多少li个项目:
test('should render 3 li items', () => {
console.log(wrapper.debug())
expect(wrapper.find('TopicItem').length).toBe(3);
});
但是我的测试失败了,因为他们开玩笑地认出了:
<ul>
<ForwardRef topic={{...}} />
<ForwardRef topic={{...}} />
<ForwardRef topic={{...}} />
</ul>
如何测试随React.forwardRef返回的组件? 我无法在互联网上或此处找到合适的解决方案。