1 import { disableRandomMock, initRandomMock } from '@proton/testing/lib/mockRandomValues';
3 import getRandomString, { DEFAULT_CHARSET } from './getRandomString';
5 describe('getRandomString()', () => {
6 const getConsecutiveArray = (length: number) => [...Array(length).keys()];
8 const mockedRandomValues = jest
10 .mockImplementation((array: Uint32Array) => Uint32Array.from(getConsecutiveArray(array.length)));
12 beforeAll(() => initRandomMock(mockedRandomValues));
13 afterAll(() => disableRandomMock());
15 describe('length', () => {
16 it('returns throw an error when length is negative', () => {
17 expect(() => getRandomString(-1)).toThrow();
19 it('returns an empty string when length is 0', () => {
20 const result = getRandomString(0);
21 expect(result).toBe('');
23 it('returns a string of required length', () => {
24 const lengths = [1, 2, 3, 5, 8, 13];
25 const results = lengths.map((length) => getRandomString(length));
26 expect(results.map((result) => result.length)).toStrictEqual(lengths);
30 describe('charset', () => {
31 it('defaults the charset', () => {
32 const result = getRandomString(DEFAULT_CHARSET.length);
34 expect(mockedRandomValues).toHaveBeenCalled();
35 expect(result).toBe(DEFAULT_CHARSET);
38 it('returns characters from the defined charset', () => {
39 const charset = 'qwerty';
41 const result = getRandomString(charset.length, charset);
43 expect(result).toBe(charset);