Relevant posts:
- How to check if a Promise is pending [duplicate]
- How can I synchronously determine a JavaScript Promise's state?
Use case: I would like to test a code with Jest that already uses promises, so to not mess up the promise queue, I needed a way to peek into the promise without using Promise.resolve or Promise.race.
My helper function:
const PROMISE_STATUS = Object.freeze({
PENDING: 'pending',
FULFILLED: 'fulfilled',
REJECTED: 'rejected'
})
function promiseStatus(p) {
if (inspect(p).includes(PROMISE_STATUS.PENDING)) {
return PROMISE_STATUS.PENDING;
}
else if (inspect(p).includes(PROMISE_STATUS.REJECTED)) {
return PROMISE_STATUS.REJECTED;
}
else {
return PROMISE_STATUS.FULFILLED;
}
}
Test for it with Jest:
test('promiseStatus', () => {
expect(promiseStatus(new Promise(()=>{}))).toEqual(PROMISE_STATUS.PENDING);
expect(promiseStatus(Promise.resolve(2))).toEqual(PROMISE_STATUS.FULFILLED);
expect(promiseStatus(Promise.reject(0))).toEqual(PROMISE_STATUS.REJECTED);
})
No comments:
Post a Comment