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!
Aucun commentaire:
Enregistrer un commentaire