Search code examples
react-testing-library

How to check with react testing library that the rendered element is of type 'div'?


I have checked this answer: Check HTML element type for result of React Testing Library's getByText? but unfortunately, div does not have a default role assigned (as can be checked here: https://www.w3.org/TR/html-aria/#docconformance)

So my below test fails:

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

I am not able to find a query which would be good for testing this. Can anyone help?


Solution

  • To check the element type you could access the nodeName from any HTMLElement returned by the screen.getByTestId.

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

    You could try something like that:

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