Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

90
Views
Cómo probar un gancho personalizado asíncrono de React que devuelve un valor booleano cuando se resuelve/rechaza una llamada a la API

Tengo un gancho React personalizado de la siguiente manera:

 export function useValidPolicyReference({ token, tenant, policyReference, }: UseValidPolicyReferenceProps): Record<string, boolean> { const [isValid, setIsValid] = React.useState<boolean>(true); React.useEffect(() => { async function fetchOnMount(): Promise<void> { try { await getPolicyByReference({ policyReference: policyReference as string, tenant, token, }); } catch (error) { setIsValid(false); } } if (tenant !== '' && policyReference !== null && token !== '') { fetchOnMount(); } }, [policyReference, tenant, token]); return { isValidPolicyReference: isValid, };

Quiero probar que isValidPolicyReference devolverá verdadero cuando getPolicyByReference no arroje y falso cuando lo haga.

Mi prueba para el caso real es la siguiente:

 test('should be truthy if the policy reference is valid', () => { (getPolicyByReference as jest.Mock).mockImplementationOnce(() => Promise.resolve(true) ); const { result: { current }, waitForNextUpdate, } = render(); expect(current.isValidPolicyReference).toBeTruthy(); waitForNextUpdate(); expect(getPolicyByReference).toHaveBeenCalledWith({ token, tenant, policyReference, }); expect(current.isValidPolicyReference).toBeTruthy(); });

Que pasa pero la prueba para el caso falso no:

 test('should be falsy if the policy reference is invalid', () => { (getPolicyByReference as jest.Mock).mockImplementationOnce(() => Promise.reject(new Error('policy reference error')) ); const { result: { current }, waitForNextUpdate, } = render(); expect(current.isValidPolicyReference).toBeTruthy(); waitForNextUpdate(); expect(current.isValidPolicyReference).toBeFalsy(); });

Falla por dos motivos:

  1. isValidPolicyReference nunca regresa como falso
  2. También hay un error de console.error registrado en esta línea setIsValid(false); donde Warning: Can't perform a React state update on an unmounted component.

No estoy seguro de cómo hacer que getPolicyByReference lance Jest para que el gancho devuelva el valor falso.

¿Qué no estoy haciendo correctamente? ¿Debería envolver mis casos de prueba en await async ? ¿Debería burlarme de axios.get en lugar de getPolicyByReference ?

about 4 years ago · Juan Pablo Isaza
1 answers
Answer question

0

También hay un error de consola registrado en esta línea setIsValid(false); donde Advertencia: no se puede realizar una actualización de estado de React en un componente desmontado.

Creo que el problema es que está tratando de probar el gancho solo con broma, cuando los ganchos solo se pueden llamar desde componentes internos.

La biblioteca de pruebas de reacción tiene muy buenos ayudantes para simplificar los ganchos de prueba, este artículo es bastante informativo al respecto.

about 4 years ago · Juan Pablo Isaza Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!