【问题标题】:Alternative to using `getByTestId()` in React-testing-library在 React-testing-library 中使用 `getByTestId()` 的替代方法
【发布时间】:2021-04-10 07:40:15
【问题描述】:

我目前正在使用 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 的替代方案,它实际上服务于语义目的而不仅仅是允许运行测试?

【问题讨论】:

    标签: create-react-app react-testing-library


    【解决方案1】:

    您可以通过在容器属性中渲染自身来获取 DOM。

    const { container } = render(...).

    如果 video 是嵌套的 DOM,您始终可以使用 container.querySelector('video') 来获取视频 DOM。

    【讨论】:

    • 因此,虽然这使测试通过,但当我更改道具时它将不起作用。换句话说,当测试应该失败时,它不会。所以,像这样的结构,它不是一个有用的测试。请注意,当我分配 testid 时,测试会按预期失败。
    • 如果我理解正确,您想检查当 prop 更改正确时该类是否正确应用。在这种情况下,您应该稍微更改一下测试,以期望在 prop 更改时应用在 DOM 上的类的更改。
    猜你喜欢
    • 2023-01-13
    • 2021-09-29
    • 1970-01-01
    • 2019-07-07
    • 2020-01-31
    • 2021-02-14
    • 2019-05-21
    • 2019-11-11
    • 2023-01-05
    相关资源
    最近更新 更多