【问题标题】:How can I pass a value to a component that doesn't have props in order to test it?如何将值传递给没有道具的组件以对其进行测试?
【发布时间】:2021-02-10 00:34:04
【问题描述】:

我正在测试一个没有 props 的组件,但它希望使用来自上下文的数据来实现。

假设这是我的组件:

export const MyComponent: FC = () => {
  const { arrayOfObjects } = useFn()

  return arrayOfObjects.length ? arrayOfObjects.map((q: VariableConfig, i: number) => (
    <SelectedQuestionTile
      {...{
        key: i + 1,
        question: q,
        questionIdx: i,
      }}
    />
  )) : <p>No Data</p>
}

这是我目前唯一的测试:

import React from 'react'
import { render, screen } from '@testing-library/react'
import { MyComponent } from './MyComponent'

describe('MyComponent', () => {
  test('It renders with empty containers', () => {
    render(<MyComponent />)
    expect(screen.getByText("No Data")).toBeInTheDocument()
  })
})

在那里,我正在测试组件的初始状态,该状态呈现几个空容器,因为它们还没有任何数据。数据位于const { arrayOfObjects } = useFn() 行上。 arrayOfObjects 只是硬编码的数据,不是动态的。

我错过了什么?

【问题讨论】:

    标签: javascript reactjs unit-testing testing react-testing-library


    【解决方案1】:

    通过将其包装在实际的上下文提供程序中进行测试。

    render(
      <MyContext.Provider value={{ arryOfObjects }}>
        <MyComponent />
      <MyContext.Provider>
    )
    

    【讨论】:

      猜你喜欢
      • 2016-10-16
      • 1970-01-01
      • 2019-12-19
      • 1970-01-01
      • 2019-02-26
      • 1970-01-01
      • 2018-08-01
      • 2021-10-29
      • 2019-04-24
      相关资源
      最近更新 更多