1
0
mirror of https://github.com/kremalicious/metamask-extension.git synced 2024-12-23 09:52:26 +01:00
metamask-extension/test/lib/wait-until-called.js
Mark Stacey b1b6d7ae38
Fix intermittent metrics e2e test failure (#9980)
The metrics e2e test would fail if the segment events still weren't
dispatched when the page loaded. The Segment events are sent on a set
interval, so it isn't abnormal for them to lag behind the page load
itself. The `waitUntilCalled` utility has been used to wait until all
required events have been dispatched.

The `wait-until-called` module was converted to an ES5 module, so that
it could be used from an e2e test. The optional `callCount` parameter
has also been added, to allow waiting for more than one call.

The `segmentSpy` had to be converted to a `segmentStub`, to allow the
`waitUntilCalled` utility to be used.
2020-12-03 14:30:50 -03:30

39 lines
1.2 KiB
JavaScript

/**
* A function that wraps a sinon stubbed function and returns a Promise
* when this stub was called.
*
* The stub that has been passed in will be setup to call the wrapped function
* directly, then trigger the returned Promise to resolve.
*
* 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 {number} [callCount] - The number of calls to wait for. Defaults to 1.
* @returns {Promise} A Promise that resolves when the stub has been called
*/
function waitUntilCalled(stub, wrappedThis = null, callCount = 1) {
let numCalls = 0
let resolve
const stubHasBeenCalled = new Promise((_resolve) => {
resolve = _resolve
})
stub.callsFake((...args) => {
try {
if (stub.wrappedMethod) {
stub.wrappedMethod.call(wrappedThis, ...args)
}
} finally {
if (numCalls < callCount) {
numCalls += 1
if (numCalls === callCount) {
resolve()
}
}
}
})
return stubHasBeenCalled
}
module.exports = waitUntilCalled