electron/spec/events-helpers.ts
Jeremy Rose db7c92fd57
test: drop now-empty remote runner (#35343)
* test: drop the now-empty remote runner from CI

* move fixtures to spec-main

* remove remote runner

* fix stuff

* remove global-paths hack

* move ts-smoke to spec/

* fix test after merge

* rename spec-main to spec

* no need to ignore spec/node_modules twice

* simplify spec-runner a little

* no need to hash pj/yl twice

* undo lint change to verify-mksnapshot.py

* excessive ..

* update electron_woa_testing.yml

* don't search for test-results-remote.xml

it is never produced now
2022-08-16 15:23:13 -04:00

55 lines
1.6 KiB
TypeScript

/**
* @fileoverview A set of helper functions to make it easier to work
* with events in async/await manner.
*/
/**
* @param {!EventTarget} target
* @param {string} eventName
* @return {!Promise<!Event>}
*/
export const waitForEvent = (target: EventTarget, eventName: string) => {
return new Promise(resolve => {
target.addEventListener(eventName, resolve, { once: true });
});
};
/**
* @param {!EventEmitter} emitter
* @param {string} eventName
* @return {!Promise<!Array>} With Event as the first item.
*/
export const emittedOnce = (emitter: NodeJS.EventEmitter, eventName: string, trigger?: () => void) => {
return emittedNTimes(emitter, eventName, 1, trigger).then(([result]) => result);
};
export const emittedNTimes = async (emitter: NodeJS.EventEmitter, eventName: string, times: number, trigger?: () => void) => {
const events: any[][] = [];
const p = new Promise<any[][]>(resolve => {
const handler = (...args: any[]) => {
events.push(args);
if (events.length === times) {
emitter.removeListener(eventName, handler);
resolve(events);
}
};
emitter.on(eventName, handler);
});
if (trigger) {
await Promise.resolve(trigger());
}
return p;
};
export const emittedUntil = async (emitter: NodeJS.EventEmitter, eventName: string, untilFn: Function) => {
const p = new Promise<any[]>(resolve => {
const handler = (...args: any[]) => {
if (untilFn(...args)) {
emitter.removeListener(eventName, handler);
resolve(args);
}
};
emitter.on(eventName, handler);
});
return p;
};