Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
7 changes: 0 additions & 7 deletions src/renderer/__helpers__/test-utils.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -110,10 +110,3 @@ export function renderWithAppContext(
),
});
}

/**
* Ensure stable snapshots for our randomized emoji use-cases
*/
export function ensureStableEmojis() {
globalThis.Math.random = vi.fn(() => 0.1);
}
5 changes: 5 additions & 0 deletions src/renderer/__helpers__/vitest.setup.ts
Original file line number Diff line number Diff line change
Expand Up @@ -11,6 +11,11 @@ vi.mock('react-router-dom', async () => ({
useNavigate: () => navigateMock,
}));

// Ensure stability in EmojiSplash component snapshots
vi.mock('../utils/core/random', () => ({
randomElement: vi.fn((arr: unknown[]) => arr[0]),
}));

// Sets timezone to UTC for consistent date/time in tests and snapshots
process.env.TZ = 'UTC';

Expand Down
9 changes: 1 addition & 8 deletions src/renderer/components/AllRead.test.tsx
Original file line number Diff line number Diff line change
@@ -1,19 +1,12 @@
import { act } from '@testing-library/react';

import {
ensureStableEmojis,
renderWithAppContext,
} from '../__helpers__/test-utils';
import { renderWithAppContext } from '../__helpers__/test-utils';
import { mockSettings } from '../__mocks__/state-mocks';

import { useFiltersStore } from '../stores';
import { AllRead } from './AllRead';

describe('renderer/components/AllRead.tsx', () => {
beforeEach(() => {
ensureStableEmojis();
});

it('should render itself & its children - no filters', async () => {
let tree: ReturnType<typeof renderWithAppContext> | null = null;

Expand Down
9 changes: 2 additions & 7 deletions src/renderer/components/AllRead.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,7 @@ import { Constants } from '../constants';
import { EmojiSplash } from './layout/EmojiSplash';

import { useFiltersStore } from '../stores';
import { randomElement } from '../utils/core/random';

interface AllReadProps {
fullHeight?: boolean;
Expand All @@ -15,13 +16,7 @@ export const AllRead: FC<AllReadProps> = ({
}: AllReadProps) => {
const hasFilters = useFiltersStore((s) => s.hasActiveFilters());

const emoji = useMemo(
() =>
Constants.EMOJIS.ALL_READ[
Math.floor(Math.random() * Constants.EMOJIS.ALL_READ.length)
],
[],
);
const emoji = useMemo(() => randomElement(Constants.EMOJIS.ALL_READ), []);

const heading = `No new ${hasFilters ? 'filtered ' : ''} notifications`;

Expand Down
10 changes: 1 addition & 9 deletions src/renderer/components/Oops.test.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -3,19 +3,11 @@ import userEvent from '@testing-library/user-event';

import { PersonIcon } from '@primer/octicons-react';

import {
ensureStableEmojis,
navigateMock,
renderWithAppContext,
} from '../__helpers__/test-utils';
import { navigateMock, renderWithAppContext } from '../__helpers__/test-utils';

import { Oops } from './Oops';

describe('renderer/components/Oops.tsx', () => {
beforeEach(() => {
ensureStableEmojis();
});

it('should render itself & its children - specified error', async () => {
const mockError = {
title: 'Error title',
Expand Down
6 changes: 2 additions & 4 deletions src/renderer/components/Oops.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,7 @@ import { EmojiSplash } from './layout/EmojiSplash';
import type { GitifyError } from '../types';

import { Errors } from '../utils/core/errors';
import { randomElement } from '../utils/core/random';

interface OopsProps {
error: GitifyError;
Expand All @@ -21,10 +22,7 @@ export const Oops: FC<OopsProps> = ({
const err = error ?? Errors.UNKNOWN;
const navigate = useNavigate();

const emoji = useMemo(
() => err.emojis[Math.floor(Math.random() * err.emojis.length)],
[err],
);
const emoji = useMemo(() => randomElement(err.emojis), [err]);

const actions = err.actions?.length
? err.actions.map((action) => (
Expand Down
8 changes: 4 additions & 4 deletions src/renderer/components/__snapshots__/AllRead.test.tsx.snap

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

Original file line number Diff line number Diff line change
@@ -1,10 +1,7 @@
import { act, screen } from '@testing-library/react';
import userEvent from '@testing-library/user-event';

import {
ensureStableEmojis,
renderWithAppContext,
} from '../../__helpers__/test-utils';
import { renderWithAppContext } from '../../__helpers__/test-utils';
import { mockGitHubCloudAccount } from '../../__mocks__/account-mocks';
import { mockGitHubCloudGitifyNotifications } from '../../__mocks__/notifications-mocks';
import { mockSettings } from '../../__mocks__/state-mocks';
Expand All @@ -17,21 +14,11 @@ import {
type AccountNotificationsProps,
} from './AccountNotifications';

const navigateMock = vi.fn();
vi.mock('react-router-dom', async () => ({
...(await vi.importActual('react-router-dom')),
useNavigate: () => navigateMock,
}));

vi.mock('./RepositoryNotifications', () => ({
RepositoryNotifications: () => <div>RepositoryNotifications</div>,
}));

describe('renderer/components/notifications/AccountNotifications.tsx', () => {
beforeEach(() => {
ensureStableEmojis();
});

it('should render itself - group notifications by repositories', () => {
const props: AccountNotificationsProps = {
account: mockGitHubCloudAccount,
Expand Down

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

49 changes: 49 additions & 0 deletions src/renderer/utils/core/random.test.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,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();
});
});
10 changes: 10 additions & 0 deletions src/renderer/utils/core/random.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,10 @@
/**
* Returns a cryptographically random element from the given array.
* Uses crypto.getRandomValues instead of Math.random to satisfy
* secure-coding requirements.
*/
export function randomElement<T>(array: T[]): T {
const buf = new Uint32Array(1);
crypto.getRandomValues(buf);
return array[buf[0] % array.length];
}
Loading