New to RTL and trying to understand how to do things idiomatically. I have a list with a dynamic element (it appears in some rows and not others).
Here's the component:
import React from 'react'
export default function DummyList ({ items }) {
return <div>
{items.map(item => <ListItem item={item} key={item.name} />)}
</div>
}
export function ListItem ({ item: { name, isActive } }) {
return <div data-testid='list-item'>
<span>{name}</span>
{isActive && <span>Active!</span>}
</div>
}
and here's the test
import React from 'react'
import { render, getByText, queryByText, getAllByTestId } from '@testing-library/react'
import '@testing-library/jest-dom/extend-expect'
import DummyList from './index'
describe('DummyList', () => {
it('renders', async () => {
const items = [
{ name: 'Unused Item' },
{ name: 'Used Item', isActive: true }
]
render(<DummyList items={items} />)
const listItems = getAllByTestId(document.body, 'list-item')
expect(listItems).toHaveLength(2)
expect(getByText(listItems[0], 'Unused Item')).toBeInTheDocument()
expect(queryByText(listItems[0], 'Active!')).not.toBeInTheDocument()
expect(getByText(listItems[1], 'Used Item')).toBeInTheDocument()
expect(queryByText(listItems[1], 'Active!')).toBeInTheDocument()
})
})
Questions
1) Is there a way to avoid using data-testid in this scenario? Or is this a reasonable use of that escape hatch?
2) More generally, is there a more idiomatic way of using RTL for testing this kind of component?
Thanks!
I would render your list using ul
and li
tags to make it more semantic. If for some reason you can't do that you can still add the aria-role
attributes. Once that's done you can use getAllByRole('listitem')
to get the elements:
describe('DummyList', () => {
it('render the items', async () => {
const items = [
{ name: 'Unused Item' },
{ name: 'Used Item', isActive: true }
]
// You can get the query methods directly from render
const { getAllByRole } = render(<DummyList items={items} />)
const listItems = getAllByRole('listitem')
expect(listItems).toHaveLength(2)
// I use a `forEach` to make the test dynamic in case we decide
// to generate items dynamically in the future
// This method is also implicitly testing the order
listItems.forEach((item, index) => {
// You can import wihthin from @testing-library/react
const { getByText, queryByText } = within(item)
const { name, isActive } = items[index]
expect(getByText(name)).toBeInTheDocument()
isActive
? expect(getByText('Active!')).toBeInTheDocument()
: expect(queryByText('Active!')).not.toBeInTheDocument()
})
})
})
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With