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?
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')
});