Skip to content

Commit

Permalink
fix: prevent using mocks in rpc (#2254)
Browse files Browse the repository at this point in the history
  • Loading branch information
sheremet-va authored Nov 1, 2022
1 parent b574a94 commit 41361fa
Show file tree
Hide file tree
Showing 2 changed files with 23 additions and 25 deletions.
24 changes: 23 additions & 1 deletion packages/vitest/src/runtime/rpc.ts
Original file line number Diff line number Diff line change
@@ -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()
Expand Down
24 changes: 0 additions & 24 deletions packages/vitest/src/utils/timers.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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
}
}

0 comments on commit 41361fa

Please sign in to comment.