Files
sim/packages/utils/src/random.test.ts
Waleed 4e17dceda0 chore(tests): consolidate test patterns — shared Vitest base, central @sim/testing mocks, check:test-patterns, lean agent docs (#8309)
* chore(tests): consolidate test patterns — shared Vitest base, central @sim/testing mocks, check:test-patterns, lean agent docs

* fix(tests): discover central mocks from their declarations and accept the async-import form

* fix(tests): address review — mock fidelity, docs, and guards

* docs(tests): restore the heavy-graph, global-mock and permanent-implementation rules and small doc pointers
2026-09-25 16:36:13 -07:00

33 lines
1021 B
TypeScript

import { describe, expect, it, vi } from 'vitest'
import { randomInt } from './random.js'
const UINT32_MAX = 0xffffffff
const UINT32_SAMPLE_SPACE_SIZE = 0x100000000
function mockRandomValues(...values: number[]) {
let index = 0
return vi.spyOn(globalThis.crypto, 'getRandomValues').mockImplementation((array) => {
if (!(array instanceof Uint32Array)) throw new Error('Expected a Uint32Array')
const value = values[index]
if (value === undefined) throw new Error('Unexpected additional random draw')
array[0] = value
index += 1
return array
})
}
describe('randomInt', () => {
it('redraws values from the biased upper tail', () => {
const getRandomValues = mockRandomValues(UINT32_MAX, 42)
expect(randomInt(0, 10)).toBe(2)
expect(getRandomValues).toHaveBeenCalledTimes(2)
})
it('rejects ranges larger than the Uint32 sample space', () => {
expect(() => randomInt(0, UINT32_SAMPLE_SPACE_SIZE + 1)).toThrow(
'randomInt: range must not exceed 2^32'
)
})
})