0

I have to create react component having image and text box, so My task is to test

  1. Image or Text box is Left or right aligned , as needed
  2. Image or Text box is Top or bottom aligned, as needed

By passing input variant as textLeft or textRight

Example Component

enter image description here

Any Help?

Thanos
  • 45
  • 1
  • 10

1 Answers1

1

If they both had the same aria-label or another selector you could use the getAllBy query which would give you an array of items in order they find them so then you could check the children by using within to query inside those.

Something like this would work.

const Component = () => {
  return (
    <>
      <div aria-label="card">
        <img alt="image example" />
      </div>
      <div aria-label="card">
        <h1>This is heading</h1>
      </div>
    </>
  )
}

import { render, screen, within } from '@testing-library/react'

test('React Testing Library works!', () => {
  render(<Component />)
  const cards = screen.getAllByLabelText('card')
  expect(cards).toHaveLength(2)
  expect(within(cards[0]).getByAltText('image example'))
  expect(within(cards[1]).queryByAltText('image example')).not.toBeInTheDocument()

  expect(within(cards[1]).getByText('This is heading'))
  expect(within(cards[0]).queryByText('This is heading')).not.toBeInTheDocument()
})

Richard Hpa
  • 2,353
  • 14
  • 23