【问题标题】:React hook unit test反应钩子单元测试
【发布时间】:2020-01-08 11:39:24
【问题描述】:

我有以下几点:

const Repairs: React.FC<RepairsProps> = ({repairs, repairsPropertyLoad}) => {
  const { t } = useTranslation()
  const [isARepair, setRepair] = useState(true)
  const handleOnClick = () => { 
    setRepair(false)
    repairsPropertyLoad('token')
  }

  return ( isARepair ? <p>on</p> : <p>off</p> )
  ...

因为它也是一个连接组件,所以我添加了以下测试:

describe('Repairs', () => {
  let store: any
  let component: any

  beforeEach(() => {
    store = mockStore({
      repairs: mockRepairs
    })

    store.dispatch = jest.fn()

    component = render(
      <Provider store={store}>
        <Repairs />
      </Provider>
    )

  })

  it('should render the Repairs component correctly', () => {
    expect(component).toMatchSnapshot()
  })

  it('should find the repair button in the document', () => {
    const { getByText } = component

    const repairsButton = getByText('Repair')
    expect(repairsButton).toBeInTheDocument()
  })
})

我如何测试isARepair 标志场景(真假)以便我可以快照offon 结果?

【问题讨论】:

    标签: javascript reactjs unit-testing jestjs


    【解决方案1】:

    我强烈建议您编写测试,就好像最终用户正在使用您的 UI。例如,当用户单击按钮时,您将 setIsRepair 设置为 false。您可以使用fireEvent模拟按钮点击:

    fireEvent.click(repairsButton);
    expect(getByText('off')).not.toBeNull();
    // this might not be the exact code but you get the gist
    

    如果你想测试你的钩子,你应该创建一个自定义钩子,把它渲染成一个虚拟的测试组件,然后测试返回值;或使用React Hooks Testing Library。但是,如果您的状态逻辑与单个 useState 一样简单,我建议您不要测试它,因为您实际上是在测试 React 的 useState 而不是测试您自己的状态逻辑。我的建议是测试由许多部分组成的状态逻辑(它足够复杂,需要测试)。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2023-04-01
      • 1970-01-01
      • 1970-01-01
      • 2019-09-30
      • 2020-02-16
      • 2020-07-07
      • 1970-01-01
      • 2017-09-24
      相关资源
      最近更新 更多