反应组件的单元测试

时间:2021-03-23 11:18:47

标签: reactjs jestjs react-testing-library

嗨,我是 React 测试的新手,我正在使用 React 测试库和 jest。请帮助我为以下代码编写测试用例。

  import React from 'react'

import {
  Loader,
  SectionTitle,
  ErrorLabel,
} from 'LookingGlass/common/components'

import LookingGlassPanelResultSection from 'LookingGlass/app/components/LookingGlassResultSection'

import constants from 'LookingGlass/constants'

import getErrorMessage from 'LookingGlass/app/utils/getErrorMessage'
import styles from './_.index.module.scss'

export default function LookingGlassPanelResults(props) {
  const { queryResult, isTimedOut, error, isServerDown, isLoading } = props

  if (isLoading)
    return (
      <Loader
        content={constants.Loader.loaderContent}
        active
        inline="centered"
        size="large"
      />
    )

  if (isServerDown) {
    return <ErrorLabel text={constants.error.message.error_404} />
  }

  if (isTimedOut) {
    return <ErrorLabel text={constants.requestsTimeout.msg} />
  }

  if (error) {
    return <ErrorLabel text={getErrorMessage(error)} />
  }

  if (!queryResult) return null

  return (
    <div>
      <hr className={styles.seperateLine} />
      <SectionTitle text={constants.QueryPanelResult.resultPanel} />
      <LookingGlassPanelResultSection queryResult={queryResult} />
    </div>
  )
}

ErrorLabel 是使用图标和显示文本的不同组件。在组件内部使用组件的地方如何编写测试?

这是我的测试用例:-

 const renderComponent = (props) =>
    render(<LookingGlassPanelResults {...props} />)
    test('Verify that isServerDown  parameter works', () => {
        const component = renderComponent({ isServerDown: true })
        const { getByText } = within(component)
        expect(
          getByText('Service unavailable. Please try later'),
        ).toBeInTheDocument()
      })

错误:-`

TypeError: Expected container to be an Element, a Document or a DocumentFragment but got Object.

      20 |     const { getByText } = within(component)
      21 |     expect(
    > 22 |       getByText('Service unavailable. Please try later'),
         |       ^
      23 |     ).toBeInTheDocument()
      24 |   })`
  

1 个答案:

答案 0 :(得分:0)

这里首先我们需要通过test-id获取ErrorLabel,然后检查期望

test('Verify that isServerDown  parameter works', () => {
    const component = renderComponent({ isServerDown: true })
    const { getByTestId } = component

    expect(getByTestId('ErrorLabel')).toHaveTextContent(
      'Service unavailable. Please try later',
    )
  })