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
:
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(); })
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"); })