You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

React测试:如何测试useState与布尔值条件语句

React组件条件渲染测试求助

我是测试新手,正在尝试测试React组件中的简单条件语句,但不知如何操作。以下是我的组件代码:

const [open, setOpen] = useState<boolean>(true);

const exitToast = (isOpen: boolean) =>
 isOpen ? setOpen(false) : setOpen(true);

return(
<div>
 <Toast
   label={<span>Incorrect Info</span>}
   isOpen={open}
   type='error'
   closeIcon
   onClose={() => closeTost(true)}
  />
</div>
)

我的测试代码:

该测试已通过(但我认为这不是一个好测试)

test('Should not show text "Incorrect Info" when isOpen is true', () => {
 render(<MyComp />)
 const toastWrapper = () => {
  const [open, setOpen] = useState<boolean>(true)
  return setOpen(false)
 }
 expect(screen.queryByLabelText('Incorrect Info')).not.beInTheDocument()
})

该测试未通过

test('Should show text "Incorrect Info" when isOpen is false', () => {
 render(<MyComp />)
 const toastWrapper = () => {
  const [open, setOpen] = useState<boolean>(true)
  return setOpen(true)
 }
 expect(screen.queryByLabelText('Incorrect Info')).toBeInTheDocument()
})

恳请各位提供帮助,谢谢!


内容的提问来源于stack exchange,提问作者Callie

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.10 14:30:43