mirror of
https://github.com/kremalicious/metamask-extension.git
synced 2024-11-23 10:30:04 +01:00
01f1f403ce
The `waitUntilCalled` utility now has a timeout. It will now throw an error if the stub is not called enough times, rather than blocking forever. The return type had to be changed to a function, so that we could throw when the timeout is triggered. I tried returning an error that rejected first, but if you don't handle the error synchronously Node.js will consider it to be an unhandled Promise rejected (even if it _is_ handled later on). I worked around this by resolving in the timeout case as well, so that there is never a "deferred" Promise exception in the timeout case. The returned function re-throws the error if it's given. That way there is never any unhandled Promise rejection.
67 lines
1.8 KiB
JavaScript
67 lines
1.8 KiB
JavaScript
const DEFAULT_TIMEOUT = 10000
|
|
|
|
/**
|
|
* A function that wraps a sinon stub and returns an asynchronous function
|
|
* that resolves if the stubbed function was called enough times, or throws
|
|
* if the timeout is exceeded.
|
|
*
|
|
* The stub that has been passed in will be setup to call the wrapped function
|
|
* directly.
|
|
*
|
|
* WARNING: Any existing `callsFake` behavior will be overwritten.
|
|
*
|
|
* @param {import('sinon').stub} stub - A sinon stub of a function
|
|
* @param {unknown} [wrappedThis] - The object the stubbed function was called
|
|
* on, if any (i.e. the `this` value)
|
|
* @param {Object} [options] - Optional configuration
|
|
* @param {number} [options.callCount] - The number of calls to wait for.
|
|
* @param {number|null} [options.timeout] - The timeout, in milliseconds. Pass
|
|
* in `null` to disable the timeout.
|
|
* @returns {Function} An asynchronous function that resolves when the stub is
|
|
* called enough times, or throws if the timeout is reached.
|
|
*/
|
|
function waitUntilCalled(
|
|
stub,
|
|
wrappedThis = null,
|
|
{ callCount = 1, timeout = DEFAULT_TIMEOUT } = {},
|
|
) {
|
|
let numCalls = 0
|
|
let resolve
|
|
let timeoutHandle
|
|
const stubHasBeenCalled = new Promise((_resolve) => {
|
|
resolve = _resolve
|
|
if (timeout !== null) {
|
|
timeoutHandle = setTimeout(
|
|
() => resolve(new Error('Timeout exceeded')),
|
|
timeout,
|
|
)
|
|
}
|
|
})
|
|
stub.callsFake((...args) => {
|
|
try {
|
|
if (stub.wrappedMethod) {
|
|
stub.wrappedMethod.call(wrappedThis, ...args)
|
|
}
|
|
} finally {
|
|
if (numCalls < callCount) {
|
|
numCalls += 1
|
|
if (numCalls === callCount) {
|
|
if (timeoutHandle) {
|
|
clearTimeout(timeoutHandle)
|
|
}
|
|
resolve()
|
|
}
|
|
}
|
|
}
|
|
})
|
|
|
|
return async () => {
|
|
const error = await stubHasBeenCalled
|
|
if (error) {
|
|
throw error
|
|
}
|
|
}
|
|
}
|
|
|
|
module.exports = waitUntilCalled
|