Skip to content

assertPromiseResolved() #3759

Description

@jespertheend

Is your feature request related to a problem? Please describe.

During tests I often want to verify that a promise has been resolved right at this moment.

Describe the solution you'd like

This is a function that I've been using a lot for this:

/**
 * Asserts whether a promise is currently resolved or not. The check is made asynchronously.
 * The call waits for the next event loops and gives the promise a chance to resolve in the current event loop.
 * The reason for this is that there is no way to synchronously check the resolved state of promises in JavaScript.
 * @param {Promise<any>} promise
 * @param {boolean} expected
 */
export async function assertPromiseResolved(promise, expected) {
	let resolved = false;
	(async () => {
		await promise;
		resolved = true;
	})();
	await waitForMicrotasks();
	const msg = expected ? "Expected the promise to be resolved" : "Expected the promise to not be resolved";
	assert(resolved == expected, msg);
}

waitForMicrotasks is a very basic:

export function waitForMicrotasks() {
	return new Promise(r => setTimeout(r, 0));
}

As far as I'm aware this is required, there's no way to figure out the state of promises synchronously.

Is this something that would be suitable for deno_std? I've got a few tests for this as well.

Describe alternatives you've considered

Keep using this from my own repository ¯\_(ツ)_/¯

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions