如何使用React测试库测试该组件-只是这个新测试库的入门

时间:2020-01-17 16:13:01

标签: javascript reactjs react-testing-library

我有2个要学习使用react-testing-library进行测试的组件,但我陷于中间。

我的组件是NestedLists.js

import React from 'react'

export const NestedLists = ({filteredData}) => {
    return (
        <ul>
            {filteredData && filteredData.map((m,i) => {
                return (
                <li key={i}>
                 {m.id}
                 {m.children && <NestedLists filteredData={m.children} />}
                </li>
        );
      })}
        </ul>
    )
}


和filteredData属性是一个具有以下值的数组::

export const filteredData = [{
    "id": 1,
    "label": "List item 1",
    "parent_id": 0
  },
  {
    "id": 9,
    "label": "List item 9",
    "parent_id": 8
  },
  {
    "id": 8,
    "label": "List item 8",
    "parent_id": 1
  },
  {
    "id": 5,
    "label": "List item 5",
    "parent_id": 1
  },
  {
    "id": 6,
    "label": "List item 6",
    "parent_id": 1
  },
  {
    "id": 7,
    "label": "List item 7",
    "parent_id": 1
  },
  {
    "id": 10,
    "label": "List item 10",
    "parent_id": 8
  },
  {
    "id": 2,
    "label": "List item 2",
    "parent_id": 0
  }
]

我已经做过一些测试,但是这些没有用。请提出一些我可以使用测试库在上述组件上进行的测试:

我的npt工作正常或失败的测试如下:

NestedLists.test.js

import React from 'react';
import { render, waitForElement } from '@testing-library/react';
import {NestedLists} from '../components/NestedLists';
import {apiData} from '../fixtures'


test('renders NestedLists components', async () => {
  const { getByText } = render(<NestedLists filteredData = {apiData} />);
  await waitForElement(() => {
      expect(getByText(props.filteredData[0].id)).toBeTruthy();
  })
});

1 个答案:

答案 0 :(得分:0)

您可能不需要测试这种简单的组件,但是如果您仍然想添加测试,则可以执行以下操作。

您可能需要从测试库导入jest-dom才能使用toBeInTheDocument

import React from 'react';
import { render} from '@testing-library/react';
import {NestedLists} from '../components/NestedLists';
import {apiData} from '../fixtures'


test('renders NestedLists components', async () => {
  const { findByText} = render(<NestedLists filteredData = {apiData} />);
  const firsListItem = await getByText(apiData[0].id);
  epxect(firstListItem).toBeInTheDocument()
});