我目前正在使用getByTestId()在我的React应用程序中进行测试。测试看起来像这样:
it('should be truthy when clicking to play or pause if "hasVideo" is true', () => {
const newProps = {
hasVideo: true
}
render(<VideoCardForm {...newProps} />);
const videoEl = screen.getByTestId('video-play-pause');
const result = fireEvent.click(videoEl);
expect(result).toBeTruthy();
}); 相关的DOM部分如下所示:
<video
data-testid="video-play-pause"
className={this.state.isPlaying ? classes.VideoOnPlay : classes.VideoPrep }
onClick={(event) => {
this.onVideoClick(this.props.url, event);
}}
src={`${this.props.url}`}
>
</video>这是可行的。但是在我看来,像这样向DOM添加一些东西:data-testid,仅仅是为了运行一个测试,对我来说有点老生常谈。有没有一种替代方案可以添加到DOM中,它实际上服务于语义目的,而不仅仅是允许运行测试?
发布于 2021-01-04 22:10:16
您可以通过在容器属性中呈现本身来获取DOM。
const { container } = render(...)。
如果视频是嵌套的DOM,则可以始终使用container.querySelector('video')来获取视频DOM。
https://stackoverflow.com/questions/65563923
复制相似问题