import { getRandomFromArray, getRandomInt } from '~/utilities/random'; const MOCK_RANDOM_STARTING_VALUE = 0.123456789; describe('Random Utility functions', () => { // eslint-disable-next-line @typescript-eslint/init-declarations let mockRandomValue: number; beforeAll(() => { const mockMath = Object.create(global.Math) as Math; mockMath.random = (): number => mockRandomValue; global.Math = mockMath; }); beforeEach(() => { mockRandomValue = MOCK_RANDOM_STARTING_VALUE; }); describe('getRandomInt', () => { test('No min, no max', () => { const int = getRandomInt(); // eslint-disable-next-line no-mixed-operators,max-len const expected = Math.floor(mockRandomValue * (Number.MAX_SAFE_INTEGER - Number.MIN_SAFE_INTEGER + 1) + Number.MIN_SAFE_INTEGER); expect(int).toStrictEqual(expected); }); test('Min, no max', () => { const min = 50; const int = getRandomInt(min); expect(int).toBeGreaterThanOrEqual(min); }); test('No min, max', () => { const max = 50; const int = getRandomInt(Number.MIN_SAFE_INTEGER, max); expect(int).toBeLessThanOrEqual(max); }); }); describe('getRandomFromArray', () => { test('Returns "random" item from array', () => { const arr = ['cornelius', 'zira', 'lucius', 'maximus', 'caesar']; const expectedIndex = Math.floor(mockRandomValue * arr.length); const item = getRandomFromArray(arr); expect(item).toStrictEqual(arr[expectedIndex]); }); }); });