1import * as Crypto from 'expo-crypto'; 2 3import getRandomValues, { getRandomValuesInsecure } from '../getRandomValues'; 4 5afterEach(() => { 6 (Crypto.getRandomValues as jest.Mock).mockClear(); 7}); 8 9test.each([ 10 ['Int8Array', Int8Array], 11 ['Uint8Array', Uint8Array], 12 ['Int16Array', Int16Array], 13 ['Uint16Array', Uint16Array], 14 ['Int32Array', Int32Array], 15 ['Uint32Array', Uint32Array], 16 ['Uint8ClampedArray', Uint8ClampedArray], 17])(`fills %s with random values`, (_, TypedArray) => { 18 const valueCount = 10; 19 const array = new TypedArray(valueCount); 20 const result = getRandomValues(array); 21 expect(result).toBe(array); 22 23 expect(Crypto.getRandomValues).toHaveBeenCalledTimes(1); 24 expect(Crypto.getRandomValues).toHaveBeenCalledWith(array); 25 26 // There is an ignorably infinitesimal chance the array is randomly all zeros 27 const zeros = new TypedArray(valueCount); 28 expect(array).not.toEqual(zeros); 29}); 30 31test.each([ 32 ['nothing'], 33 ['a plain array', []], 34 ['a plain object', {}], 35 ['a Float32Array', Float32Array], 36 ['null', null], 37])(`throws if given %s`, (_, ...values) => { 38 expect(() => getRandomValues(...(values as [any]))).toThrow(TypeError); 39}); 40 41test(`throws if requesting more than 65536 bytes`, () => { 42 const oversized = new Int32Array(Math.ceil(65537 / Int32Array.BYTES_PER_ELEMENT)); 43 44 let error: any = undefined; 45 try { 46 getRandomValues(oversized); 47 } catch (e) { 48 error = e; 49 } 50 51 expect(error).toBeDefined(); 52 expect(error.name).toBe('QuotaExceededError'); 53 expect(error.code).toBe(22 /* QUOTA_EXCEEDED_ERR */); 54}); 55 56describe(getRandomValuesInsecure, () => { 57 test.each([ 58 ['Int8Array', Int8Array], 59 ['Uint8Array', Uint8Array], 60 ['Int16Array', Int16Array], 61 ['Uint16Array', Uint16Array], 62 ['Int32Array', Int32Array], 63 ['Uint32Array', Uint32Array], 64 ['Uint8ClampedArray', Uint8ClampedArray], 65 ])(`fills %s with random values`, (_, TypedArray) => { 66 const valueCount = 10; 67 const array = new TypedArray(valueCount); 68 const result = getRandomValuesInsecure(array); 69 expect(result).toBe(array); 70 71 // There is an ignorably infinitesimal chance the array is randomly all zeros 72 const zeros = new TypedArray(valueCount); 73 expect(array).not.toEqual(zeros); 74 }); 75}); 76