3

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?

2
  • Why not using data-testid attribute and query the element by screen.getByTestId(xxx)? Commented Feb 17, 2022 at 4:02
  • thanks @slideshowp2, I updated the question Commented Feb 17, 2022 at 7:20

1 Answer 1

3

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')
  })
Sign up to request clarification or add additional context in comments.

1 Comment

Great! in typescript I had to change just a little but is the same: expect(screen.getByTestId('test-button').nodeName.toLowerCase()).toBe('div');

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.