Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

fix: prevent using mocks in rpc #2254

Merged
merged 1 commit into from Nov 1, 2022
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Jump to
Jump to file
Failed to load files.
Diff view
Diff view
24 changes: 23 additions & 1 deletion 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()
Expand Down
24 changes: 0 additions & 24 deletions packages/vitest/src/utils/timers.ts
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
}
}