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

190
Views
Asynchronous tests using jest and only callbacks

I'm trying to implement some asynchronous tests using jest and only callbacks. I managed to make this code, which I hope is right (it passes the test):

test('Test the then() clause', function (done) {
    expect.assertions(1);
    const result = generate();
    new Promise(function (resolve, reject) {
        setTimeout(function () {
            resolve(result);
        }, 100);
    }).then((data) => {
        expect(data).toBe(result);
        done();
    });
});

But I'm stuck trying to create a test when I expect to catch an error, just like so:

test('Test unhandled promise rejection', function (done) {
    expect.assertions(1);
    try {
        new Promise(function (resolve, reject) {
            setTimeout(function () {
                reject('errorrrrr');
            }, 100);
        });
    } catch (error) {
        console.log(error);
        done();
    }
});

What I am doing wrong?

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

0

EDIT: If you want to do this with a callback then simply get rid of the try/catch

test('Test unhandled promise rejection', function (done) {
    new Promise(function (resolve, reject) {
            setTimeout(function () {
                reject('errorrrrr');
            }, 100);
    }).catch(() => {
      console.log(error);
      done();
    });
});

You need to await the promise, otherwise it doesn't throw

test('Test unhandled promise rejection', async function (done) {
    expect.assertions(1);
    try {
        await new Promise(function (resolve, reject) {
            setTimeout(function () {
                reject('errorrrrr');
            }, 100);
        });
    } catch (error) {
        console.log(error);
        done();
    }
});

So it's just plain easier (IMO) to skip the callbacks and use resolves/rejects

test('Test unhandled promise rejection', async () => {
    await expect(new Promise(function (resolve, reject) {
            setTimeout(function () {
                reject('errorrrrr');
            }, 100);
    }).rejects.toMatch('errorrrrr')
});
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!