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

91
Views
Prueba de broma para promesa asíncrona con async/await

Tengo esta función que devuelve una promesa y falla cuando se llama:

 export const mockAsync = () => { return new Promise((_, reject) => { setTimeout(() => reject(new Error('Error')), 50); }); };

Y tengo esta prueba, que está pasando:

 describe('mockAsync', () => { test('it should throw if we ask for it', async () => { const result = mockAsync(); await expect(result).rejects.toThrow('Error'); }); });

Pero lo encuentro extraño, esperaría que llamara await antes de la llamada a la función:

 describe('mockAsync', () => { test('it should throw if we ask for it', async () => { const result = await mockAsync(); expect(result).rejects.toThrow('Error'); }); });

Este último no está pasando, y no puedo entender por qué. ¿No es la sintaxis correcta?

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

0

Para probar el trabajo que desea que la promesa sea rechazada dentro del contexto de la expectativa. por eso solemos escribirlo así:

 await expect(/*sync function call*/).rejects.toThrow('someError')

Y en tu ejemplo particular:

 describe('mockAsync', () => { test('it should throw if we ask for it', async () => { await expect(mockAsync()).rejects.toThrow('Error') }) })

Si desea utilizar el enfoque Try/Catch, simplemente detecte el error y asegúrese de que sea el esperado:

 describe('mockAsync', () => { test('it should throw if we ask for it', async () => { try{ await mockAsync() } catch(err){ expect(err.message).toEqual('Error') } }) })
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!