Skip to content

Errors thrown in useEffect are not being caught #305

Closed
@SachinSharmaE

Description

@SachinSharmaE

How to catch an throw Error which is thrown at first render ? for example

import React, { useState, useContext, useCallback } from 'react'

export function useCounter(initialValue = 0) {
  const [count, setCount] = useState(initialValue)

  React.useEffect(()=>{
  if (count > 100) {
    throw Error("It's over 100!")
  },[count])


  return { count}
}

and then i call the following code

import { renderHook, act } from '@testing-library/react-hooks'
import { useCounter } from './counter'

it('should throw when over 100', () => {
  const { result } = renderHook(() => useCounter(101))


  expect(result.error).toEqual(Error("It's over 100!"))
})

So how to catch an error that is thrown automatically on first render?

Metadata

Metadata

Assignees

No one assigned

    Labels

    enhancementNew feature or request

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions