/** * 随机数测试辅助函数 */ import { vi } from 'vitest' let mockRandomValue = 0.5 /** * 设置 Math.random() 返回值 * @param {number} value - 返回值(0-1) */ export function setMockRandom(value) { mockRandomValue = value } /** * 创建 Math.random() 的 mock * @returns {Object} spy */ export function mockMathRandom() { return vi.spyOn(Math, 'random').mockImplementation(() => mockRandomValue) } /** * 重置 mock 随机值 */ export function resetMockRandom() { mockRandomValue = 0.5 } /** * 设置随机数序列 * @param {Array} values - 随机数序列 * @returns {Object} spy */ export function mockRandomSequence(values) { let index = 0 return vi.spyOn(Math, 'random').mockImplementation(() => { const value = values[index % values.length] index++ return value }) } /** * 创建确定性的随机数生成器 * @param {number} seed - 种子值 * @returns {Function} 随机函数 */ export function createSeededRandom(seed) { return () => { seed = (seed * 9301 + 49297) % 233280 return seed / 233280 } } /** * Mock 随机数生成器 * @param {number} seed - 种子值 * @returns {Object} spy */ export function mockSeededRandom(seed) { const randomFunc = createSeededRandom(seed) return vi.spyOn(Math, 'random').mockImplementation(randomFunc) } /** * 清理所有 mock */ export function cleanupMocks() { vi.restoreAllMocks() resetMockRandom() }