diff --git a/packages/vitest/src/runtime/rpc.ts b/packages/vitest/src/runtime/rpc.ts index 7875598eac19..56c894e362d5 100644 --- a/packages/vitest/src/runtime/rpc.ts +++ b/packages/vitest/src/runtime/rpc.ts @@ -1,4 +1,26 @@ -import { getWorkerState, withSafeTimers } from '../utils' +import { getWorkerState } from '../utils' +import { + setTimeout as safeSetTimeout, +} from '../utils/timers' + +const safeRandom = Math.random + +function withSafeTimers(fn: () => void) { + const currentSetTimeout = globalThis.setTimeout + const currentRandom = globalThis.Math.random + + try { + globalThis.setTimeout = safeSetTimeout + globalThis.Math.random = safeRandom + + const result = fn() + return result + } + finally { + globalThis.setTimeout = currentSetTimeout + globalThis.Math.random = currentRandom + } +} export const rpc = () => { const { rpc } = getWorkerState() diff --git a/packages/vitest/src/utils/timers.ts b/packages/vitest/src/utils/timers.ts index 159a0074421a..55b0fd03579c 100644 --- a/packages/vitest/src/utils/timers.ts +++ b/packages/vitest/src/utils/timers.ts @@ -11,27 +11,3 @@ export { safeClearInterval as clearInterval, safeClearTimeout as clearTimeout, } - -// can only work with sync code to not potentially mess with other code -export function withSafeTimers(fn: () => void) { - const currentSetTimeout = globalThis.setTimeout - const currentSetInterval = globalThis.setInterval - const currentClearInterval = globalThis.clearInterval - const currentClearTimeout = globalThis.clearTimeout - - try { - globalThis.setTimeout = safeSetTimeout - globalThis.setInterval = safeSetInterval - globalThis.clearInterval = safeClearInterval - globalThis.clearTimeout = safeClearTimeout - - const result = fn() - return result - } - finally { - globalThis.setTimeout = currentSetTimeout - globalThis.setInterval = currentSetInterval - globalThis.clearInterval = currentClearInterval - globalThis.clearTimeout = currentClearTimeout - } -}