使用react-testing-library测试具有动态内容的列表的惯用方式是什么

时间:2019-08-09 18:49:46

标签: reactjs testing react-testing-library

是RTL的新手,它试图理解习惯用法。我有一个包含动态元素的列表(它显示在某些行中,而不是其他行中。)

以下是组件:

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

这是测试

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

问题

1)有没有一种方法可以避免在这种情况下使用data-testid?还是对逃生舱口的合理使用?

2)更笼统地说,是否有使用RTL来测试这种组件的更惯用的方法?

谢谢!

1 个答案:

答案 0 :(得分:1)

我将使用ulli标签渲染您的列表,使其更具语义。如果由于某些原因您不能执行此操作,则仍然可以添加aria-role属性。完成后,您可以使用getAllByRole('listitem')来获取元素:

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