【问题标题】:How to check with react testing library that the rendered element is of type 'div'?如何使用反应测试库检查渲染元素的类型为“div”?
【发布时间】:2022-11-11 07:40:48
【问题描述】:

我已经检查了这个答案:Check HTML element type for result of React Testing Library's getByText? 但不幸的是,div 没有分配默认角色(可以在这里检查:https://www.w3.org/TR/html-aria/#docconformance

所以我下面的测试失败了:

  it('should render as div when the "as" attribute is passed with a value of "div"', () => {
    render(<Button label={testText} as='div' data-testid='test-button'/>)

    expect(screen.getByTestId('test-button')).toBe('div')
  })

我无法找到一个有利于测试的查询。任何人都可以帮忙吗?

【问题讨论】:

  • 为什么不使用data-testid 属性并通过screen.getByTestId(xxx) 查询元素?
  • 谢谢@slideshowp2,我更新了问题

标签: react-testing-library


【解决方案1】:

要检查元素类型,您可以从 screen.getByTestId 返回的任何 HTMLElement 访问 nodeName

https://developer.mozilla.org/en-US/docs/Web/API/Node/nodeName

你可以尝试这样的事情:

  it('should render as div when the "as" attribute is passed with a value of "div"', () => {
    render(<Button label={testText} as='div' data-testid='test-button'/>)
    
    expect(screen.getByTestId('test-button').nodeName.toLowerCase()).toBe('div')
  })

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2019-12-25
    • 2021-04-07
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-09-28
    • 1970-01-01
    • 2020-09-16
    相关资源
    最近更新 更多