-
Notifications
You must be signed in to change notification settings - Fork 284
Expand file tree
/
Copy pathrandom.test.ts
More file actions
49 lines (41 loc) · 1.32 KB
/
random.test.ts
File metadata and controls
49 lines (41 loc) · 1.32 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
vi.unmock('./random');
import { randomElement } from './random';
const FRUITS = ['apple', 'banana', 'cherry', 'date', 'elderberry'];
describe('randomElement', () => {
it('should return an element from the array', () => {
for (let i = 0; i < 100; i++) {
const result = randomElement(FRUITS);
expect(FRUITS).toContain(result);
}
});
it('should use crypto.getRandomValues', () => {
const spy = vi.spyOn(globalThis.crypto, 'getRandomValues');
randomElement(FRUITS);
expect(spy).toHaveBeenCalledOnce();
spy.mockRestore();
});
it('should return first element when crypto returns 0', () => {
vi.spyOn(globalThis.crypto, 'getRandomValues').mockImplementation(
<T extends ArrayBufferView>(array: T): T => {
if (array instanceof Uint32Array) {
array[0] = 0;
}
return array;
},
);
expect(randomElement(FRUITS)).toBe('apple');
vi.restoreAllMocks();
});
it('should wrap large values via modulo', () => {
vi.spyOn(globalThis.crypto, 'getRandomValues').mockImplementation(
<T extends ArrayBufferView>(array: T): T => {
if (array instanceof Uint32Array) {
array[0] = 13;
}
return array;
},
);
expect(randomElement(FRUITS)).toBe('date'); // 13 % 5 === 3
vi.restoreAllMocks();
});
});