0

I'm having a problem trying to access state and setState using react-hooks-testing-library.

I've followed examples from various sources using Provider but it doesn't work

Pay.tsx

export const Pay = (): JSX.Element => {
  const location = useLocation()
  const [paymentState, setPaymentState] = useState<
    'IDLE' | 'LOADING' | 'SUCCESS' | 'FAILURE'
  >('IDLE')

  return (
    <View style={{ minHeight: '100vh' }}>
      {paymentState === 'LOADING' && <PaymentLoading />}
      {paymentState === 'SUCCESS' && <PaymentResult status="SUCCESS" />}
      {paymentState === 'FAILURE' && <PaymentResult status="FAIL" />}

Pay.test.tsx

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

it(`Payment Input`, async () => {
const wrapper: FC = ({ children }) => (
  <SafeAreaProvider>
    <Router history={history}>
     <Route path="/pay">{children}</Route>
    </Router>
  </SafeAreaProvider>
)
const { result: payHook, waitForNextUpdate } = renderHook(() => Pay(), {
  wrapper,
})
console.log(payHook.current)
})

Expected of console.log(payHook.current)

{paymentState: 'IDLE', setPaymentState: [Function]}

Result that i got of console.log(payHook.current)

{        '$$typeof': Symbol(react.element),
        type: {
          '$$typeof': Symbol(react.forward_ref),
          render: [Function (anonymous)] { displayName: 'View' }
        },
        key: null,
        ref: null,
        props: {
          style: { minHeight: '100vh' },
          children: [ [Object], false, false, false ]
        },
        _owner: <ref *1> FiberNode {
          tag: 0,
          key: null,
          elementType: [Function: TestComponent],
          type: [Function: TestComponent],
Sofyan Setiawan
  • 347
  • 1
  • 6
  • 15
  • 3
    IMHO there is no need to use react-hooks-testing-library . The library was meant to test custom hooks . https://github.com/testing-library/react-hooks-testing-library#when-to-use-this-library . In your case it is just enough to test whether the component is rendered correctly for you different states. – Shyam Jul 13 '21 at 08:47
  • Author of react-hooks-testing-library here. @Shyam is correct. This is not what the library is for. You want to be using `@testing-library/react` and testing your component. – Michael Peyper Aug 16 '21 at 09:47

0 Answers0