【问题标题】:React Testing: How to test useState and boolean if Statements in ReactReact Testing: How to test useState and boolean if Statements in React
【发布时间】:2022-12-02 03:30:11
【问题描述】:

I'm new to testing and I'm trying to test a simple if statement but not sure how to go about it. Here's the component:

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>
)

Here's my Tests:

THIS TEST IS PASSING (but I don't think it's a good test.)
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()
})

THIS TEST IS **NOT** PASSING
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()
})

Any help on this would be great, thanks!

【问题讨论】:

    标签: reactjs react-testing-library


    【解决方案1】:

    You shouldn't test React. Instead of that you should test the UI.

    test('Should render something when clicked', () => {
     // render component
     render(<MyComp />)
     
     // get button to do something
     const openButton = screen.getByTestId('open-button');
    
     // simulate click on it
     fireEvent.click(openButton)
     
     // test that something happen after the click
     expect(screen.queryByLabelText('Some text')).toBeInTheDocument()
    })
    

    【讨论】:

      猜你喜欢
      • 2022-12-26
      • 2022-12-28
      • 2022-12-02
      • 2022-12-02
      • 2022-12-26
      • 2022-12-02
      • 2022-12-27
      • 2022-12-02
      • 2022-12-26
      相关资源
      最近更新 更多