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

326
Views
Broma: la función que debería lanzar no pasa y la prueba fallará

Quiero probar una función A que llama a muchas otras funciones dentro de ella que pueden arrojar errores.

Aquí hay una abstracción de mi código:

 // file A.ts const A = (args: any[]): boolean => { (() => { // nested function which throws throw new RangeError("some arg not correct") })() return true }

y

 // file main.test.ts test("should throw an error", () => { expect(A()).toThrow() })

¿Cómo pruebo esto apropiadamente en Jest?

La prueba no tendrá éxito y jest registrará el error lanzado. Aquí hay una caja de arena y aquí está el resultado de la prueba que puede ver si ejecuta test :

ingrese la descripción de la imagen aquí

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

0

No soy bueno con mecanografiado, así que he escrito los ejemplos usando JS normal.

Resulta que no necesita llamar a la función A para probar si arroja :

 // throw.test.js const A = () => { (() => { // nested function which throws throw new RangeError("some arg not correct") })(); }; test("should throw an error", () => { expect(A).toThrow(); })

que salidas

 > jest PASS ./throw.test.js ✓ should throw an error (6ms) Test Suites: 1 passed, 1 total Tests: 1 passed, 1 total Snapshots: 0 total Time: 4.404s Ran all test suites.

Si desea llamar a la función, digamos para pasar un argumento, llámelo dentro de otra función que se pasa a la expectativa:

 // throw2.test.js const A = () => { (() => { // nested function which throws throw new RangeError("some arg not correct") })(); }; test("should throw an error", () => { expect(() => A('my-arg')).toThrow(); })
about 4 years ago · Juan Pablo Isaza Report

0

Refactoricé una función que era asíncrona para que ya no fuera así y recibía este error. Entonces, si tiene una función asíncrona interna, use este enfoque:

 test("async function throws", async() => { await expect(() => A('my-arg')).rejects.toThrow(); })

También puede hacer algunas comprobaciones más específicas, como qué tipo de error y el mensaje, etc.

 test("async function throws", async() => { await expect(() => A('my-arg')).rejects.toThrow(MyError("Specific Error Message"); })
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!