level_0
int64
0
10k
index
int64
0
0
repo_id
stringlengths
22
152
file_path
stringlengths
41
203
content
stringlengths
11
11.5M
5,657
0
petrpan-code/ProtonMail/WebClients/packages/components/components
petrpan-code/ProtonMail/WebClients/packages/components/components/time/TimeIntl.test.tsx
import { render } from '@testing-library/react'; import { fromUnixTime, getUnixTime } from 'date-fns'; import { readableTimeIntl } from '@proton/shared/lib/helpers/time'; import { dateLocale } from '@proton/shared/lib/i18n'; import TimeIntl from './TimeIntl'; jest.mock('@proton/shared/lib/i18n', () => ({ dateLocale: { code: 'en-US', formatLong: { time: jest.fn(), }, }, })); const mockedFormatLongTime = jest.mocked(dateLocale.formatLong!.time).mockReturnValue('h:mm:ss a zzzz'); describe('TimeIntl component', () => { const unixDate = 1552897937; it('should handle default when time is not set', () => { const { container } = render(<TimeIntl />); expect(container.firstChild?.textContent).toBe('Jan 1, 1970'); }); it('should display time if same day', () => { jest.useFakeTimers().setSystemTime(fromUnixTime(unixDate)); const { container } = render(<TimeIntl>{unixDate}</TimeIntl>); expect(container.firstChild?.textContent).toBe( readableTimeIntl(unixDate, { hour12: true, intlOptions: { hour: 'numeric', minute: 'numeric', }, }) ); jest.useRealTimers(); }); it('should display time with AM/PM if b is present in date-fns time format', () => { jest.useFakeTimers().setSystemTime(fromUnixTime(unixDate)); mockedFormatLongTime.mockReturnValueOnce('h:mm:ss b zzzz'); const { container } = render(<TimeIntl>{unixDate}</TimeIntl>); expect(container.firstChild?.textContent).toBe( readableTimeIntl(unixDate, { hour12: true, intlOptions: { hour: 'numeric', minute: 'numeric', }, }) ); jest.useRealTimers(); }); it('should support Intl options', () => { const options: Intl.DateTimeFormatOptions = { hour: 'numeric', minute: 'numeric', month: 'short', day: 'numeric', year: 'numeric', }; const { container } = render(<TimeIntl options={options}>{unixDate}</TimeIntl>); expect(container.firstChild?.textContent).toBe( readableTimeIntl(unixDate, { intlOptions: options, hour12: true, }) ); }); it('should support Intl options forcing', () => { const todayUnixDate = Math.floor(Date.now() / 1000); const options: Intl.DateTimeFormatOptions = { month: 'short', day: 'numeric', year: 'numeric', }; const sameDayOptions: Intl.DateTimeFormatOptions = { month: 'short', day: 'numeric', year: 'numeric', }; const { container } = render( <TimeIntl options={options} sameDayOptions={sameDayOptions}> {todayUnixDate} </TimeIntl> ); expect(container.firstChild?.textContent).toBe( readableTimeIntl(todayUnixDate, { intlOptions: options, sameDayIntlOptions: sameDayOptions, }) ); }); it('should support Intl options forcing (sameDayOptions={false})', () => { const todayUnixDate = Math.floor(Date.now() / 1000); const options: Intl.DateTimeFormatOptions = { month: 'short', day: 'numeric', year: 'numeric', }; const { container } = render( <TimeIntl options={options} sameDayOptions={false}> {todayUnixDate} </TimeIntl> ); expect(container.firstChild?.textContent).toBe( readableTimeIntl(todayUnixDate, { intlOptions: options, sameDayIntlOptions: options, }) ); }); it('should support 24hour date format', () => { mockedFormatLongTime.mockReturnValueOnce('h:mm:ss zzzz'); const todayUnixDate = Math.floor(Date.now() / 1000); const { container } = render(<TimeIntl>{todayUnixDate}</TimeIntl>); expect(container.firstChild?.textContent).toBe(readableTimeIntl(todayUnixDate, { hour12: false })); }); it('should support date as children', () => { const date = new Date('2023-03-22'); const { container } = render(<TimeIntl>{date}</TimeIntl>); expect(container.firstChild?.textContent).toBe(readableTimeIntl(getUnixTime(date))); }); });
5,673
0
petrpan-code/ProtonMail/WebClients/packages/components/components
petrpan-code/ProtonMail/WebClients/packages/components/components/tooltip/Tooltip.test.tsx
import { fireEvent, render, screen } from '@testing-library/react'; import userEvent, { UserEvent } from '@testing-library/user-event'; import Tooltip from './Tooltip'; describe('tooltip', () => { let timerUserEvent: UserEvent; beforeEach(() => { jest.useFakeTimers(); timerUserEvent = userEvent.setup({ advanceTimers: jest.advanceTimersByTime }); }); afterEach(() => { jest.runOnlyPendingTimers(); jest.useRealTimers(); }); it('should show tooltip immediately when externally opened', () => { render( <Tooltip title={<span data-testid="tooltip">World</span>} isOpen> <span data-testid="span">Hello</span> </Tooltip> ); expect(screen.getByTestId('span')).toHaveTextContent('Hello'); expect(screen.getByTestId('tooltip')).toHaveTextContent('World'); }); it('should not show tooltip when not open', () => { render( <Tooltip title={<span data-testid="tooltip">World</span>} isOpen={false}> <span data-testid="span">Hello</span> </Tooltip> ); expect(screen.getByTestId('span')).toHaveTextContent('Hello'); expect(screen.queryByTestId('tooltip')).toBeNull(); }); it('should not close tooltip when externally opened', async () => { render( <> <Tooltip title={<span data-testid="tooltip">World</span>} isOpen> <span data-testid="span">Hello</span> </Tooltip> <div data-testid="outside">hello</div> </> ); expect(screen.getByTestId('span')).toHaveTextContent('Hello'); expect(screen.getByTestId('tooltip')).toHaveTextContent('World'); await timerUserEvent.unhover(screen.getByTestId('span')); await timerUserEvent.click(screen.getByTestId('outside')); jest.advanceTimersByTime(1000); fireEvent.animationEnd(screen.getByTestId('tooltip'), { animationName: 'anime-tooltip-out-last' }); expect(screen.getByTestId('span')).toHaveTextContent('Hello'); expect(screen.getByTestId('tooltip')).toHaveTextContent('World'); }); it('should show and hide tooltip with a delay', async () => { render( <Tooltip title={<span data-testid="tooltip">World</span>}> <span data-testid="span">Hello</span> </Tooltip> ); expect(screen.getByTestId('span')).toHaveTextContent('Hello'); expect(screen.queryByTestId('tooltip')).toBeNull(); await timerUserEvent.hover(screen.getByTestId('span')); expect(screen.queryByTestId('tooltip')).toBeNull(); jest.advanceTimersByTime(1000); fireEvent.animationEnd(screen.getByTestId('tooltip'), { animationName: 'anime-tooltip-in-first' }); expect(screen.getByTestId('tooltip')).toHaveTextContent('World'); await timerUserEvent.unhover(screen.getByTestId('span')); expect(screen.getByTestId('tooltip')).toHaveTextContent('World'); jest.advanceTimersByTime(500); fireEvent.animationEnd(screen.getByTestId('tooltip'), { animationName: 'anime-tooltip-out-last' }); expect(screen.queryByTestId('tooltip')).toBeNull(); }); it('should show second tooltip instantly and hide tooltip with a delay', async () => { render( <> <Tooltip title={<span data-testid="tooltip-1">World</span>}> <span data-testid="span-1">Hello</span> </Tooltip> <Tooltip title={<span data-testid="tooltip-2">Bar</span>}> <span data-testid="span-2">Foo</span> </Tooltip> </> ); expect(screen.queryByTestId('tooltip-1')).toBeNull(); expect(screen.queryByTestId('tooltip-2')).toBeNull(); await timerUserEvent.hover(screen.getByTestId('span-1')); expect(screen.queryByTestId('tooltip-1')).toBeNull(); expect(screen.queryByTestId('tooltip-2')).toBeNull(); jest.advanceTimersByTime(1000); fireEvent.animationEnd(screen.getByTestId('tooltip-1'), { animationName: 'anime-tooltip-in-first' }); expect(screen.getByTestId('tooltip-1')).toHaveTextContent('World'); expect(screen.queryByTestId('tooltip-2')).toBeNull(); await timerUserEvent.unhover(screen.getByTestId('span-1')); expect(screen.getByTestId('tooltip-1')).toHaveTextContent('World'); expect(screen.queryByTestId('tooltip-2')).toBeNull(); await timerUserEvent.hover(screen.getByTestId('span-2')); fireEvent.animationEnd(screen.getByTestId('tooltip-1'), { animationName: 'anime-tooltip-out' }); expect(screen.queryByTestId('tooltip-1')).toBeNull(); fireEvent.animationEnd(screen.getByTestId('tooltip-2'), { animationName: 'anime-tooltip-in' }); expect(screen.getByTestId('tooltip-2')).toHaveTextContent('Bar'); await timerUserEvent.unhover(screen.getByTestId('span-2')); jest.advanceTimersByTime(500); expect(screen.queryByTestId('tooltip-1')).toBeNull(); fireEvent.animationEnd(screen.getByTestId('tooltip-2'), { animationName: 'anime-tooltip-out-last' }); expect(screen.queryByTestId('tooltip-2')).toBeNull(); }); });
5,706
0
petrpan-code/ProtonMail/WebClients/packages/components/components/v2
petrpan-code/ProtonMail/WebClients/packages/components/components/v2/field/InputField.test.tsx
import { render } from '@testing-library/react'; import InputFieldTwo from './InputField'; const ComponentWithDefaultTestId = (props: any) => { return ( <div data-testid="foo" {...props}> bar </div> ); }; describe('input field test', () => { it('should not override default data-testid', () => { const { getByTestId } = render(<InputFieldTwo as={ComponentWithDefaultTestId} />); expect(getByTestId('foo')).toBeVisible(); }); it('should let data-testid be defined', () => { const { getByTestId, queryByTestId } = render( <InputFieldTwo data-testid="bar" as={ComponentWithDefaultTestId} /> ); expect(getByTestId('bar')).toBeVisible(); expect(queryByTestId('foo')).toBeNull(); }); });
5,711
0
petrpan-code/ProtonMail/WebClients/packages/components/components/v2
petrpan-code/ProtonMail/WebClients/packages/components/components/v2/input/TotpInput.test.tsx
import { useRef, useState } from 'react'; import { fireEvent, render } from '@testing-library/react'; import TotpInput from './TotpInput'; const EMPTY = ' '; const expectValues = (value: string, inputNodes: NodeListOf<HTMLInputElement>) => { value.split('').forEach((value, i) => { expect(inputNodes[i].value).toBe(value.replace(EMPTY, '')); }); }; describe('TotpInput component', () => { it('should display 6 inputs with a totp code', () => { const { container } = render(<TotpInput value="123456" onValue={() => {}} length={6} />); const inputNodes = container.querySelectorAll('input'); expect(inputNodes.length).toBe(6); expectValues('123456', inputNodes); }); it('should display 4 inputs with a partial totp code with invalid values', () => { const { container } = render(<TotpInput value="a12b" onValue={() => {}} length={4} />); const inputNodes = container.querySelectorAll('input'); expect(inputNodes.length).toBe(4); expectValues(' 12 ', inputNodes); }); it('should display 4 inputs with a partial totp code', () => { const { container } = render(<TotpInput value="12" onValue={() => {}} length={4} />); const inputNodes = container.querySelectorAll('input'); expect(inputNodes.length).toBe(4); expectValues('12 ', inputNodes); }); it('should display 3 inputs with partial alphabet value', () => { const { container } = render(<TotpInput value="1a" onValue={() => {}} length={3} type="alphabet" />); const inputNodes = container.querySelectorAll('input'); expect(inputNodes.length).toBe(3); expectValues('1a ', inputNodes); }); it('should not move focus when entering an invalid value', () => { const Test = () => { const [value, setValue] = useState('1'); return <TotpInput value={value} onValue={setValue} length={4} />; }; const { container } = render(<Test />); const inputNodes = container.querySelectorAll('input'); inputNodes[0].focus(); fireEvent.change(inputNodes[0], { target: { value: 'a' } }); expectValues('1 ', inputNodes); expect(inputNodes[0]).toHaveFocus(); fireEvent.change(inputNodes[0], { target: { value: '' } }); expectValues(' ', inputNodes); expect(inputNodes[0]).toHaveFocus(); fireEvent.change(inputNodes[0], { target: { value: 'a' } }); expectValues(' ', inputNodes); expect(inputNodes[0]).toHaveFocus(); }); it('should move focus to the next input when entering a value in the 1st input', () => { const Test = () => { const [value, setValue] = useState(''); return <TotpInput value={value} onValue={setValue} length={4} />; }; const { container } = render(<Test />); const inputNodes = container.querySelectorAll('input'); fireEvent.change(inputNodes[0], { target: { value: '1' } }); expectValues('1 ', inputNodes); expect(inputNodes[1]).toHaveFocus(); }); it('should move focus to the next input when entering a value in the 2nd input', () => { const Test = () => { const [value, setValue] = useState(''); return <TotpInput value={value} onValue={setValue} length={4} />; }; const { container } = render(<Test />); const inputNodes = container.querySelectorAll('input'); fireEvent.change(inputNodes[1], { target: { value: '1' } }); expectValues(' 1 ', inputNodes); expect(inputNodes[2]).toHaveFocus(); }); it('should move focus to the previous input when removing a value', () => { const Test = () => { const [value, setValue] = useState('123'); return <TotpInput value={value} onValue={setValue} length={4} />; }; const { container } = render(<Test />); const inputNodes = container.querySelectorAll('input'); expectValues('123 ', inputNodes); expect(inputNodes[1].value).toBe('2'); inputNodes[1].focus(); fireEvent.change(inputNodes[1], { target: { value: '' } }); expectValues('1 3 ', inputNodes); expect(inputNodes[1]).toHaveFocus(); fireEvent.keyDown(inputNodes[1], { key: 'Backspace' }); expectValues(' 3 ', inputNodes); expect(inputNodes[0]).toHaveFocus(); }); it('should remove the previous value when hitting backspace on left-most selection', () => { const Test = () => { const [value, setValue] = useState('123'); return <TotpInput value={value} onValue={setValue} length={4} />; }; const { container } = render(<Test />); const inputNodes = container.querySelectorAll('input'); inputNodes[1].selectionStart = 0; inputNodes[1].selectionEnd = 0; expectValues('123', inputNodes); fireEvent.keyDown(inputNodes[1], { key: 'Backspace' }); expectValues(' 23', inputNodes); expect(inputNodes[1].value).toBe('2'); expect(inputNodes[0].value).toBe(''); expect(inputNodes[0]).toHaveFocus(); }); it('should go to the next input when entering the same value', () => { const Test = () => { const [value, setValue] = useState('123'); return <TotpInput value={value} onValue={setValue} length={4} />; }; const { container } = render(<Test />); const inputNodes = container.querySelectorAll('input'); fireEvent.input(inputNodes[1], { target: { value: '2' } }); expectValues('123', inputNodes); expect(inputNodes[2]).toHaveFocus(); }); it('should move focus when pasting', () => { const Test = () => { const [value, setValue] = useState(''); return <TotpInput autoFocus value={value} onValue={setValue} length={4} />; }; const { container } = render(<Test />); const inputNodes = container.querySelectorAll('input'); expect(inputNodes[0]).toHaveFocus(); fireEvent.paste(inputNodes[0], { clipboardData: { getData: () => '32' } }); expect(inputNodes[2]).toHaveFocus(); expectValues('32 ', inputNodes); fireEvent.paste(inputNodes[1], { clipboardData: { getData: () => '32' } }); expect(inputNodes[3]).toHaveFocus(); expectValues('332 ', inputNodes); fireEvent.paste(inputNodes[0], { clipboardData: { getData: () => '7654321' } }); expect(inputNodes[3]).toHaveFocus(); expectValues('7654', inputNodes); }); it('should accept all values when pasting or changing multiple values', () => { const Test = () => { const [value, setValue] = useState('123'); return <TotpInput value={value} onValue={setValue} length={4} />; }; const { container } = render(<Test />); const inputNodes = container.querySelectorAll('input'); expectValues('123 ', inputNodes); fireEvent.paste(inputNodes[0], { clipboardData: { getData: () => '321' } }); expectValues('321 ', inputNodes); expect(inputNodes[3]).toHaveFocus(); fireEvent.paste(inputNodes[1], { clipboardData: { getData: () => '4321' } }); expectValues('3432', inputNodes); expect(inputNodes[3]).toHaveFocus(); fireEvent.change(inputNodes[1], { target: { value: '9876' } }); expectValues('3987', inputNodes); expect(inputNodes[3]).toHaveFocus(); }); describe('Autofocus behaviours', () => { const Test = (options: { autoFocus: boolean; initialValue: string }) => { const focusRef = useRef<HTMLInputElement>(null); const [value, setValue] = useState(options.initialValue); return ( <TotpInput value={value} onValue={setValue} length={4} ref={focusRef} autoFocus={options.autoFocus} /> ); }; it('should not focus inputs if not autofocused & empty value', () => { const { container } = render(<Test autoFocus={false} initialValue="" />); const inputNodes = container.querySelectorAll('input'); inputNodes.forEach((input) => expect(input).not.toHaveFocus()); }); it('should not focus inputs if not autofocused & initial value', () => { const { container } = render(<Test autoFocus={false} initialValue="123" />); const inputNodes = container.querySelectorAll('input'); inputNodes.forEach((input) => expect(input).not.toHaveFocus()); }); it('should focus first input when autofocused & empty value', () => { const { container } = render(<Test autoFocus initialValue="" />); const inputNodes = container.querySelectorAll('input'); expect(inputNodes[0]).toHaveFocus(); }); it('should focus correct input when autofocused & initial value', () => { const { container } = render(<Test autoFocus initialValue="12" />); const inputNodes = container.querySelectorAll('input'); expect(inputNodes[2]).toHaveFocus(); }); it('should focus last input when autofocused & initial value outgrows TOTP length', () => { const { container } = render(<Test autoFocus initialValue="123456789" />); const inputNodes = container.querySelectorAll('input'); expect(inputNodes[3]).toHaveFocus(); }); }); });
5,716
0
petrpan-code/ProtonMail/WebClients/packages/components/components/v2
petrpan-code/ProtonMail/WebClients/packages/components/components/v2/phone/PhoneInput.test.tsx
import { useState } from 'react'; import { fireEvent, render } from '@testing-library/react'; import PhoneInput from './PhoneInput'; import { getCountryFromNumber, getCursorPosition, getSpecificCountry } from './helper'; const Test = ({ initialValue, defaultCountry }: { initialValue: string; defaultCountry?: string }) => { const [value, setValue] = useState(initialValue); return <PhoneInput defaultCountry={defaultCountry} data-testid="input" value={value} onChange={setValue} />; }; const getCountry = (el: HTMLElement) => { return el.getAttribute('aria-label'); }; jest.mock('./flagSvgs', () => { return { getFlagSvg: () => true, }; }); jest.mock('react-virtualized', () => { const ReactVirtualized = jest.requireActual('react-virtualized'); return { ...ReactVirtualized, // @ts-ignore AutoSizer: ({ children }) => children({ height: 1000, width: 1000 }), }; }); interface TestCommands { input?: string; select?: string; expectation: { value: string; country: string | null }; } const runTest = (testCommands: TestCommands[]) => { const { getByTestId, getByRole, getByPlaceholderText, getByTitle } = render( <Test initialValue="" defaultCountry="US" /> ); const inputEl = getByTestId('input') as HTMLInputElement; const buttonEl = getByRole('button') as HTMLButtonElement; testCommands.forEach(({ input, select, expectation: { value, country } }) => { if (select !== undefined) { fireEvent.click(buttonEl); const searchEl = getByPlaceholderText('Country'); fireEvent.change(searchEl, { target: { value: select } }); const rowEl = getByTitle(select); fireEvent.click(rowEl); } if (input !== undefined) { fireEvent.change(inputEl, { target: { value: input } }); } expect(inputEl.value).toBe(value); expect(getCountry(buttonEl)).toBe(country); }); }; describe('PhoneInput', () => { it('should format input', () => { const spy = jest.fn(); const { getByTestId, getByRole, rerender } = render( <PhoneInput value="+41781234567" data-testid="input" onChange={spy} /> ); const input = getByTestId('input') as HTMLInputElement; const button = getByRole('button') as HTMLButtonElement; expect(input.value).toBe('78 123 45 67'); expect(getCountry(button)).toBe('Switzerland'); rerender(<PhoneInput data-testid="input" value="+410782354666" onChange={spy} />); expect(input.value).toBe('78 235 46 66'); expect(getCountry(button)).toBe('Switzerland'); rerender(<PhoneInput data-testid="input" value="+1613123" onChange={spy} />); expect(input.value).toBe('613 123'); expect(getCountry(button)).toBe('Canada'); rerender(<PhoneInput data-testid="input" value="+1631123" onChange={spy} />); expect(input.value).toBe('631 123'); expect(getCountry(button)).toBe('United States'); }); it('format as user enters text', () => { runTest([ { input: '631', expectation: { value: '631', country: 'United States' } }, { input: '6311', expectation: { value: '631 1', country: 'United States' } }, { input: '631', expectation: { value: '631', country: 'United States' } }, { input: '613', expectation: { value: '613', country: 'Canada' } }, { input: '6131', expectation: { value: '613 1', country: 'Canada' } }, { input: '61', expectation: { value: '61', country: 'Canada' } }, { input: '', expectation: { value: '', country: 'Canada' } }, { input: '6', expectation: { value: '6', country: 'Canada' } }, { input: '63', expectation: { value: '63', country: 'Canada' } }, { input: '631', expectation: { value: '631', country: 'United States' } }, ]); }); it('change country if entering with country calling code', () => { runTest([ { input: '', expectation: { value: '', country: 'United States' } }, { input: '+41', expectation: { value: '+41', country: 'Switzerland' } }, { input: '+417', expectation: { value: '+41 7', country: 'Switzerland' } }, { input: '+41781', expectation: { value: '+41 78 1', country: 'Switzerland' } }, { input: '', expectation: { value: '', country: 'Switzerland' } }, { input: '78', expectation: { value: '78', country: 'Switzerland' } }, { input: '781', expectation: { value: '78 1', country: 'Switzerland' } }, ]); }); it('change country selecting from dropdown', () => { runTest([ { input: '', expectation: { value: '', country: 'United States' } }, { select: 'Canada', expectation: { value: '', country: 'Canada' } }, { input: '6', expectation: { value: '6', country: 'Canada' } }, { input: '61', expectation: { value: '61', country: 'Canada' } }, { input: '613', expectation: { value: '613', country: 'Canada' } }, { select: 'Bahamas', expectation: { value: '', country: 'Bahamas' } }, { input: '6', expectation: { value: '6', country: 'Bahamas' } }, { input: '61', expectation: { value: '61', country: 'Bahamas' } }, { input: '613', expectation: { value: '613', country: 'Canada' } }, { input: '631', expectation: { value: '631', country: 'United States' } }, { select: 'Canada', expectation: { value: '', country: 'Canada' } }, ]); }); it('reset and remember country', () => { runTest([ { input: '', expectation: { value: '', country: 'United States' } }, { input: '+', expectation: { value: '+', country: null } }, { input: '+4', expectation: { value: '+4', country: null } }, { input: '+41', expectation: { value: '+41', country: 'Switzerland' } }, { input: '', expectation: { value: '', country: 'Switzerland' } }, { input: '+', expectation: { value: '+', country: null } }, ]); }); it('should get a country from a number', () => { expect(getCountryFromNumber('+')).toEqual(''); expect(getCountryFromNumber('+1')).toEqual('US'); expect(getCountryFromNumber('+11')).toEqual('US'); expect(getCountryFromNumber('+111')).toEqual('US'); expect(getCountryFromNumber('+12')).toEqual('US'); expect(getCountryFromNumber('3')).toEqual(''); expect(getCountryFromNumber('2')).toEqual(''); expect(getCountryFromNumber('1')).toEqual(''); expect(getCountryFromNumber('+41')).toEqual('CH'); expect(getCountryFromNumber('+411')).toEqual('CH'); expect(getCountryFromNumber('+411')).toEqual('CH'); expect(getCountryFromNumber('+42')).toEqual(''); expect(getCountryFromNumber('+320')).toEqual('BE'); }); it('should get a more specific country from a number', () => { expect(getSpecificCountry('', '1', 'US')).toEqual(['US', 0]); expect(getSpecificCountry('613', '1', 'US')).toEqual(['CA', 3]); expect(getSpecificCountry('631', '1', 'US')).toEqual(['US', 0]); expect(getSpecificCountry('787', '1', 'US')).toEqual(['PR', 3]); expect(getSpecificCountry('7', '7', 'RU')).toEqual(['KZ', 1]); expect(getSpecificCountry('', '7', 'KZ')).toEqual(['KZ', 0]); }); it('should get cursor at position', () => { [ { digit: 1, value: '1', expectation: 1 }, { digit: 2, value: '1', expectation: 1 }, { digit: 0, value: '1----2', expectation: 0 }, { digit: 0, value: '--1--', expectation: 1 }, { digit: 0, value: '--1', expectation: 1 }, { digit: 0, value: '--12', expectation: 1 }, { digit: 0, value: '--1-2-', expectation: 1 }, { digit: 1, value: '--1-2-', expectation: 3 }, { digit: 1, value: '--1----2', expectation: 6 }, { digit: 0, value: '--1----2', expectation: 1 }, ].forEach(({ digit, value, expectation }) => { expect(getCursorPosition(digit, value)).toEqual(expectation); }); }); it('should format input for CH', () => { const { getByTestId } = render(<Test defaultCountry="CH" initialValue="" data-testid="input" />); const input = getByTestId('input') as HTMLInputElement; expect(input.value).toBe(''); fireEvent.change(input, { target: { value: '1' } }); expect(input.value).toBe('1'); }); it('should format input for US', () => { const { getByTestId } = render(<Test defaultCountry="US" initialValue="" data-testid="input" />); const input = getByTestId('input') as HTMLInputElement; expect(input.value).toBe(''); fireEvent.change(input, { target: { value: '1' } }); expect(input.value).toBe('1'); }); });
5,736
0
petrpan-code/ProtonMail/WebClients/packages/components/containers
petrpan-code/ProtonMail/WebClients/packages/components/containers/account/EditEmailSubscription.test.tsx
import { fireEvent, render, screen, waitFor } from '@testing-library/react'; import { sub } from 'date-fns'; import { useApi, useUser, useUserSettings } from '../../hooks'; import EditEmailSubscription from './EditEmailSubscription'; jest.mock('../../hooks/useApi'); const mockedUseApi = useApi as jest.MockedFunction<any>; let mockedApi: ReturnType<typeof mockedUseApi>; jest.mock('../../hooks/useEventManager', () => () => ({ call: jest.fn() })); jest.mock('@proton/hooks/useLoading', () => () => [false, jest.fn((fn) => fn())]); jest.mock('../../hooks/useNotifications', () => () => ({ createNotification: jest.fn() })); jest.mock('../../hooks/useUser'); const mockedUseUser = useUser as jest.MockedFunction<any>; jest.mock('../../hooks/useUserSettings'); const mockedUseUserSettings = useUserSettings as jest.MockedFunction<any>; describe('EditEmailSubscription', () => { beforeEach(() => { mockedApi = jest.fn(); mockedUseApi.mockReturnValue(mockedApi); mockedUseUserSettings.mockReturnValue([{ EarlyAccess: 1, News: 0 }]); mockedUseUser.mockReturnValue([{ CreateTime: Math.floor(sub(new Date(), { weeks: 1 }).getTime() / 1000) }]); }); it('should have all expected toggles', () => { render(<EditEmailSubscription />); expect(screen.getByText('Proton important announcements')); expect(screen.getByText('Proton for Business newsletter')); expect(screen.getByText('Proton newsletter')); expect(screen.getByText('Proton beta announcements')); expect(screen.getByText('Proton offers and promotions')); expect(screen.getByText('Proton welcome emails')); expect(screen.getByText('Proton Mail and Calendar new features')); expect(screen.getByText('Proton Drive product updates')); expect(screen.getByText('Proton Pass product updates')); expect(screen.getByText('Proton VPN product updates')); }); it('should not have FEATURES toggle', () => { render(<EditEmailSubscription />); expect(screen.queryByText('Proton product announcements')).not.toBeInTheDocument(); }); it('should toggle nothing', () => { const { container } = render(<EditEmailSubscription />); const checkedToggles = container.querySelectorAll('[checked=""]'); expect(checkedToggles).toHaveLength(0); }); it('should toggle everything', () => { mockedUseUserSettings.mockReturnValue([{ EarlyAccess: 1, News: 4095 }]); const { container } = render(<EditEmailSubscription />); const checkedToggles = container.querySelectorAll('[checked=""]'); expect(checkedToggles).toHaveLength(10); }); it('should call api on update', async () => { render(<EditEmailSubscription />); const toggleContent = screen.getByText('Proton offers and promotions'); fireEvent.click(toggleContent); await waitFor(() => expect(mockedApi).toHaveBeenCalledTimes(1)); expect(mockedApi).toHaveBeenCalledWith({ data: { Features: false, Offers: true }, method: 'PATCH', url: 'core/v4/settings/news', }); }); it('should update global feature news flag when one product feature news is updated', async () => { render(<EditEmailSubscription />); const toggleContent = screen.getByText('Proton Drive product updates'); fireEvent.click(toggleContent); await waitFor(() => expect(mockedApi).toHaveBeenCalledTimes(1)); expect(mockedApi).toHaveBeenCalledWith({ data: { DriveNews: true, Features: true }, method: 'PATCH', url: 'core/v4/settings/news', }); }); describe('when user has been created more than one month ago', () => { it('should not display `welcome emails` toggle', () => { mockedUseUser.mockReturnValue([{ CreateTime: Math.floor(sub(new Date(), { weeks: 5 }).getTime() / 1000) }]); render(<EditEmailSubscription />); expect(screen.queryByText('Proton welcome emails')).toBeNull(); }); }); describe('when user is not in beta', () => { it('should not display `beta announcements` toggle', () => { mockedUseUserSettings.mockReturnValue([{ EarlyAccess: 0, News: 4095 }]); render(<EditEmailSubscription />); expect(screen.queryByText('Proton beta announcements')).toBeNull(); }); }); });
5,802
0
petrpan-code/ProtonMail/WebClients/packages/components/containers
petrpan-code/ProtonMail/WebClients/packages/components/containers/addresses/AddressesWithUser.test.tsx
import { ComponentPropsWithoutRef } from 'react'; import { fireEvent, render } from '@testing-library/react'; import { OrderableTable, useAddresses, useAddressesKeys, useApi, useFlag, useKTVerifier, useNotifications, useUser, } from '@proton/components'; import { orderAddress } from '@proton/shared/lib/api/addresses'; import { ADDRESS_TYPE } from '@proton/shared/lib/constants'; import { Address, UserModel } from '@proton/shared/lib/interfaces'; import AddressesWithUser from './AddressesWithUser'; jest.mock('@proton/components/hooks/useEventManager', () => () => ({})); jest.mock('@proton/components/components/orderableTable/OrderableTable'); const ActualOrderableTable = jest.requireActual('@proton/components/components/orderableTable/OrderableTable').default; const mockedOrderableTable = OrderableTable as jest.MockedFunction<typeof OrderableTable>; jest.mock('@proton/components/hooks/useAddresses'); const mockedUseAddresses = useAddresses as jest.MockedFunction<typeof useAddresses>; jest.mock('@proton/components/hooks/useApi'); const mockedUseApi = useApi as jest.MockedFunction<typeof useApi>; jest.mock('@proton/components/hooks/useNotifications'); const mockedUseNotifications = useNotifications as jest.MockedFunction<typeof useNotifications>; jest.mock('@proton/components/hooks/useUser'); const mockedUseUser = useUser as jest.MockedFunction<typeof useUser>; jest.mock('@proton/components/hooks/useAddressesKeys'); const mockedUseAddressesKeys = useAddressesKeys as jest.MockedFunction<typeof useAddressesKeys>; jest.mock('@proton/components/containers/keyTransparency/useKTVerifier'); const mockedUseKTVerifier = useKTVerifier as jest.MockedFunction<typeof useKTVerifier>; jest.mock('@proton/components/containers/unleash/useFlag'); const mockedUseFlag = useFlag as jest.MockedFunction<any>; describe('addresses with user', () => { const user = { ID: 'abc', } as UserModel; const addresses = [ { ID: '1', Email: '[email protected]', Type: ADDRESS_TYPE.TYPE_ORIGINAL, Status: 1, Receive: 1, Send: 1, HasKeys: 1, }, { ID: '2', Email: '[email protected]', Type: ADDRESS_TYPE.TYPE_EXTERNAL, Status: 1, Receive: 0, Send: 0, HasKeys: 1, }, { ID: '3', Email: '[email protected]', Type: ADDRESS_TYPE.TYPE_ALIAS, Status: 1, Receive: 1, Send: 1, HasKeys: 1, }, { ID: '4', Email: '[email protected]', Type: ADDRESS_TYPE.TYPE_PREMIUM, Status: 0, Receive: 0, Send: 0, HasKeys: 1, }, ] as Address[]; mockedUseAddresses.mockReturnValue([addresses, false, null]); mockedOrderableTable.mockImplementation(ActualOrderableTable); mockedUseNotifications.mockReturnValue({} as any); mockedUseUser.mockReturnValue([{}] as any); mockedUseAddressesKeys.mockReturnValue([{}] as any); mockedUseKTVerifier.mockReturnValue({} as any); mockedUseFlag.mockReturnValue(true); const getFirstAddress = (container: HTMLElement) => { return container.querySelector('[title]'); }; it('should be able to set an alias as default', async () => { const mockApi = jest.fn(); mockedUseApi.mockReturnValue(mockApi); const { getByTestId, getByText, container } = render(<AddressesWithUser user={user} />); // Assumes that "Make default" is displayed on the address we're interested in fireEvent.click(getByTestId('dropdownActions:dropdown')); fireEvent.click(getByText('Set as default')); expect(mockApi).toHaveBeenCalledWith(orderAddress(['3', '1', '2', '4'])); expect(getFirstAddress(container)?.innerHTML).toBe('[email protected]'); }); describe('set as default', () => { const setup = () => { const createNotification = jest.fn(); mockedUseNotifications.mockReturnValue({ createNotification } as any); let onSortEnd: ComponentPropsWithoutRef<typeof OrderableTable>['onSortEnd']; mockedOrderableTable.mockImplementation((props) => { onSortEnd = props.onSortEnd; return <ActualOrderableTable {...props} />; }); const handleSortEnd: typeof onSortEnd = (...args) => { onSortEnd?.(...args); }; return { onSortEnd: handleSortEnd, createNotification }; }; it('should not be able to set an external address as default', () => { const { onSortEnd, createNotification } = setup(); const { container } = render(<AddressesWithUser user={user} />); onSortEnd({ newIndex: 0, oldIndex: 2 } as any, {} as any); expect(createNotification).toHaveBeenCalledWith({ type: 'error', text: 'An external address cannot be default', }); expect(getFirstAddress(container)?.innerHTML).toBe('[email protected]'); }); it('should not be able to set a disabled address as default', () => { const { onSortEnd, createNotification } = setup(); const { container } = render(<AddressesWithUser user={user} />); onSortEnd({ newIndex: 0, oldIndex: 3 } as any, {} as any); expect(createNotification).toHaveBeenCalledWith({ type: 'error', text: 'A disabled address cannot be default', }); expect(getFirstAddress(container)?.innerHTML).toBe('[email protected]'); }); }); });
5,909
0
petrpan-code/ProtonMail/WebClients/packages/components/containers
petrpan-code/ProtonMail/WebClients/packages/components/containers/calendar/CalendarLimitReachedModal.test.tsx
import { render, screen, waitFor } from '@testing-library/react'; import userEvent from '@testing-library/user-event'; import { mockUseConfig } from '@proton/testing/lib/mockUseConfig'; import { mockUseLocation } from '@proton/testing/lib/mockUseLocation'; import CalendarLimitReachedModal from './CalendarLimitReachedModal'; describe('CalendarLimitReachedModal', () => { beforeEach(() => { mockUseLocation(); mockUseConfig(); }); describe('when user is free', () => { it('should render correct prompt', async () => { const onClose = jest.fn(); render(<CalendarLimitReachedModal open onClose={onClose} isFreeUser />); expect(screen.getByRole('heading', { level: 1, name: /Cannot add more calendars/ })); expect(screen.getByText("You've reached the maximum number of calendars available in your plan.")); expect( screen.getByText( 'To add a new calendar, remove another calendar or upgrade your Proton plan to a Mail paid plan.' ) ); const link = screen.getByRole('link', { name: /Upgrade/ }); expect(link).toHaveAttribute('href', '/mail/upgrade?ref=upsell_calendar-modal-max-cal'); const button = screen.getByRole('button', { name: /Cancel/ }); await userEvent.click(button); await waitFor(() => { expect(onClose).toHaveBeenCalledTimes(1); }); }); }); describe('when user is paid', () => { it('should render correct prompt', async () => { const onClose = jest.fn(); render(<CalendarLimitReachedModal open onClose={onClose} isFreeUser={false} />); expect(screen.getByRole('heading', { level: 1, name: /Cannot add more calendars/ })); expect(screen.getByText("You've reached the maximum number of calendars available in your plan.")); expect(screen.getByText('To add a new calendar, remove an existing one.')); const link = screen.getByRole('link', { name: /Manage/ }); expect(link).toHaveAttribute('href', '/mail/calendars'); const button = screen.getByRole('button', { name: /Cancel/ }); await userEvent.click(button); await waitFor(() => { expect(onClose).toHaveBeenCalledTimes(1); }); }); }); });
5,922
0
petrpan-code/ProtonMail/WebClients/packages/components/containers/calendar/holidaysCalendarModal
petrpan-code/ProtonMail/WebClients/packages/components/containers/calendar/holidaysCalendarModal/tests/HolidaysCalendarModalWithDirectory.test.tsx
import { fireEvent, render, screen, waitFor, within } from '@testing-library/react'; import { mocked } from 'jest-mock'; import { useCalendarUserSettings, useNotifications } from '@proton/components/hooks'; import { ACCENT_COLORS_MAP } from '@proton/shared/lib/colors'; import { localeCode, setLocales } from '@proton/shared/lib/i18n'; import { HolidaysDirectoryCalendar, VisualCalendar } from '@proton/shared/lib/interfaces/calendar'; import { generateHolidaysCalendars } from '@proton/testing/lib/builders'; import { mockNotifications } from '@proton/testing/lib/mockNotifications'; import { CALENDAR_MODAL_TYPE } from '../../calendarModal'; import HolidaysCalendarModalWithDirectory from '../HolidaysCalendarModalWithDirectory'; jest.mock('@proton/components/hooks/useAddresses', () => ({ __esModule: true, default: jest.fn(() => []), useGetAddresses: jest.fn(), })); jest.mock('@proton/components/hooks/useGetCalendarBootstrap', () => ({ __esModule: true, default: jest.fn(() => () => Promise.resolve({ CalendarSettings: { DefaultFullDayNotifications: [] } })), useReadCalendarBootstrap: jest.fn(), })); jest.mock('@proton/components/hooks/useEventManager', () => () => ({})); jest.mock('@proton/components/containers/eventManager/calendar/ModelEventManagerProvider', () => ({ useCalendarModelEventManager: jest.fn(() => ({})), })); jest.mock('@proton/components/hooks/useGetAddressKeys', () => () => ({})); jest.mock('@proton/components/hooks/useNotifications'); jest.mock('@proton/components/hooks/useCalendarUserSettings', () => ({ ...jest.requireActual('@proton/components/hooks/useCalendarUserSettings'), useCalendarUserSettings: jest.fn(), })); const mockedColor = '#273EB2'; jest.mock('@proton/shared/lib/colors', () => ({ ...jest.requireActual('@proton/shared/lib/colors'), getRandomAccentColor: jest.fn(() => mockedColor), // return cobalt })); // Holidays calendars mocks const frCalendar = { CalendarID: 'calendarID1', Country: 'France', CountryCode: 'fr', Hidden: false, LanguageCode: 'fr', Language: 'Français', Timezones: ['Europe/Paris'], Passphrase: 'dummyPassphrase', SessionKey: { Key: 'dummyKey', Algorithm: 'dummyAlgorithm', }, }; const chEnCalendar = { CalendarID: 'calendarID2', Country: 'Switzerland', CountryCode: 'ch', Hidden: false, LanguageCode: 'en', Language: 'English', Timezones: ['Europe/Zurich'], Passphrase: 'dummyPassphrase', SessionKey: { Key: 'dummyKey', Algorithm: 'dummyAlgorithm', }, }; const chDeCalendar = { CalendarID: 'calendarID3', Country: 'Switzerland', CountryCode: 'ch', Hidden: false, LanguageCode: 'de', Language: 'Deutsch', Timezones: ['Europe/Zurich'], Passphrase: 'dummyPassphrase', SessionKey: { Key: 'dummyKey', Algorithm: 'dummyAlgorithm', }, }; const beFrCalendar = { CalendarID: 'calendarID4', Country: 'Belgium', CountryCode: 'be', Hidden: false, LanguageCode: 'fr', Language: 'Français', Timezones: ['Europe/Brussels'], Passphrase: 'dummyPassphrase', SessionKey: { Key: 'dummyKey', Algorithm: 'dummyAlgorithm', }, }; const beNlCalendar = { CalendarID: 'calendarID5', Country: 'Belgium', CountryCode: 'be', Hidden: false, LanguageCode: 'nl', Language: 'Dutch', Timezones: ['Europe/Brussels'], Passphrase: 'dummyPassphrase', SessionKey: { Key: 'dummyKey', Algorithm: 'dummyAlgorithm', }, }; const nlCalendar = { CalendarID: 'calendarID6', Country: 'Netherlands', CountryCode: 'nl', Hidden: false, LanguageCode: 'nl', Language: 'Dutch', Timezones: ['Europe/Brussels'], Passphrase: 'dummyPassphrase', SessionKey: { Key: 'dummyKey', Algorithm: 'dummyAlgorithm', }, }; const esCalendar = { CalendarID: 'calendarID7', Country: 'Spain', CountryCode: 'es', Hidden: false, LanguageCode: 'es', Language: 'Español', Timezones: ['Europe/Madrid'], Passphrase: 'dummyPassphrase', SessionKey: { Key: 'dummyKey', Algorithm: 'dummyAlgorithm', }, }; const esBaCalendar = { CalendarID: 'calendarID8', Country: 'Spain', CountryCode: 'es', Hidden: false, LanguageCode: 'eu', Language: 'Euskera', Timezones: ['Europe/Madrid'], Passphrase: 'dummyPassphrase', SessionKey: { Key: 'dummyKey', Algorithm: 'dummyAlgorithm', }, }; const esCaCalendar = { CalendarID: 'calendarID9', Country: 'Spain', CountryCode: 'es', Hidden: false, LanguageCode: 'ca', Language: 'Català', Timezones: ['Europe/Madrid'], Passphrase: 'dummyPassphrase', SessionKey: { Key: 'dummyKey', Algorithm: 'dummyAlgorithm', }, }; const esGlCalendar = { CalendarID: 'calendarID10', Country: 'Spain', CountryCode: 'es', Hidden: false, LanguageCode: 'gl', Language: 'Galego', Timezones: ['Europe/Madrid'], Passphrase: 'dummyPassphrase', SessionKey: { Key: 'dummyKey', Algorithm: 'dummyAlgorithm', }, }; const itItCalendar = { CalendarID: 'calendarID11', Country: 'Italy', CountryCode: 'it', Hidden: true, LanguageCode: 'it', Language: 'Italiano', Timezones: ['Europe/Rome'], Passphrase: 'dummyPassphrase', SessionKey: { Key: 'dummyKey', Algorithm: 'dummyAlgorithm', }, }; const directory: HolidaysDirectoryCalendar[] = [ frCalendar, chEnCalendar, chDeCalendar, beNlCalendar, beFrCalendar, nlCalendar, esCalendar, esBaCalendar, esCaCalendar, esGlCalendar, itItCalendar, ]; const holidaysCalendars: VisualCalendar[] = generateHolidaysCalendars(2, [ { id: frCalendar.CalendarID, name: 'Holidays in France', color: ACCENT_COLORS_MAP.cerise.color }, { id: chEnCalendar.CalendarID, name: 'Holidays in Switzerland', color: ACCENT_COLORS_MAP.carrot.color }, ]); describe('HolidaysCalendarModal - Subscribe to a holidays calendar', () => { const mockedUseNotifications = mocked(useNotifications); beforeEach(async () => { mockedUseNotifications.mockImplementation(() => mockNotifications); }); afterEach(async () => { setLocales({ localeCode: 'en_US', languageCode: 'en' }); }); const setup = ({ inputCalendar, holidaysCalendars = [], type = CALENDAR_MODAL_TYPE.COMPLETE, }: { inputCalendar?: VisualCalendar; holidaysCalendars?: VisualCalendar[]; type?: CALENDAR_MODAL_TYPE; }) => { render( <HolidaysCalendarModalWithDirectory calendar={inputCalendar} directory={directory} holidaysCalendars={holidaysCalendars} open type={type} /> ); }; describe('Add a holidays calendar', () => { describe('List of calendars', () => { it('should only offer non-hidden calendars', () => { // @ts-ignore useCalendarUserSettings.mockReturnValue([{ PrimaryTimezone: 'Something else' }, false]); setup({}); const countrySelect = screen.getByText('Please select a country'); fireEvent.click(countrySelect); // expected countries expect(screen.getByText('France')).toBeInTheDocument(); expect(screen.getByText('Switzerland')).toBeInTheDocument(); expect(screen.getByText('Belgium')).toBeInTheDocument(); expect(screen.getByText('Netherlands')).toBeInTheDocument(); expect(screen.getByText('Spain')).toBeInTheDocument(); // hidden countries expect(screen.queryByText('Italy')).not.toBeInTheDocument(); }); }); describe('Pre-selected fields', () => { it('should pre-select the suggested holidays calendar based on time zone', async () => { // Mock user's time zone to Paris // @ts-ignore useCalendarUserSettings.mockReturnValue([{ PrimaryTimezone: 'Europe/Paris' }, false]); setup({}); // Modal title and subtitle are displayed screen.getByText('Add public holidays'); screen.getByText("Get a country's official public holidays calendar."); // Country is pre-selected screen.getByText('France'); // Hint is displayed before country select focus screen.getByText('Based on your time zone'); const countrySelect = screen.getByTestId('country-select'); fireEvent.click(countrySelect); // Hint is displayed within country select within(screen.getByTestId('select-list')).getByText('Based on your time zone'); // Preselected option is focused const preselectedOption = await waitFor(() => screen.getByTestId('preselected-country-select-option')); expect(preselectedOption).toHaveTextContent('France'); expect(preselectedOption).toHaveClass('dropdown-item--is-selected'); // Language is NOT shown because there's only one available for this country const languageInput = screen.queryByTestId('holidays-calendar-modal:language-select'); expect(languageInput).toBeNull(); // Random color has been selected (we mock the result to be cobalt) screen.getByText('cobalt'); // No notification set const notificationInput = screen.queryByTestId('notification-time-input'); expect(notificationInput).toBeNull(); // Add notification button is visible screen.getByTestId('add-notification'); }); it('should pre-select the suggested holidays calendar based on time zone and user language', async () => { // Mock user's time zone to Zurich // @ts-ignore useCalendarUserSettings.mockReturnValue([{ PrimaryTimezone: 'Europe/Zurich' }, false]); setup({}); // Modal title and subtitle are displayed screen.getByText('Add public holidays'); screen.getByText("Get a country's official public holidays calendar."); // Country is pre-selected screen.getByText('Switzerland'); // Hint is displayed before country select focus screen.getByText('Based on your time zone'); const countrySelect = screen.getByTestId('country-select'); fireEvent.click(countrySelect); // Hint is displayed within country select within(screen.getByTestId('select-list')).getByText('Based on your time zone'); // Preselected option is focused const preselectedOption = await waitFor(() => screen.getByTestId('preselected-country-select-option')); expect(preselectedOption).toHaveTextContent('Switzerland'); expect(preselectedOption).toHaveClass('dropdown-item--is-selected'); // Language is shown because there's several languages for this country screen.getByText('English'); // Random color has been selected (we mock the result to be cobalt) screen.getByText('cobalt'); // No notification set const notificationInput = screen.queryByTestId('notification-time-input'); expect(notificationInput).toBeNull(); // Add notification button is visible screen.getByTestId('add-notification'); }); it('should pre-select the suggested holidays calendar based on time zone and first language', async () => { setLocales({ localeCode, languageCode: 'something' }); // Mock user's time zone to Spain // @ts-ignore useCalendarUserSettings.mockReturnValue([{ PrimaryTimezone: 'Europe/Madrid' }, false]); setup({}); // Modal title and subtitle are displayed screen.getByText('Add public holidays'); screen.getByText("Get a country's official public holidays calendar."); // Country is pre-selected screen.getByText('Spain'); // Hint is displayed before country select focus screen.getByText('Based on your time zone'); const countrySelect = screen.getByTestId('country-select'); fireEvent.click(countrySelect); // Hint is displayed within country select within(screen.getByTestId('select-list')).getByText('Based on your time zone'); // Preselected option is focused const preselectedOption = await waitFor(() => screen.getByTestId('preselected-country-select-option')); expect(preselectedOption).toHaveTextContent('Spain'); expect(preselectedOption).toHaveClass('dropdown-item--is-selected'); // Language is shown because there's several languages for this country screen.getByText('Català'); // Random color has been selected (we mock the result to be cobalt) screen.getByText('cobalt'); // No notification set const notificationInput = screen.queryByTestId('notification-time-input'); expect(notificationInput).toBeNull(); // Add notification button is visible screen.getByTestId('add-notification'); }); it('should not pre-select a suggested holidays calendar when no corresponding time zone is found', () => { // Mock user's time zone to something which does not exist in holidays calendars list we get // @ts-ignore useCalendarUserSettings.mockReturnValue([{ PrimaryTimezone: 'Something else' }, false]); setup({}); // Modal title and subtitle are displayed screen.getByText('Add public holidays'); screen.getByText("Get a country's official public holidays calendar."); // Country is NOT pre-selected screen.getByText('Please select a country'); // Hint is NOT displayed const hint = screen.queryByText('Based on your time zone'); expect(hint).toBeNull(); // Language is NOT shown because no default country is found const languageInput = screen.queryByTestId('holidays-calendar-modal:language-select'); expect(languageInput).toBeNull(); // Random color has been selected (we mock the result to be cobalt) screen.getByText('cobalt'); // No notification set const notificationInput = screen.queryByTestId('notification-time-input'); expect(notificationInput).toBeNull(); // Add notification button is visible screen.getByTestId('add-notification'); }); it('should not pre-select a suggested holidays calendar that is not visible', () => { // @ts-ignore useCalendarUserSettings.mockReturnValue([{ PrimaryTimezone: 'Europe/Rome' }, false]); setLocales({ localeCode: 'it_IT', languageCode: 'it' }); setup({}); // Modal title and subtitle are displayed screen.getByText('Add public holidays'); screen.getByText("Get a country's official public holidays calendar."); // Italy is NOT pre-selected and NOT offered screen.getByText('Please select a country'); }); }); describe('Already added holidays calendar', () => { it('should not pre-select the suggested calendar if the user already added it', () => { // Mock user's time zone to Paris // @ts-ignore useCalendarUserSettings.mockReturnValue([{ PrimaryTimezone: 'Europe/Paris' }, false]); setup({ holidaysCalendars }); // Modal title and subtitle are displayed screen.getByText('Add public holidays'); screen.getByText("Get a country's official public holidays calendar."); // Country is NOT pre-selected screen.getByText('Please select a country'); // Hint is NOT displayed const hint = screen.queryByText('Based on your time zone'); expect(hint).toBeNull(); // Language is NOT shown because there's only one available for this country const languageInput = screen.queryByTestId('holidays-calendar-modal:language-select'); expect(languageInput).toBeNull(); // Random color has been selected (we mock the result to be cobalt) screen.getByText('cobalt'); // No notification set const notificationInput = screen.queryByTestId('notification-time-input'); expect(notificationInput).toBeNull(); // Add notification button is visible screen.getByTestId('add-notification'); }); it('should display an error message when selecting a country of an already added holidays calendar', () => { // Mock user's time zone to Paris // @ts-ignore useCalendarUserSettings.mockReturnValue([{ PrimaryTimezone: 'Europe/Paris' }, false]); setup({ holidaysCalendars }); // Modal title and subtitle are displayed screen.getByText('Add public holidays'); screen.getByText("Get a country's official public holidays calendar."); // Country is NOT pre-selected const countryInput = screen.getByText('Please select a country'); // Open dropdown fireEvent.click(countryInput); // Select France const franceDropdownOption = screen.getByText('France'); fireEvent.click(franceDropdownOption); // Click "Add" const submitButton = screen.getByText('Add'); fireEvent.click(submitButton); // An error is displayed under the country input screen.getByText('You already added this holidays calendar'); }); }); }); describe('Edit a holidays calendar', () => { it('should pre-select all fields in modal', async () => { // Mock user's time zone to Paris // @ts-ignore useCalendarUserSettings.mockReturnValue([{ PrimaryTimezone: 'Europe/Paris' }, false]); setup({ holidaysCalendars, inputCalendar: holidaysCalendars[0], type: CALENDAR_MODAL_TYPE.COMPLETE, }); await waitFor(() => { expect(screen.getByText('Edit calendar')); }); // Modal title is displayed screen.getByText('Edit calendar'); // No modal subtitle is displayed const subtitle = screen.queryByText("Get a country's official public holidays calendar."); expect(subtitle).toBeNull(); // Edited country is selected screen.getByText('France'); // Hint should not be displayed on edition const hint = screen.queryByText('Based on your time zone'); expect(hint).toBeNull(); // Language is NOT shown because there's only one available for this country const languageInput = screen.queryByTestId('holidays-calendar-modal:language-select'); expect(languageInput).toBeNull(); // Random color has been selected (we mock the result to be cobalt) screen.getByText('cerise'); // Add notification button is NOT visible in edit mode const notificationButton = screen.queryByTestId('add-notification'); expect(notificationButton).toBeInTheDocument(); }); it('should display a message when user wants to change country to an already added holidays calendar', async () => { // Mock user's time zone to Zurich // @ts-ignore useCalendarUserSettings.mockReturnValue([{ PrimaryTimezone: 'Europe/Zurich' }, false]); setup({ holidaysCalendars, inputCalendar: holidaysCalendars[1], type: CALENDAR_MODAL_TYPE.COMPLETE, }); await waitFor(() => { expect(screen.getByText('Edit calendar')); }); // No modal subtitle is displayed const subtitle = screen.queryByText("Get a country's official public holidays calendar."); expect(subtitle).toBeNull(); // Country is pre-selected const countryInput = screen.getByText('Switzerland'); // Random color has been selected (we mock the result to be cobalt) screen.getByText('carrot'); // Add notification button is NOT visible in edit mode const notificationButton = screen.queryByTestId('add-notification'); expect(notificationButton).toBeInTheDocument(); // Open dropdown fireEvent.click(countryInput); // Select France const frDropdownOption = screen.getByText('France'); fireEvent.click(frDropdownOption); // An error is displayed under the country input after trying to save const submitButton = screen.getByText('Save'); fireEvent.click(submitButton); screen.getByText('You already added this holidays calendar'); }); it('should allow to edit a hidden calendar', async () => { // Mock user's time zone to Paris // @ts-ignore useCalendarUserSettings.mockReturnValue([{ PrimaryTimezone: 'Europe/Paris' }, false]); const holidaysCalendars = generateHolidaysCalendars(1, [ { id: itItCalendar.CalendarID, name: 'Giorni festivi e ricorrenze in Italia', color: ACCENT_COLORS_MAP.cerise.color, }, ]); setup({ holidaysCalendars, inputCalendar: holidaysCalendars[0], type: CALENDAR_MODAL_TYPE.COMPLETE, }); await waitFor(() => { expect(screen.getByText('Edit calendar')); }); // No modal subtitle is displayed const subtitle = screen.queryByText("Get a country's official public holidays calendar."); expect(subtitle).toBeNull(); // Edited country is selected screen.getByText('Italy'); }); }); });
5,952
0
petrpan-code/ProtonMail/WebClients/packages/components/containers/calendar
petrpan-code/ProtonMail/WebClients/packages/components/containers/calendar/settings/CalendarMemberAndInvitationList.test.tsx
import { render, screen } from '@testing-library/react'; import { mocked } from 'jest-mock'; import { useNotifications } from '@proton/components/hooks'; import { CalendarMember, CalendarMemberInvitation, MEMBER_INVITATION_STATUS, } from '@proton/shared/lib/interfaces/calendar'; import { mockNotifications } from '@proton/testing'; import CalendarMemberAndInvitationList from './CalendarMemberAndInvitationList'; jest.mock('@proton/components/hooks/useGetEncryptionPreferences'); jest.mock('@proton/components/hooks/useNotifications'); jest.mock('@proton/components/hooks/useAddresses'); jest.mock('../../contacts/ContactEmailsProvider', () => ({ useContactEmailsCache: () => ({ contactEmails: [], contactGroups: [], contactEmailsMap: { '[email protected]': { Name: 'Abraham Trump', Email: '[email protected]', }, '[email protected]': { Name: 'Unknown Person', Email: '[email protected]', }, }, groupsWithContactsMap: {}, }), })); const mockedUseNotifications = mocked(useNotifications); describe('CalendarMemberAndInvitationList', () => { beforeEach(() => { mockedUseNotifications.mockImplementation(() => mockNotifications); }); it(`doesn't display anything if there are no members or invitations`, () => { const { container } = render( <CalendarMemberAndInvitationList members={[]} invitations={[]} canEdit onDeleteInvitation={() => Promise.resolve()} onDeleteMember={() => Promise.resolve()} calendarID="1" /> ); expect(container).toBeEmptyDOMElement(); }); it('displays a members and invitations with available data', () => { const members = [ { ID: 'member1', Email: '[email protected]', Permissions: 96, }, ] as CalendarMember[]; const invitations = [ { CalendarInvitationID: 'invitation1', Email: '[email protected]', // TODO: change when free/busy becomes available // Permissions: 64, Permissions: 96, Status: MEMBER_INVITATION_STATUS.PENDING, }, { CalendarInvitationID: 'invitation2', Email: '[email protected]', Permissions: 112, Status: MEMBER_INVITATION_STATUS.REJECTED, }, ] as CalendarMemberInvitation[]; const { rerender } = render( <CalendarMemberAndInvitationList members={members} invitations={invitations} canEdit onDeleteInvitation={() => Promise.resolve()} onDeleteMember={() => Promise.resolve()} calendarID="1" /> ); expect(screen.getByText(/^AT$/)).toBeInTheDocument(); expect(screen.getByText(/[email protected]/)).toBeInTheDocument(); expect(screen.queryByText(/[email protected]/)).not.toBeInTheDocument(); // Temporary until free/busy becomes available // expect(screen.getByText(/See all event details/)).toBeInTheDocument(); expect(screen.getAllByText(/See all event details/).length).toBeTruthy(); // String is found 2 times due to responsive behaviour. // We need two buttons, each with the label "Remove this member" const removeMemberLabel = screen.getAllByText(/Remove this member/); expect(removeMemberLabel).toHaveLength(2); expect(screen.getByText(/^UP$/)).toBeInTheDocument(); expect(screen.getByText(/[email protected]/)).toBeInTheDocument(); // expect(screen.getByText(/See only free\/busy/)).toBeInTheDocument(); expect(screen.getByText(/Invite sent/)).toBeInTheDocument(); expect(screen.getByText(/^I$/)).toBeInTheDocument(); expect(screen.getByText(/[email protected]/)).toBeInTheDocument(); expect(screen.getByText(/Declined/)).toBeInTheDocument(); expect(screen.getAllByText(/Revoke this invitation/).length).toBe(2); expect(screen.getAllByText(/Delete/).length).toBe(2); /* * Check cannot edit case * * It should be possible to remove members * * It shouldn't be possible to edit permissions */ rerender( <CalendarMemberAndInvitationList members={members} invitations={invitations} canEdit={false} onDeleteInvitation={() => Promise.resolve()} onDeleteMember={() => Promise.resolve()} calendarID="1" /> ); const changePermissionsButtons = screen.getAllByRole('button', { name: /See all event details|Edit/ }); changePermissionsButtons.forEach((button) => { expect(button).toBeDisabled(); }); const removeThisMemberButtons = screen.getAllByRole('button', { name: /Remove this member/ }); removeThisMemberButtons.forEach((button) => { expect(button).not.toBeDisabled(); }); }); });
5,962
0
petrpan-code/ProtonMail/WebClients/packages/components/containers/calendar
petrpan-code/ProtonMail/WebClients/packages/components/containers/calendar/settings/CalendarsSection.test.tsx
import { Router } from 'react-router-dom'; import { render, screen } from '@testing-library/react'; import { createMemoryHistory } from 'history'; import createCache from '@proton/shared/lib/helpers/cache'; import { UserModel } from '@proton/shared/lib/interfaces'; import { generateSimpleCalendar } from '@proton/testing/lib/builders'; import { CacheProvider } from '../../cache'; import ModalsProvider from '../../modals/Provider'; import CalendarsSection, { CalendarsSectionProps } from './CalendarsSection'; jest.mock('../../../hooks/useAddresses', () => ({ __esModule: true, default: jest.fn(() => [ [ { Email: '[email protected]', Status: 1, Receive: 1, Send: 1, }, ], ]), useGetAddresses: jest.fn(), })); jest.mock('../../../hooks/useEventManager', () => () => ({})); jest.mock('../../eventManager/calendar/useCalendarsInfoListener', () => () => ({})); jest.mock('../../eventManager/calendar/ModelEventManagerProvider', () => ({ useCalendarModelEventManager: jest.fn(), })); jest.mock('@proton/components/hooks/useConfig', () => () => ({ APP_NAME: 'proton-calendar', APP_VERSION: 'test' })); jest.mock('@proton/components/hooks/useAddresses', () => ({ __esModule: true, default: jest.fn(() => [ [ { Email: '[email protected]', Status: 1, Receive: 1, Send: 1, }, ], ]), useGetAddresses: jest.fn(), })); function renderComponent(props?: Partial<CalendarsSectionProps>) { const defaultProps: CalendarsSectionProps = { addresses: [], calendars: [], children: null, // defaultCalendarID?: string, user: { hasPaidMail: false } as UserModel, // loading?: boolean, // onSetDefault?: (id: string) => Promise<void>, onEdit: jest.fn(), onDelete: jest.fn(), // onExport?: (calendar: Calendar) => void, }; return ( <ModalsProvider> <Router history={createMemoryHistory()}> <CacheProvider cache={createCache()}> <CalendarsSection {...defaultProps} {...props} /> </CacheProvider> </Router> </ModalsProvider> ); } describe('CalendarsSection', () => { it('renders properly', () => { render( renderComponent({ calendars: [generateSimpleCalendar(1, { name: 'calendar1' })], }) ); expect(screen.getByText('calendar1')).toBeInTheDocument(); }); it('does not render a table when no calendars are provided', () => { render(renderComponent()); expect(screen.queryByRole('table')).not.toBeInTheDocument(); }); });
5,964
0
petrpan-code/ProtonMail/WebClients/packages/components/containers/calendar
petrpan-code/ProtonMail/WebClients/packages/components/containers/calendar/settings/CalendarsSettingsSection.test.tsx
import { Router } from 'react-router'; import { render, screen, within } from '@testing-library/react'; import { createMemoryHistory } from 'history'; import { MAX_CALENDARS_FREE, MAX_CALENDARS_PAID } from '@proton/shared/lib/calendar/constants'; import { ADDRESS_RECEIVE, ADDRESS_SEND, ADDRESS_STATUS, BRAND_NAME, MAIL_SHORT_APP_NAME, } from '@proton/shared/lib/constants'; import { RequireOnly, UserModel } from '@proton/shared/lib/interfaces'; import { SubscribedCalendar, VisualCalendar } from '@proton/shared/lib/interfaces/calendar'; import { addressBuilder, generateHolidaysCalendars, generateOwnedPersonalCalendars, generateSharedCalendars, generateSubscribedCalendars, } from '@proton/testing/lib/builders'; import { IconName } from '../../../components'; import CalendarsSettingsSection, { CalendarsSettingsSectionProps } from './CalendarsSettingsSection'; jest.mock('../../../hooks/useCalendarShareInvitations', () => jest.fn().mockReturnValue({ loading: false, invitations: [], }) ); jest.mock('../../../hooks/useCalendarShareInvitationActions', () => jest.fn().mockReturnValue({ accept: () => {}, reject: () => {}, }) ); jest.mock('../../../hooks/useConfig', () => () => ({ CLIENT_TYPE: 1, CLIENT_SECRET: 'not_so_secret', APP_VERSION: 'test', APP_NAME: 'proton-calendar', API_URL: 'api', LOCALES: {}, DATE_VERSION: 'test', COMMIT: 'test', BRANCH: 'test', SENTRY_DSN: 'test', VERSION_PATH: 'test', })); jest.mock('../../../hooks/useAppTitle', () => jest.fn().mockReturnValue(undefined)); jest.mock('../../../hooks/useApi', () => jest.fn(() => jest.fn().mockResolvedValue({}))); jest.mock('../../../hooks/useEventManager', () => () => ({})); jest.mock('../../eventManager/calendar/useCalendarsInfoListener', () => () => ({})); jest.mock('../../eventManager/calendar/ModelEventManagerProvider', () => ({ useCalendarModelEventManager: jest.fn(() => ({ call: jest.fn() })), })); jest.mock('@proton/components/hooks/useNotifications', () => () => ({})); jest.mock('@proton/components/hooks/useFeature', () => jest.fn(() => ({ feature: { Value: true } }))); jest.mock('@proton/components/hooks/useEarlyAccess', () => () => ({})); jest.mock('@proton/components/containers/calendar/hooks/useHolidaysDirectory', () => ({ __esModule: true, default: jest.fn(() => []), })); let memoryHistory = createMemoryHistory(); const renderComponent = ({ user, addresses = [addressBuilder()], calendars, myCalendars, subscribedCalendars, sharedCalendars, unknownCalendars = [], holidaysCalendars = [], }: RequireOnly< CalendarsSettingsSectionProps, 'user' | 'calendars' | 'myCalendars' | 'sharedCalendars' | 'subscribedCalendars' >) => { const config = { icon: 'calendar' as IconName, to: '/calendars', text: 'Calendars', subsections: [ { text: 'My calendars', id: 'my-calendars' }, { text: 'Other calendars', id: 'other-calendars' }, ], }; render( <Router history={memoryHistory}> <CalendarsSettingsSection config={config} user={user} addresses={addresses} calendars={calendars} myCalendars={myCalendars} subscribedCalendars={subscribedCalendars} sharedCalendars={sharedCalendars} holidaysCalendars={holidaysCalendars} unknownCalendars={unknownCalendars} /> </Router> ); }; describe('My calendars section', () => { const createCalendarText = `Create calendar`; const addCalendarText = `Add calendar from URL`; const addHolidaysCalendarText = `Add public holidays`; const limitReachedFreeText = `You've reached the maximum number of calendars available in your plan. To add a new calendar, remove another calendar or upgrade your ${BRAND_NAME} plan to a ${MAIL_SHORT_APP_NAME} paid plan.`; const limitReachedPaidText = `You've reached the maximum number of calendars available in your plan. To add a new calendar, remove an existing one.`; describe('for a Mail free user', () => { it('allows the user to create both personal and other calendars if under the limit', () => { const user = { isFree: false, hasPaidMail: false, hasNonDelinquentScope: true } as UserModel; const myCalendars: VisualCalendar[] = []; const sharedCalendars: VisualCalendar[] = []; const subscribedCalendars = generateSubscribedCalendars(1); const calendars = [...myCalendars, ...sharedCalendars, ...subscribedCalendars]; renderComponent({ user, calendars, myCalendars, sharedCalendars, subscribedCalendars, }); expect(screen.queryAllByText(limitReachedFreeText)).toHaveLength(0); expect(screen.queryAllByText(createCalendarText)).toHaveLength(1); expect(screen.queryAllByText(addCalendarText)).toHaveLength(1); expect(screen.queryAllByText(addHolidaysCalendarText)).toHaveLength(1); }); it('displays the limit reached message in both "My calendars" and "Other calendars" section when the user reaches the calendar limit with personal owned calendars', () => { const user = { isFree: false, hasPaidMail: false, hasNonDelinquentScope: true } as UserModel; const myCalendars = generateOwnedPersonalCalendars(MAX_CALENDARS_FREE); const sharedCalendars: VisualCalendar[] = []; const subscribedCalendars: SubscribedCalendar[] = []; const calendars = [...myCalendars, ...sharedCalendars, ...subscribedCalendars]; renderComponent({ user, calendars, myCalendars, sharedCalendars, subscribedCalendars, }); expect(screen.queryAllByText(limitReachedFreeText)).toHaveLength(2); expect(screen.queryAllByText(createCalendarText)).toHaveLength(0); expect(screen.queryAllByText(addCalendarText)).toHaveLength(0); }); it('displays the limit reached message only in "Other calendars" section when the user reached the calendar limit with shared and subscribed calendars (only possible for pre-plans-migration users), and allows creation of owned personal calendars', () => { const user = { isFree: false, hasPaidMail: false, hasNonDelinquentScope: true } as UserModel; const myCalendars: VisualCalendar[] = []; const sharedCalendars = generateSharedCalendars(MAX_CALENDARS_FREE - 2); const subscribedCalendars = generateSubscribedCalendars(2); const calendars = [...myCalendars, ...sharedCalendars, ...subscribedCalendars]; renderComponent({ user, calendars, myCalendars, sharedCalendars, subscribedCalendars, }); expect(screen.queryAllByText(limitReachedFreeText)).toHaveLength(1); expect(screen.queryAllByText(createCalendarText)).toHaveLength(1); }); it('prevents user from creating MAX_CALENDARS_FREE other calendars by displaying limit reached message', () => { const user = { isFree: false, hasPaidMail: false, hasNonDelinquentScope: true } as UserModel; const myCalendars: VisualCalendar[] = []; const sharedCalendars = generateSharedCalendars(1); const subscribedCalendars = generateSubscribedCalendars(MAX_CALENDARS_FREE - 2); const calendars = [...myCalendars, ...sharedCalendars, ...subscribedCalendars]; renderComponent({ user, calendars, myCalendars, sharedCalendars, subscribedCalendars, }); expect(screen.queryAllByText(limitReachedFreeText)).toHaveLength(1); expect(screen.queryAllByText(createCalendarText)).toHaveLength(1); expect(screen.queryAllByText(addCalendarText)).toHaveLength(0); expect(screen.queryAllByText(addHolidaysCalendarText)).toHaveLength(0); }); it('prevents user without active addresses from creating personal or other calendars', () => { const user = { isFree: true, hasPaidMail: false, hasNonDelinquentScope: true } as UserModel; const addresses = [ { ...addressBuilder(), Receive: ADDRESS_RECEIVE.RECEIVE_NO, Send: ADDRESS_SEND.SEND_NO, Status: ADDRESS_STATUS.STATUS_DISABLED, }, ]; const myCalendars = generateOwnedPersonalCalendars(0); const sharedCalendars = generateSharedCalendars(0); const subscribedCalendars = generateSubscribedCalendars(0); const calendars = [...myCalendars, ...sharedCalendars, ...subscribedCalendars]; renderComponent({ user, addresses, calendars, myCalendars, sharedCalendars, subscribedCalendars, }); const createCalendarButton = screen.getByText(createCalendarText); const addCalendarButton = screen.getByText(addCalendarText); const addHolidaysCalendarButton = screen.getByText(addHolidaysCalendarText); expect(screen.queryAllByText(limitReachedPaidText)).toHaveLength(0); expect(createCalendarButton).toBeInTheDocument(); expect(createCalendarButton).toBeDisabled(); expect(addCalendarButton).toBeInTheDocument(); expect(addCalendarButton).toBeDisabled(); expect(addHolidaysCalendarButton).toBeInTheDocument(); expect(addHolidaysCalendarButton).toBeDisabled(); }); it('prevents delinquent user from creating personal or other calendars', () => { const user = { isFree: true, hasPaidMail: false, hasNonDelinquentScope: false } as UserModel; const myCalendars = generateOwnedPersonalCalendars(0); const sharedCalendars = generateSharedCalendars(0); const subscribedCalendars = generateSubscribedCalendars(0); const calendars = [...myCalendars, ...sharedCalendars, ...subscribedCalendars]; renderComponent({ user, calendars, myCalendars, sharedCalendars, subscribedCalendars, }); const createCalendarButton = screen.getByText(createCalendarText); const addCalendarButton = screen.getByText(addCalendarText); const addHolidaysCalendarButton = screen.getByText(addHolidaysCalendarText); expect(screen.queryAllByText(limitReachedPaidText)).toHaveLength(0); expect(createCalendarButton).toBeInTheDocument(); expect(createCalendarButton).toBeDisabled(); expect(addCalendarButton).toBeInTheDocument(); expect(addCalendarButton).toBeDisabled(); expect(addHolidaysCalendarButton).toBeInTheDocument(); expect(addHolidaysCalendarButton).toBeDisabled(); }); }); describe('for a Mail paid user', () => { it('allows the user to create both personal and other calendars if under the limit', () => { const user = { isFree: false, hasPaidMail: true, hasNonDelinquentScope: true } as UserModel; const myCalendars = generateOwnedPersonalCalendars(7); const sharedCalendars = generateSharedCalendars(4); const subscribedCalendars = generateSubscribedCalendars(5); const calendars = [...myCalendars, ...sharedCalendars, ...subscribedCalendars]; renderComponent({ user, calendars, myCalendars, sharedCalendars, subscribedCalendars, }); expect(screen.queryAllByText(limitReachedFreeText)).toHaveLength(0); expect(screen.queryAllByText(createCalendarText)).toHaveLength(1); expect(screen.queryAllByText(addCalendarText)).toHaveLength(1); expect(screen.queryAllByText(addHolidaysCalendarText)).toHaveLength(1); }); it('displays the limit reached message in both "My calendars" and "Other calendars" section when the user reaches the calendar limit with personal owned calendars', () => { const user = { isFree: false, hasPaidMail: true, hasNonDelinquentScope: true } as UserModel; const myCalendars = generateOwnedPersonalCalendars(MAX_CALENDARS_PAID); const sharedCalendars: VisualCalendar[] = []; const subscribedCalendars: SubscribedCalendar[] = []; const calendars = [...myCalendars, ...sharedCalendars, ...subscribedCalendars]; renderComponent({ user, calendars, myCalendars, sharedCalendars, subscribedCalendars, }); expect(screen.queryAllByText(limitReachedPaidText)).toHaveLength(2); expect(screen.queryAllByText(createCalendarText)).toHaveLength(0); expect(screen.queryAllByText(addCalendarText)).toHaveLength(0); expect(screen.queryAllByText(addHolidaysCalendarText)).toHaveLength(0); }); it('prevents user from creating MAX_CALENDARS_PAID other calendars by display limit reached message', () => { const user = { isFree: false, hasPaidMail: true, hasNonDelinquentScope: true } as UserModel; const myCalendars: VisualCalendar[] = []; const sharedCalendars = generateSharedCalendars(MAX_CALENDARS_PAID - 2); const subscribedCalendars = generateSubscribedCalendars(1); const calendars = [...myCalendars, ...sharedCalendars, ...subscribedCalendars]; renderComponent({ user, calendars, myCalendars, sharedCalendars, subscribedCalendars, }); expect(screen.queryAllByText(limitReachedPaidText)).toHaveLength(1); expect(screen.queryAllByText(createCalendarText)).toHaveLength(1); expect(screen.queryAllByText(addCalendarText)).toHaveLength(0); expect(screen.queryAllByText(addHolidaysCalendarText)).toHaveLength(0); }); it('prevents user without active addresses from creating personal or other calendars', () => { const user = { isFree: false, hasPaidMail: true, hasNonDelinquentScope: true } as UserModel; const addresses = [ { ...addressBuilder(), Receive: ADDRESS_RECEIVE.RECEIVE_NO, Send: ADDRESS_SEND.SEND_NO, Status: ADDRESS_STATUS.STATUS_DISABLED, }, ]; const myCalendars = generateOwnedPersonalCalendars(2); const sharedCalendars = generateSharedCalendars(0); const subscribedCalendars = generateSubscribedCalendars(0); const calendars = [...myCalendars, ...sharedCalendars, ...subscribedCalendars]; renderComponent({ user, addresses, calendars, myCalendars, sharedCalendars, subscribedCalendars, }); const createCalendarButton = screen.getByText(createCalendarText); const addCalendarButton = screen.getByText(addCalendarText); const addHolidaysCalendarButton = screen.getByText(addHolidaysCalendarText); expect(screen.queryAllByText(limitReachedPaidText)).toHaveLength(0); expect(createCalendarButton).toBeInTheDocument(); expect(createCalendarButton).toBeDisabled(); expect(addCalendarButton).toBeInTheDocument(); expect(addCalendarButton).toBeDisabled(); expect(addHolidaysCalendarButton).toBeInTheDocument(); expect(addHolidaysCalendarButton).toBeDisabled(); }); it('prevents delinquent user from creating personal or other calendars', () => { const user = { isFree: false, hasPaidMail: true, hasNonDelinquentScope: false } as UserModel; const myCalendars = generateOwnedPersonalCalendars(1); const sharedCalendars = generateSharedCalendars(1); const subscribedCalendars = generateSubscribedCalendars(1); const calendars = [...myCalendars, ...sharedCalendars, ...subscribedCalendars]; renderComponent({ user, calendars, myCalendars, sharedCalendars, subscribedCalendars, }); const createCalendarButton = screen.getByText(createCalendarText); const addCalendarButton = screen.getByText(addCalendarText); const addHolidaysCalendarButton = screen.getByText(addHolidaysCalendarText); expect(screen.queryAllByText(limitReachedPaidText)).toHaveLength(0); expect(createCalendarButton).toBeInTheDocument(); expect(createCalendarButton).toBeDisabled(); expect(addCalendarButton).toBeInTheDocument(); expect(addCalendarButton).toBeDisabled(); expect(addHolidaysCalendarButton).toBeInTheDocument(); expect(addHolidaysCalendarButton).toBeDisabled(); }); }); describe("displays user's calendars", () => { it('in their respective sections', async () => { const user = { isFree: false, hasPaidMail: true, hasNonDelinquentScope: true } as UserModel; const myCalendars = generateOwnedPersonalCalendars(2, [{ name: 'Calendar 1' }, { name: 'Calendar 2' }]); const subscribedCalendars = generateSubscribedCalendars(2, [ { name: 'Calendar 3' }, { name: 'Calendar 4' }, ]); const sharedCalendars = generateSharedCalendars(2, [{ name: 'Calendar 5' }, { name: 'Calendar 6' }]); const holidaysCalendars = generateHolidaysCalendars(2, [{ name: 'Calendar 7' }, { name: 'Calendar 8' }]); const calendars = [...myCalendars, ...sharedCalendars, ...holidaysCalendars, ...subscribedCalendars]; renderComponent({ user, calendars, myCalendars, sharedCalendars, holidaysCalendars, subscribedCalendars, }); const myCalendarsSection = await screen.findByTestId('my-calendars-section'); const susbcribedCalendarsSection = await screen.findByTestId('subscribed-calendars-section'); const sharedCalendarsSection = await screen.findByTestId('shared-calendars-section'); const holidaysCalendarsSection = await screen.findByTestId('holidays-calendars-section'); within(myCalendarsSection).getByText(myCalendars[0].Name); within(myCalendarsSection).getByText(myCalendars[1].Name); within(susbcribedCalendarsSection).getByText(subscribedCalendars[0].Name); within(susbcribedCalendarsSection).getByText(subscribedCalendars[1].Name); within(sharedCalendarsSection).getByText(`${sharedCalendars[0].Name} (${sharedCalendars[0].Owner.Email})`); within(sharedCalendarsSection).getByText(`${sharedCalendars[1].Name} (${sharedCalendars[1].Owner.Email})`); within(holidaysCalendarsSection).getByText(holidaysCalendars[0].Name); within(holidaysCalendarsSection).getByText(holidaysCalendars[1].Name); }); }); });
5,980
0
petrpan-code/ProtonMail/WebClients/packages/components/containers/calendar
petrpan-code/ProtonMail/WebClients/packages/components/containers/calendar/shareProton/ShareCalendarModal.test.tsx
import { act, render, screen, waitFor } from '@testing-library/react'; import userEvent from '@testing-library/user-event'; import { mocked } from 'jest-mock'; import { useApi, useGetEncryptionPreferences, useNotifications } from '@proton/components/hooks'; import { PublicKeyReference } from '@proton/crypto'; import { MIME_TYPES, PGP_SCHEMES } from '@proton/shared/lib/constants'; import createCache from '@proton/shared/lib/helpers/cache'; import { EncryptionPreferences } from '@proton/shared/lib/mail/encryptionPreferences'; import { addressBuilder, calendarBuilder, mockApiWithServer, mockNotifications, server } from '@proton/testing'; import { CacheProvider } from '../../cache'; import ShareCalendarModal from './ShareCalendarModal'; jest.mock('@proton/components/hooks/useGetEncryptionPreferences'); jest.mock('@proton/components/hooks/useNotifications'); jest.mock('@proton/components/hooks/useApi'); jest.mock('@proton/components/hooks/useAddresses'); jest.mock('../../contacts/ContactEmailsProvider', () => ({ useContactEmailsCache: () => ({ contactEmails: [], contactGroups: [], contactEmailsMap: {}, groupsWithContactsMap: {}, }), })); const mockedUseApi = mocked(useApi); const mockedUseNotifications = mocked(useNotifications); const mockedUseGetEncryptionPreferences = mocked(useGetEncryptionPreferences); const mockedEncryptionPreferences: EncryptionPreferences = { encrypt: true, sign: true, scheme: PGP_SCHEMES.PGP_INLINE, mimeType: MIME_TYPES.PLAINTEXT, isInternalWithDisabledE2EEForMail: false, sendKey: 'anything' as unknown as PublicKeyReference, apiKeys: [], pinnedKeys: [], verifyingPinnedKeys: [], isInternal: true, hasApiKeys: true, hasPinnedKeys: true, isContact: true, // error: new EncryptionPreferencesError(ENCRYPTION_PREFERENCES_ERROR_TYPES.EMAIL_ADDRESS_ERROR, 'EMAIL_ADDRESS_ERROR'), }; function renderComponent({ members = [], invitations = [] } = {}) { const Wrapper = ({ children }: any) => <CacheProvider cache={createCache()}>{children}</CacheProvider>; return render( <ShareCalendarModal members={members} invitations={invitations} calendar={calendarBuilder()} addresses={[addressBuilder()]} onFinish={() => {}} open />, { wrapper: Wrapper } ); } function addRecipients(emails: string[]) { const emailInput = screen.getByTitle('Email address'); screen.debug(emailInput, 10000000); act(() => { emails.forEach(async (email) => { // FIXME: same issue as in MainContainer.spec.tsx, it doesn't enter recipients await userEvent.type(emailInput, `${email}{enter}`); }); }); } xdescribe('ShareCalendarModal', () => { beforeAll(() => server.listen()); afterAll(() => server.close()); beforeEach(() => { mockedUseApi.mockImplementation(() => mockApiWithServer); mockedUseNotifications.mockImplementation(() => mockNotifications); mockedUseGetEncryptionPreferences.mockImplementation(() => () => Promise.resolve(mockedEncryptionPreferences)); }); afterEach(() => { server.resetHandlers(); }); it(`removes duplicate recipients and self addresses when added and displays a notification`, async () => { renderComponent(); addRecipients(['[email protected]']); await waitFor(() => { expect(screen.getByText(/[email protected]/)).toBeInTheDocument(); }); expect(screen.getByText(/[email protected]/)).toBeInTheDocument(); expect(screen.queryByText(/legit\[email protected]/)).not.toBeInTheDocument(); expect(screen.queryByText(/[email protected]/)).not.toBeInTheDocument(); expect(mockedUseNotifications().createNotification).toHaveBeenCalledTimes(2); }); it(`displays errors for existing members, invalid emails and exceeding the limit before submitting`, () => { renderComponent(); }); it(`displays errors for non-proton, non-existing and other errors after submitting`, () => { // assistive text when non-proton renderComponent(); }); it(`disables the share button if there are no recipients or there are errors`, () => { renderComponent(); expect(screen.getByText(/Share/, { selector: 'button' })).toBeDisabled(); }); it(`shows a loading state when submitting and a notification once done`, () => { renderComponent(); }); });
5,990
0
petrpan-code/ProtonMail/WebClients/packages/components/containers/calendar
petrpan-code/ProtonMail/WebClients/packages/components/containers/calendar/subscribedCalendarModal/SubscribedCalendarModal.test.tsx
import { render, screen, waitFor } from '@testing-library/react'; import userEvent from '@testing-library/user-event'; import createCache from '@proton/shared/lib/helpers/cache'; import { CALENDAR_SUBSCRIPTION_STATUS } from '@proton/shared/lib/interfaces/calendar'; import { CacheProvider } from '../../cache'; import SubscribedCalendarModal from './SubscribedCalendarModal'; jest.mock('../hooks/useGetCalendarSetup', () => () => ({})); jest.mock('@proton/components/hooks/useNotifications', () => () => ({})); jest.mock('../calendarModal/calendarModalState', () => ({ ...jest.requireActual('../calendarModal/calendarModalState'), getDefaultModel: jest.fn(() => ({ calendarID: '7824929ac66f483ba12ee051c056b9e5', name: 'A fake calendar', members: [], description: 'a fake description', color: '#8080FF', display: true, addressID: 'fa4ea8f5e6ac4df494f8190a6c9d9bd9', addressOptions: [], duration: 30, type: 0, })), })); const mockApi = jest.fn(); jest.mock('@proton/components/hooks/useApi', () => ({ __esModule: true, default: jest.fn(() => mockApi), })); const mockHandleCreateCalendar = jest.fn(); jest.mock('../hooks/useGetCalendarActions', () => ({ __esModule: true, default: jest.fn(() => ({ handleCreateCalendar: mockHandleCreateCalendar, })), })); jest.mock('@proton/components/hooks/useEventManager', () => ({ __esModule: true, default: jest.fn(() => ({ call: jest.fn(), subscribe: jest.fn(), })), })); jest.mock('@proton/components/containers/eventManager/calendar/ModelEventManagerProvider', () => ({ useCalendarModelEventManager: jest.fn(() => ({ subscribe: jest.fn(), })), })); function renderComponent() { const Wrapper = ({ children }: { children: any }) => ( <CacheProvider cache={createCache()}>{children}</CacheProvider> ); return render(<SubscribedCalendarModal open />, { wrapper: Wrapper }); } describe('SubscribedCalendarModal', () => { afterEach(() => { mockApi.mockReset(); mockHandleCreateCalendar.mockReset(); }); describe('when validation API returns a validation error', () => { it('should display an error message and not call mockUseGetCalendarActions', async () => { renderComponent(); mockApi.mockResolvedValue({ ValidationResult: { Result: CALENDAR_SUBSCRIPTION_STATUS.INVALID_URL } }); const submitButton = screen.getByText('Add calendar', { selector: 'button' }); const input = screen.getByLabelText('Calendar URL'); const invalidGoogleCalendarLink = `https://calendar.google.com/public/a.ics`; expect(submitButton).toBeDisabled(); input.focus(); await userEvent.paste(invalidGoogleCalendarLink); expect(submitButton).toBeEnabled(); await userEvent.click(submitButton); await screen.findByText('Invalid URL'); expect(mockApi).toHaveBeenCalledTimes(1); expect(mockApi).toHaveBeenCalledWith({ data: { Mode: 1, URL: 'https://calendar.google.com/public/a.ics' }, method: 'post', silence: true, url: 'calendar/v1/subscription/validate', }); expect(mockHandleCreateCalendar).not.toHaveBeenCalled(); }); }); describe('when validation returns OK', () => { it('should call `handleCreateCalendar`', async () => { renderComponent(); mockApi.mockResolvedValue({ ValidationResult: { Result: CALENDAR_SUBSCRIPTION_STATUS.OK } }); mockHandleCreateCalendar.mockImplementation(() => Promise.resolve()); const submitButton = screen.getByText('Add calendar', { selector: 'button' }); const input = screen.getByLabelText('Calendar URL'); const invalidGoogleCalendarLink = `https://calendar.google.com/public/a.ics`; expect(submitButton).toBeDisabled(); input.focus(); await userEvent.paste(invalidGoogleCalendarLink); expect(submitButton).toBeEnabled(); await userEvent.click(submitButton); // wait for the last api call to be made await waitFor(() => expect(mockHandleCreateCalendar).toHaveBeenCalledTimes(1)); expect(mockApi).toHaveBeenCalledTimes(1); expect(mockApi).toHaveBeenCalledWith({ data: { Mode: 1, URL: 'https://calendar.google.com/public/a.ics' }, method: 'post', silence: true, url: 'calendar/v1/subscription/validate', }); expect(mockHandleCreateCalendar).toHaveBeenCalledWith( 'fa4ea8f5e6ac4df494f8190a6c9d9bd9', { Color: '#8080FF', Description: 'a fake description', Display: 1, Name: 'https://calendar.google.com/public/a.ics', URL: 'https://calendar.google.com/public/a.ics', }, { DefaultEventDuration: 30, DefaultFullDayNotifications: [], DefaultPartDayNotifications: [] } ); }); }); });
6,013
0
petrpan-code/ProtonMail/WebClients/packages/components/containers/contacts
petrpan-code/ProtonMail/WebClients/packages/components/containers/contacts/edit/ContactEditModal.test.tsx
import { fireEvent, waitFor } from '@testing-library/react'; import { CryptoProxy } from '@proton/crypto'; import { API_CODES, CONTACT_CARD_TYPE } from '@proton/shared/lib/constants'; import { parseToVCard } from '@proton/shared/lib/contacts/vcard'; import { wait } from '@proton/shared/lib/helpers/promise'; import { api, clearAll, mockedCryptoApi, notificationManager, render } from '../tests/render'; import ContactEditModal, { ContactEditModalProps, ContactEditProps } from './ContactEditModal'; jest.mock('../../../hooks/useAuthentication', () => { return { __esModule: true, default: jest.fn(() => ({ getUID: jest.fn(), })), }; }); jest.mock('../../../hooks/useConfig', () => () => ({ API_URL: 'api' })); jest.mock('@proton/shared/lib/helpers/image.ts', () => { return { toImage: (src: string) => ({ src }), }; }); describe('ContactEditModal', () => { const props: ContactEditProps & ContactEditModalProps = { contactID: 'ContactID', vCardContact: { fn: [] }, onUpgrade: jest.fn(), onSelectImage: jest.fn(), onGroupEdit: jest.fn(), onLimitReached: jest.fn(), }; beforeAll(() => { CryptoProxy.setEndpoint(mockedCryptoApi); }); beforeEach(clearAll); afterAll(async () => { await CryptoProxy.releaseEndpoint(); }); it('should prefill all fields with contact values', async () => { const vcard = `BEGIN:VCARD VERSION:4.0 UID:urn:uuid:4fbe8971-0bc3-424c-9c26-36c3e1eff6b1 FN:J. Doe FN:FN2 EMAIL:[email protected] NOTE:TestNote ADR:1;2;3;4;5;6;7 ADR:;;;;;;testadr TEL:testtel PHOTO:https://example.com/myphoto.jpg END:VCARD`; const vCardContact = parseToVCard(vcard); const { getByDisplayValue } = render(<ContactEditModal open={true} {...props} vCardContact={vCardContact} />); // To see the image loaded await wait(0); getByDisplayValue('J. Doe'); expect(document.querySelector('img[src="https://example.com/myphoto.jpg"]')).not.toBe(null); getByDisplayValue('FN2'); getByDisplayValue('[email protected]'); getByDisplayValue('testtel'); getByDisplayValue('1'); getByDisplayValue('4'); getByDisplayValue('5'); getByDisplayValue('6'); getByDisplayValue('7'); getByDisplayValue('testadr'); getByDisplayValue('TestNote'); }); it.skip('should update basic properties', async () => { const vcard = `BEGIN:VCARD VERSION:4.0 UID:urn:uuid:4fbe8971-0bc3-424c-9c26-36c3e1eff6b1 FN:J. Doe EMAIL:[email protected] TEL:testtel NOTE:TestNote END:VCARD`; const vCardContact = parseToVCard(vcard); const saveRequestSpy = jest.fn(); api.mockImplementation(async (args: any): Promise<any> => { if (args.url === 'contacts/v4/contacts') { saveRequestSpy(args.data); return { Responses: [{ Response: { Code: API_CODES.SINGLE_SUCCESS } }] }; } if (args.url === 'contacts/v4/contacts/ContactID') { saveRequestSpy(args.data); return { Code: API_CODES.SINGLE_SUCCESS }; } }); const { getByDisplayValue, getByTestId, getByText } = render( <ContactEditModal open={true} {...props} vCardContact={vCardContact} /> ); const name = getByDisplayValue('J. Doe'); fireEvent.change(name, { target: { value: 'New name' } }); const email = getByDisplayValue('[email protected]'); fireEvent.change(email, { target: { value: '[email protected]' } }); const tel = getByDisplayValue('testtel'); fireEvent.change(tel, { target: { value: 'newtel' } }); const note = getByDisplayValue('TestNote'); fireEvent.change(note, { target: { value: 'NewNote' } }); const addButton = getByTestId('add-other'); fireEvent.click(addButton); const properties = document.querySelectorAll('[data-contact-property-id]'); const newProperty = properties[properties.length - 1]; const typeSelect = newProperty.querySelector('button.select'); fireEvent.click(typeSelect as Element); const titleOption = document.querySelector('.dropdown button[title="Title"]'); fireEvent.click(titleOption as Element); const titleInput = getByTestId('Title'); fireEvent.change(titleInput, { target: { value: 'NewTitle' } }); const saveButton = getByText('Save'); fireEvent.click(saveButton); await waitFor(() => { if (notificationManager.createNotification.mock.calls.length > 0) { throw new Error(); } }); const sentData = saveRequestSpy.mock.calls[0][0]; const cards = sentData.Cards; const signedCardContent = cards.find( ({ Type }: { Type: CONTACT_CARD_TYPE }) => Type === CONTACT_CARD_TYPE.SIGNED ).Data; const encryptedCardContent = cards.find( ({ Type }: { Type: CONTACT_CARD_TYPE }) => Type === CONTACT_CARD_TYPE.ENCRYPTED_AND_SIGNED ).Data; const expectedSignedCard = `BEGIN:VCARD VERSION:4.0 UID:urn:uuid:4fbe8971-0bc3-424c-9c26-36c3e1eff6b1 FN;PREF=1:New name ITEM1.EMAIL;PREF=1:[email protected] END:VCARD`.replaceAll('\n', '\r\n'); const expectedEncryptedCard = `BEGIN:VCARD VERSION:4.0 TEL;PREF=1:newtel NOTE:NewNote N:;;;; TITLE:NewTitle END:VCARD`.replaceAll('\n', '\r\n'); expect(signedCardContent).toBe(expectedSignedCard); expect(encryptedCardContent).toBe(expectedEncryptedCard); }); it('should create a contact', async () => { const saveRequestSpy = jest.fn(); api.mockImplementation(async (args: any): Promise<any> => { if (args.url === 'contacts/v4/contacts') { saveRequestSpy(args.data); return { Responses: [{ Response: { Code: API_CODES.SINGLE_SUCCESS } }] }; } if (args.url === 'contacts/v4/contacts/ContactID') { saveRequestSpy(args.data); return { Code: API_CODES.SINGLE_SUCCESS }; } }); const { getByTestId, getByText } = render(<ContactEditModal open={true} {...props} />); const firstName = getByTestId('First name'); fireEvent.change(firstName, { target: { value: 'Bruno' } }); const lastName = getByTestId('Last name'); fireEvent.change(lastName, { target: { value: 'Mars' } }); const displayName = getByTestId('Enter a display name or nickname'); fireEvent.change(displayName, { target: { value: 'New name' } }); const email = getByTestId('Email'); fireEvent.change(email, { target: { value: '[email protected]' } }); const saveButton = getByText('Save'); fireEvent.click(saveButton); await waitFor(() => expect(notificationManager.createNotification).toHaveBeenCalled()); const sentData = saveRequestSpy.mock.calls[0][0]; const cards = sentData.Cards; const signedCardContent = cards.find( ({ Type }: { Type: CONTACT_CARD_TYPE }) => Type === CONTACT_CARD_TYPE.SIGNED ).Data; const encryptedCardContent = cards.find( ({ Type }: { Type: CONTACT_CARD_TYPE }) => Type === CONTACT_CARD_TYPE.ENCRYPTED_AND_SIGNED ).Data; expect(signedCardContent).toContain('FN;PREF=1:New name'); expect(signedCardContent).toContain('ITEM1.EMAIL;PREF=1:[email protected]'); expect(encryptedCardContent).toContain('N:Mars;Bruno;;;'); }); it('should trigger an error if display name is empty when creating a contact', async () => { const { getByText } = render(<ContactEditModal open={true} {...props} />); const saveButton = getByText('Save'); fireEvent.click(saveButton); const errorZone = getByText('Please provide either a first name, a last name or a display name'); expect(errorZone).toBeVisible(); }); it('should trigger an error if display name is empty when editing a contact', async () => { const vcard = `BEGIN:VCARD VERSION:4.0 UID:urn:uuid:4fbe8971-0bc3-424c-9c26-36c3e1eff6b1 EMAIL:[email protected] END:VCARD`; const vCardContact = parseToVCard(vcard); const { getByText } = render(<ContactEditModal open={true} {...props} vCardContact={vCardContact} />); const saveButton = getByText('Save'); fireEvent.click(saveButton); const errorZone = getByText('This field is required'); expect(errorZone).toBeVisible(); }); });
6,029
0
petrpan-code/ProtonMail/WebClients/packages/components/containers/contacts
petrpan-code/ProtonMail/WebClients/packages/components/containers/contacts/email/ContactEmailSettingsModal.test.tsx
import { fireEvent, waitFor } from '@testing-library/react'; import { CryptoProxy } from '@proton/crypto'; import { API_CODES, CONTACT_CARD_TYPE, KEY_FLAG } from '@proton/shared/lib/constants'; import { parseToVCard } from '@proton/shared/lib/contacts/vcard'; import { RequireSome } from '@proton/shared/lib/interfaces'; import { VCardContact, VCardProperty } from '@proton/shared/lib/interfaces/contacts/VCard'; import { api, clearAll, mockedCryptoApi, notificationManager, render } from '../tests/render'; import ContactEmailSettingsModal, { ContactEmailSettingsProps } from './ContactEmailSettingsModal'; describe('ContactEmailSettingsModal', () => { const props: ContactEmailSettingsProps = { contactID: 'ContactID', vCardContact: { fn: [] }, emailProperty: {} as VCardProperty<string>, onClose: jest.fn(), }; beforeEach(clearAll); afterEach(async () => { await CryptoProxy.releaseEndpoint(); }); it('should save a contact with updated email settings (no keys)', async () => { CryptoProxy.setEndpoint(mockedCryptoApi); const vcard = `BEGIN:VCARD VERSION:4.0 FN;PREF=1:J. Doe UID:urn:uuid:4fbe8971-0bc3-424c-9c26-36c3e1eff6b1 ITEM1.EMAIL;PREF=1:[email protected] END:VCARD`; const vCardContact = parseToVCard(vcard) as RequireSome<VCardContact, 'email'>; const saveRequestSpy = jest.fn(); api.mockImplementation(async (args: any): Promise<any> => { if (args.url === 'core/v4/keys/all') { return { Address: { Keys: [] } }; } if (args.url === 'contacts/v4/contacts') { saveRequestSpy(args.data); return { Responses: [{ Response: { Code: API_CODES.SINGLE_SUCCESS } }] }; } if (args.url === 'contacts/v4/contacts/ContactID') { saveRequestSpy(args.data); return { Code: API_CODES.SINGLE_SUCCESS }; } }); const { getByText, getByTitle } = render( <ContactEmailSettingsModal open={true} {...props} vCardContact={vCardContact} emailProperty={vCardContact.email?.[0]} /> ); const showMoreButton = getByText('Show advanced PGP settings'); await waitFor(() => expect(showMoreButton).not.toBeDisabled()); fireEvent.click(showMoreButton); const encryptToggle = document.getElementById('encrypt-toggle'); expect(encryptToggle).toBeDisabled(); const signSelect = getByText("Use global default (Don't sign)", { exact: false }); fireEvent.click(signSelect); const signOption = getByTitle('Sign'); fireEvent.click(signOption); const pgpSelect = getByText('Use global default (PGP/MIME)', { exact: false }); fireEvent.click(pgpSelect); const pgpInlineOption = getByTitle('PGP/Inline'); fireEvent.click(pgpInlineOption); const saveButton = getByText('Save'); fireEvent.click(saveButton); await waitFor(() => expect(notificationManager.createNotification).toHaveBeenCalled()); const sentData = saveRequestSpy.mock.calls[0][0]; const cards = sentData.Cards; const expectedEncryptedCard = `BEGIN:VCARD VERSION:4.0 FN;PREF=1:J. Doe UID:urn:uuid:4fbe8971-0bc3-424c-9c26-36c3e1eff6b1 ITEM1.EMAIL;PREF=1:[email protected] ITEM1.X-PM-MIMETYPE:text/plain ITEM1.X-PM-SIGN:true ITEM1.X-PM-SCHEME:pgp-inline END:VCARD`.replaceAll('\n', '\r\n'); const signedCardContent = cards.find( ({ Type }: { Type: CONTACT_CARD_TYPE }) => Type === CONTACT_CARD_TYPE.SIGNED ).Data; expect(signedCardContent).toBe(expectedEncryptedCard); }); it('should not store X-PM-SIGN if global default signing setting is selected', async () => { CryptoProxy.setEndpoint(mockedCryptoApi); const vcard = `BEGIN:VCARD VERSION:4.0 FN;PREF=1:J. Doe UID:urn:uuid:4fbe8971-0bc3-424c-9c26-36c3e1eff6b1 ITEM1.EMAIL;PREF=1:[email protected] ITEM1.X-PM-SIGN:true END:VCARD`; const vCardContact = parseToVCard(vcard) as RequireSome<VCardContact, 'email'>; const saveRequestSpy = jest.fn(); api.mockImplementation(async (args: any): Promise<any> => { if (args.url === 'core/v4/keys/all') { return { Address: { Keys: [] } }; } if (args.url === 'contacts/v4/contacts') { saveRequestSpy(args.data); return { Responses: [{ Response: { Code: API_CODES.SINGLE_SUCCESS } }] }; } if (args.url === 'contacts/v4/contacts/ContactID') { saveRequestSpy(args.data); return { Code: API_CODES.SINGLE_SUCCESS }; } }); const { getByText, getByTitle } = render( <ContactEmailSettingsModal open={true} {...props} vCardContact={vCardContact} emailProperty={vCardContact.email?.[0]} /> ); const showMoreButton = getByText('Show advanced PGP settings'); await waitFor(() => expect(showMoreButton).not.toBeDisabled()); fireEvent.click(showMoreButton); const signSelect = getByText('Sign', { exact: true }); fireEvent.click(signSelect); const signOption = getByTitle("Use global default (Don't sign)"); fireEvent.click(signOption); const saveButton = getByText('Save'); fireEvent.click(saveButton); await waitFor(() => expect(notificationManager.createNotification).toHaveBeenCalled()); const sentData = saveRequestSpy.mock.calls[0][0]; const cards = sentData.Cards; const expectedCard = `BEGIN:VCARD VERSION:4.0 FN;PREF=1:J. Doe UID:urn:uuid:4fbe8971-0bc3-424c-9c26-36c3e1eff6b1 ITEM1.EMAIL;PREF=1:[email protected] END:VCARD`.replaceAll('\n', '\r\n'); const signedCardContent = cards.find( ({ Type }: { Type: CONTACT_CARD_TYPE }) => Type === CONTACT_CARD_TYPE.SIGNED ).Data; expect(signedCardContent).toBe(expectedCard); }); it('should warn if encryption is enabled and uploaded keys are not valid for sending', async () => { CryptoProxy.setEndpoint({ ...mockedCryptoApi, importPublicKey: jest.fn().mockImplementation(async () => ({ getFingerprint: () => `abcdef`, getCreationTime: () => new Date(0), getExpirationTime: () => new Date(0), getAlgorithmInfo: () => ({ algorithm: 'eddsa', curve: 'curve25519' }), subkeys: [], getUserIDs: jest.fn().mockImplementation(() => ['<[email protected]>']), })), canKeyEncrypt: jest.fn().mockImplementation(() => false), exportPublicKey: jest.fn().mockImplementation(() => new Uint8Array()), isExpiredKey: jest.fn().mockImplementation(() => true), isRevokedKey: jest.fn().mockImplementation(() => false), }); const vcard = `BEGIN:VCARD VERSION:4.0 FN;PREF=1:expired UID:proton-web-b2dc0409-262d-96db-8925-3ee4f0030fd8 ITEM1.EMAIL;PREF=1:[email protected] ITEM1.KEY;PREF=1:data:application/pgp-keys;base64,xjMEYS376BYJKwYBBAHaRw8BA QdAm9ZJKSCnCg28vJ/1Iegycsiq9wKxFP5/BMDeP51C/jbNGmV4cGlyZWQgPGV4cGlyZWRAdGVz dC5jb20+wpIEEBYKACMFAmEt++gFCQAAAPoECwkHCAMVCAoEFgACAQIZAQIbAwIeAQAhCRDs7cn 9e8csRhYhBP/xHanO8KRS6sPFiOztyf17xyxGhYIBANpMcbjGa3w3qPzWDfb3b/TgfbJuYFQ49Y ik/Zd/ZZQZAP42rtyxbSz/XfKkNdcJPbZ+MQa2nalOZ6+uXm9ScCQtBc44BGEt++gSCisGAQQBl 1UBBQEBB0Dj+ZNzODXqLeZchFOVE4E87HD8QsoSI60bDkpklgK3eQMBCAfCfgQYFggADwUCYS37 6AUJAAAA+gIbDAAhCRDs7cn9e8csRhYhBP/xHanO8KRS6sPFiOztyf17xyxGbyIA/2Jz6p/6WBo yh279kjiKpX8NWde/2/O7M7W7deYulO4oAQDWtYZNTw1OTYfYI2PBcs1kMbB3hhBr1VEG0pLvtz xoAA== ITEM1.X-PM-ENCRYPT:true ITEM1.X-PM-SIGN:true END:VCARD`; const vCardContact = parseToVCard(vcard) as RequireSome<VCardContact, 'email'>; const saveRequestSpy = jest.fn(); api.mockImplementation(async (args: any): Promise<any> => { if (args.url === 'core/v4/keys/all') { return { Address: { Keys: [] } }; } if (args.url === 'contacts/v4/contacts') { saveRequestSpy(args.data); return { Responses: [{ Response: { Code: API_CODES.SINGLE_SUCCESS } }] }; } if (args.url === 'contacts/v4/contacts/ContactID') { saveRequestSpy(args.data); return { Code: API_CODES.SINGLE_SUCCESS }; } }); const { getByText } = render( <ContactEmailSettingsModal open={true} {...props} vCardContact={vCardContact} emailProperty={vCardContact.email?.[0]} /> ); const showMoreButton = getByText('Show advanced PGP settings'); await waitFor(() => expect(showMoreButton).not.toBeDisabled()); fireEvent.click(showMoreButton); await waitFor(() => { const keyFingerprint = getByText('abcdef'); return expect(keyFingerprint).toBeVisible(); }); const warningInvalidKey = getByText(/None of the uploaded keys are valid for encryption/); expect(warningInvalidKey).toBeVisible(); const encryptToggleLabel = getByText('Encrypt emails'); fireEvent.click(encryptToggleLabel); expect(warningInvalidKey).not.toBeVisible(); const saveButton = getByText('Save'); fireEvent.click(saveButton); await waitFor(() => expect(notificationManager.createNotification).toHaveBeenCalled()); const sentData = saveRequestSpy.mock.calls[0][0]; const cards = sentData.Cards; const signedCardContent = cards.find( ({ Type }: { Type: CONTACT_CARD_TYPE }) => Type === CONTACT_CARD_TYPE.SIGNED ).Data; expect(signedCardContent.includes('ITEM1.X-PM-ENCRYPT:false')).toBe(true); }); it('should enable encryption by default if WKD keys are found', async () => { CryptoProxy.setEndpoint({ ...mockedCryptoApi, importPublicKey: jest.fn().mockImplementation(async () => ({ getFingerprint: () => `abcdef`, getCreationTime: () => new Date(0), getExpirationTime: () => new Date(0), getAlgorithmInfo: () => ({ algorithm: 'eddsa', curve: 'curve25519' }), subkeys: [], getUserIDs: jest.fn().mockImplementation(() => ['<[email protected]>']), })), canKeyEncrypt: jest.fn().mockImplementation(() => true), exportPublicKey: jest.fn().mockImplementation(() => new Uint8Array()), isExpiredKey: jest.fn().mockImplementation(() => false), isRevokedKey: jest.fn().mockImplementation(() => false), }); const armoredPublicKey = `-----BEGIN PGP PUBLIC KEY BLOCK----- xjMEYRaiLRYJKwYBBAHaRw8BAQdAMrsrfniSJuxOLn+Q3VKP0WWqgizG4VOF 6t0HZYx8mSnNEHRlc3QgPHRlc3RAYS5pdD7CjAQQFgoAHQUCYRaiLQQLCQcI AxUICgQWAAIBAhkBAhsDAh4BACEJEKaNwv/NOLSZFiEEnJT1OMsrVBCZa+wE po3C/804tJnYOAD/YR2og60sJ2VVhPwYRL258dYIHnJXI2dDXB+m76GK9x4A /imlPnTOgIJAV1xOqkvO96QcbawjKgvH829zxN9DZEgMzjgEYRaiLRIKKwYB BAGXVQEFAQEHQN5UswYds0RWr4I7xNKNK+fOn+o9pYkkYzJwCbqxCsBwAwEI B8J4BBgWCAAJBQJhFqItAhsMACEJEKaNwv/NOLSZFiEEnJT1OMsrVBCZa+wE po3C/804tJkeKgEA0ruKx9rcMTi4LxfYgijjPrI+GgrfegfREt/YN2KQ75gA /Rs9S+8arbQVoniq7izz3uisWxfjMup+IVEC5uqMld8L =8+ep -----END PGP PUBLIC KEY BLOCK-----`; const vcard = `BEGIN:VCARD VERSION:4.0 FN;PREF=1:J. Doe UID:urn:uuid:4fbe8971-0bc3-424c-9c26-36c3e1eff6b1 ITEM1.EMAIL;PREF=1:[email protected] ITEM1.X-PM-ENCRYPT:true END:VCARD`; const vCardContact = parseToVCard(vcard) as RequireSome<VCardContact, 'email'>; const saveRequestSpy = jest.fn(); api.mockImplementation(async (args: any): Promise<any> => { if (args.url === 'core/v4/keys/all') { return { Address: { Keys: [] }, Unverified: { Keys: [{ Flags: 3, PublicKey: armoredPublicKey }], }, }; } if (args.url === 'contacts/v4/contacts') { saveRequestSpy(args.data); return { Responses: [{ Response: { Code: API_CODES.SINGLE_SUCCESS } }] }; } if (args.url === 'contacts/v4/contacts/ContactID') { saveRequestSpy(args.data); return { Code: API_CODES.SINGLE_SUCCESS }; } }); const { getByText } = render( <ContactEmailSettingsModal open={true} {...props} vCardContact={vCardContact} emailProperty={vCardContact.email?.[0]} /> ); const showMoreButton = getByText('Show advanced PGP settings'); await waitFor(() => expect(showMoreButton).not.toBeDisabled()); fireEvent.click(showMoreButton); const encryptToggle = document.getElementById('encrypt-toggle'); expect(encryptToggle).not.toBeDisabled(); expect(encryptToggle).toBeChecked(); const signSelectDropdown = document.getElementById('sign-select'); expect(signSelectDropdown).toBeDisabled(); signSelectDropdown?.innerHTML.includes('Sign'); const saveButton = getByText('Save'); fireEvent.click(saveButton); await waitFor(() => expect(notificationManager.createNotification).toHaveBeenCalled()); const sentData = saveRequestSpy.mock.calls[0][0]; const cards = sentData.Cards; const expectedEncryptedCard = `BEGIN:VCARD VERSION:4.0 FN;PREF=1:J. Doe UID:urn:uuid:4fbe8971-0bc3-424c-9c26-36c3e1eff6b1 ITEM1.EMAIL;PREF=1:[email protected] ITEM1.X-PM-ENCRYPT-UNTRUSTED:true ITEM1.X-PM-SIGN:true END:VCARD`.replaceAll('\n', '\r\n'); const signedCardContent = cards.find( ({ Type }: { Type: CONTACT_CARD_TYPE }) => Type === CONTACT_CARD_TYPE.SIGNED ).Data; expect(signedCardContent).toBe(expectedEncryptedCard); }); it('should warn if encryption is enabled and WKD keys are not valid for sending', async () => { CryptoProxy.setEndpoint({ ...mockedCryptoApi, importPublicKey: jest.fn().mockImplementation(async () => ({ getFingerprint: () => `abcdef`, getCreationTime: () => new Date(0), getExpirationTime: () => new Date(0), getAlgorithmInfo: () => ({ algorithm: 'eddsa', curve: 'curve25519' }), subkeys: [], getUserIDs: jest.fn().mockImplementation(() => ['<[email protected]>']), })), canKeyEncrypt: jest.fn().mockImplementation(() => false), exportPublicKey: jest.fn().mockImplementation(() => new Uint8Array()), isExpiredKey: jest.fn().mockImplementation(() => true), isRevokedKey: jest.fn().mockImplementation(() => false), }); const armoredPublicKey = `-----BEGIN PGP PUBLIC KEY BLOCK----- xjMEYS376BYJKwYBBAHaRw8BAQdAm9ZJKSCnCg28vJ/1Iegycsiq9wKxFP5/ BMDeP51C/jbNGmV4cGlyZWQgPGV4cGlyZWRAdGVzdC5jb20+wpIEEBYKACMF AmEt++gFCQAAAPoECwkHCAMVCAoEFgACAQIZAQIbAwIeAQAhCRDs7cn9e8cs RhYhBP/xHanO8KRS6sPFiOztyf17xyxGhYIBANpMcbjGa3w3qPzWDfb3b/Tg fbJuYFQ49Yik/Zd/ZZQZAP42rtyxbSz/XfKkNdcJPbZ+MQa2nalOZ6+uXm9S cCQtBc44BGEt++gSCisGAQQBl1UBBQEBB0Dj+ZNzODXqLeZchFOVE4E87HD8 QsoSI60bDkpklgK3eQMBCAfCfgQYFggADwUCYS376AUJAAAA+gIbDAAhCRDs 7cn9e8csRhYhBP/xHanO8KRS6sPFiOztyf17xyxGbyIA/2Jz6p/6WBoyh279 kjiKpX8NWde/2/O7M7W7deYulO4oAQDWtYZNTw1OTYfYI2PBcs1kMbB3hhBr 1VEG0pLvtzxoAA== =456g -----END PGP PUBLIC KEY BLOCK-----`; const vcard = `BEGIN:VCARD VERSION:4.0 FN;PREF=1:J. Doe UID:urn:uuid:4fbe8971-0bc3-424c-9c26-36c3e1eff6b1 ITEM1.EMAIL;PREF=1:[email protected] END:VCARD`; const vCardContact = parseToVCard(vcard) as RequireSome<VCardContact, 'email'>; const saveRequestSpy = jest.fn(); api.mockImplementation(async (args: any): Promise<any> => { if (args.url === 'core/v4/keys/all') { return { Address: { Keys: [] }, Unverified: { Keys: [{ Flags: 3, PublicKey: armoredPublicKey }] }, }; } if (args.url === 'contacts/v4/contacts') { saveRequestSpy(args.data); return { Responses: [{ Response: { Code: API_CODES.SINGLE_SUCCESS } }] }; } if (args.url === 'contacts/v4/contacts/ContactID') { saveRequestSpy(args.data); return { Code: API_CODES.SINGLE_SUCCESS }; } }); const { getByText } = render( <ContactEmailSettingsModal open={true} {...props} vCardContact={vCardContact} emailProperty={vCardContact.email?.[0]} /> ); const showMoreButton = getByText('Show advanced PGP settings'); await waitFor(() => expect(showMoreButton).not.toBeDisabled()); fireEvent.click(showMoreButton); await waitFor(() => { const keyFingerprint = getByText('abcdef'); return expect(keyFingerprint).toBeVisible(); }); const warningInvalidKey = getByText(/None of the uploaded keys are valid for encryption/); expect(warningInvalidKey).toBeVisible(); const encryptToggleLabel = getByText('Encrypt emails'); fireEvent.click(encryptToggleLabel); expect(warningInvalidKey).not.toBeVisible(); const saveButton = getByText('Save'); fireEvent.click(saveButton); await waitFor(() => expect(notificationManager.createNotification).toHaveBeenCalled()); const sentData = saveRequestSpy.mock.calls[0][0]; const cards = sentData.Cards; const signedCardContent = cards.find( ({ Type }: { Type: CONTACT_CARD_TYPE }) => Type === CONTACT_CARD_TYPE.SIGNED ).Data; expect(signedCardContent.includes('ITEM1.X-PM-ENCRYPT-UNTRUSTED:false')).toBe(true); }); it('should indicate that end-to-end encryption is disabled for internal addresses whose keys have e2ee-disabled flags', async () => { CryptoProxy.setEndpoint({ ...mockedCryptoApi, importPublicKey: jest.fn().mockImplementation(async () => ({ getFingerprint: () => `abcdef`, getCreationTime: () => new Date(0), getExpirationTime: () => new Date(0), getAlgorithmInfo: () => ({ algorithm: 'eddsa', curve: 'curve25519' }), subkeys: [], getUserIDs: jest.fn().mockImplementation(() => ['<[email protected]>']), })), canKeyEncrypt: jest.fn().mockImplementation(() => true), exportPublicKey: jest.fn().mockImplementation(() => new Uint8Array()), isExpiredKey: jest.fn().mockImplementation(() => false), isRevokedKey: jest.fn().mockImplementation(() => false), }); const vcard = `BEGIN:VCARD VERSION:4.0 FN;PREF=1:J. Doe UID:urn:uuid:4fbe8971-0bc3-424c-9c26-36c3e1eff6b1 ITEM1.EMAIL;PREF=1:[email protected] END:VCARD`; const vCardContact = parseToVCard(vcard) as RequireSome<VCardContact, 'email'>; const saveRequestSpy = jest.fn(); api.mockImplementation(async (args: any): Promise<any> => { if (args.url === 'core/v4/keys/all') { return { Address: { Keys: [ { PublicKey: 'mocked armored key', Flags: KEY_FLAG.FLAG_EMAIL_NO_ENCRYPT | KEY_FLAG.FLAG_NOT_COMPROMISED, }, ], }, ProtonMX: true, // internal address }; } if (args.url === 'contacts/v4/contacts') { saveRequestSpy(args.data); return { Responses: [{ Response: { Code: API_CODES.SINGLE_SUCCESS } }] }; } if (args.url === 'contacts/v4/contacts/ContactID') { saveRequestSpy(args.data); return { Code: API_CODES.SINGLE_SUCCESS }; } }); const { getByText, getByTitle, queryByText } = render( <ContactEmailSettingsModal open={true} {...props} vCardContact={vCardContact} emailProperty={vCardContact.email?.[0]} /> ); const showMoreButton = getByText('Show advanced PGP settings'); await waitFor(() => expect(showMoreButton).not.toBeDisabled()); fireEvent.click(showMoreButton); await waitFor(() => { const keyFingerprint = getByText('abcdef'); return expect(keyFingerprint).toBeVisible(); }); const infoEncryptionDisabled = getByText(/The owner of this address has disabled end-to-end encryption/); expect(infoEncryptionDisabled).toBeVisible(); expect(queryByText('Encrypt emails')).toBeNull(); expect(queryByText('Sign emails')).toBeNull(); expect(queryByText('Upload keys')).toBeNull(); const dropdownButton = getByTitle('Open actions dropdown'); fireEvent.click(dropdownButton); const trustKeyButton = getByText('Trust'); fireEvent.click(trustKeyButton); const saveButton = getByText('Save'); fireEvent.click(saveButton); await waitFor(() => expect(notificationManager.createNotification).toHaveBeenCalled()); const sentData = saveRequestSpy.mock.calls[0][0]; const cards = sentData.Cards; const signedCardContent = cards.find( ({ Type }: { Type: CONTACT_CARD_TYPE }) => Type === CONTACT_CARD_TYPE.SIGNED ).Data; expect(signedCardContent.includes('ITEM1.KEY;PREF=1:data:application/pgp-keys')).toBe(true); expect(signedCardContent.includes('ITEM1.X-PM-ENCRYPT')).toBe(false); expect(signedCardContent.includes('ITEM1.X-PM-SIGN')).toBe(false); }); it('shoul display WKD keys but not internal address keys for external account with internal address keys', async () => { CryptoProxy.setEndpoint({ ...mockedCryptoApi, importPublicKey: jest.fn().mockImplementation(async ({ armoredKey }) => ({ getFingerprint: () => armoredKey, getCreationTime: () => new Date(0), getExpirationTime: () => new Date(0), getAlgorithmInfo: () => ({ algorithm: 'eddsa', curve: 'curve25519' }), subkeys: [], getUserIDs: jest.fn().mockImplementation(() => ['<[email protected]>']), })), canKeyEncrypt: jest.fn().mockImplementation(() => true), exportPublicKey: jest.fn().mockImplementation(() => new Uint8Array()), isExpiredKey: jest.fn().mockImplementation(() => false), isRevokedKey: jest.fn().mockImplementation(() => false), }); const vcard = `BEGIN:VCARD VERSION:4.0 FN;PREF=1:J. Doe UID:urn:uuid:4fbe8971-0bc3-424c-9c26-36c3e1eff6b1 ITEM1.EMAIL;PREF=1:[email protected] END:VCARD`; const vCardContact = parseToVCard(vcard) as RequireSome<VCardContact, 'email'>; const saveRequestSpy = jest.fn(); api.mockImplementation(async (args: any): Promise<any> => { if (args.url === 'core/v4/keys/all') { return { Address: { Keys: [ { PublicKey: 'internal mocked armored key', Flags: KEY_FLAG.FLAG_EMAIL_NO_ENCRYPT | KEY_FLAG.FLAG_NOT_COMPROMISED, }, ], }, Unverified: { Keys: [{ PublicKey: 'wkd mocked armored key', Flags: KEY_FLAG.FLAG_NOT_COMPROMISED }], }, ProtonMX: false, // external account }; } if (args.url === 'contacts/v4/contacts') { saveRequestSpy(args.data); return { Responses: [{ Response: { Code: API_CODES.SINGLE_SUCCESS } }] }; } if (args.url === 'contacts/v4/contacts/ContactID') { saveRequestSpy(args.data); return { Code: API_CODES.SINGLE_SUCCESS }; } }); const { getByText, getByTitle, queryByText } = render( <ContactEmailSettingsModal open={true} {...props} vCardContact={vCardContact} emailProperty={vCardContact.email?.[0]} /> ); const showMoreButton = getByText('Show advanced PGP settings'); await waitFor(() => expect(showMoreButton).not.toBeDisabled()); fireEvent.click(showMoreButton); await waitFor(() => { const internalAddressKeyFingerprint = queryByText('internal mocked armored key'); return expect(internalAddressKeyFingerprint).toBeNull(); }); await waitFor(() => { const wkdKeyFingerprint = getByText('wkd mocked armored key'); return expect(wkdKeyFingerprint).toBeVisible(); }); const infoEncryptionDisabled = queryByText(/The owner of this address has disabled end-to-end encryption/); expect(infoEncryptionDisabled).toBeNull(); // only shown to internal accounts // Ensure the UI matches that of external recipients with WKD keys: // - encryption should be enabled by default, and toggable // - key uploads are not permitted // - key pinning works stores the X-PM-ENCRYPT flag const encryptToggle = document.getElementById('encrypt-toggle'); expect(encryptToggle).not.toBeDisabled(); expect(encryptToggle).toBeChecked(); const signSelectDropdown = document.getElementById('sign-select'); expect(signSelectDropdown).toBeDisabled(); signSelectDropdown?.innerHTML.includes('Sign'); expect(queryByText('Upload keys')).toBeNull(); const dropdownButton = getByTitle('Open actions dropdown'); fireEvent.click(dropdownButton); const trustKeyButton = getByText('Trust'); fireEvent.click(trustKeyButton); const saveButton = getByText('Save'); fireEvent.click(saveButton); await waitFor(() => expect(notificationManager.createNotification).toHaveBeenCalled()); const sentData = saveRequestSpy.mock.calls[0][0]; const cards = sentData.Cards; const signedCardContent = cards.find( ({ Type }: { Type: CONTACT_CARD_TYPE }) => Type === CONTACT_CARD_TYPE.SIGNED ).Data; expect(signedCardContent.includes('ITEM1.KEY;PREF=1:data:application/pgp-keys')).toBe(true); expect(signedCardContent.includes('ITEM1.X-PM-ENCRYPT:true')).toBe(true); expect(signedCardContent.includes('ITEM1.X-PM-SIGN:true')).toBe(true); }); });
6,038
0
petrpan-code/ProtonMail/WebClients/packages/components/containers/contacts
petrpan-code/ProtonMail/WebClients/packages/components/containers/contacts/group/ContactGroupDetailsModal.test.tsx
import { LABEL_TYPE } from '@proton/shared/lib/constants'; import { ContactEmail, ContactGroup } from '@proton/shared/lib/interfaces/contacts'; import { STATUS } from '@proton/shared/lib/models/cache'; import { cache, clearAll, minimalCache, render } from '../tests/render'; import ContactGroupDetailsModal, { ContactGroupDetailsProps } from './ContactGroupDetailsModal'; describe('ContactGroupDetailsModal', () => { const props: ContactGroupDetailsProps = { contactGroupID: 'ContactGroupID', onEdit: jest.fn(), onDelete: jest.fn(), onExport: jest.fn(), onUpgrade: jest.fn(), }; const group: ContactGroup = { ID: 'ContactGroupID', Name: 'GroupName', Color: 'GroupColor', Path: '/ContactGroupID', Display: 1, Exclusive: 1, Notify: 1, Order: 1, Type: LABEL_TYPE.CONTACT_GROUP, }; const contactEmail1: ContactEmail = { ID: 'ContactEmail1', Email: '[email protected]', Name: 'email1', Type: [], Defaults: 1, Order: 1, ContactID: 'ContactID', LabelIDs: ['ContactGroupID'], LastUsedTime: 1, }; const contactEmail2: ContactEmail = { ...contactEmail1, ID: 'ContactEmail2', Email: '[email protected]', Name: 'email2', }; const contactEmail3: ContactEmail = { ...contactEmail1, ID: 'ContactEmail3', Email: '[email protected]', Name: 'email3', }; beforeEach(clearAll); it('should display a contact group', async () => { minimalCache(); cache.set('Labels', { status: STATUS.RESOLVED, value: [group] }); cache.set('ContactEmails', { status: STATUS.RESOLVED, value: [contactEmail1, contactEmail2, contactEmail3] }); const { getByText } = render(<ContactGroupDetailsModal open={true} {...props} />, false); getByText(group.Name); getByText('3 email addresses'); getByText(contactEmail1.Name); getByText(contactEmail2.Name); getByText(contactEmail3.Name); }); });
6,040
0
petrpan-code/ProtonMail/WebClients/packages/components/containers/contacts
petrpan-code/ProtonMail/WebClients/packages/components/containers/contacts/group/ContactGroupEditModal.test.tsx
import { fireEvent, getByDisplayValue, waitFor } from '@testing-library/react'; import { CryptoProxy } from '@proton/crypto'; import { ACCENT_COLORS } from '@proton/shared/lib/colors'; import { LABEL_TYPE } from '@proton/shared/lib/constants'; import { ContactEmail, ContactGroup } from '@proton/shared/lib/interfaces/contacts'; import { MAX_RECIPIENTS } from '@proton/shared/lib/mail/mailSettings'; import { STATUS } from '@proton/shared/lib/models/cache'; import { api, cache, clearAll, getCard, minimalCache, mockedCryptoApi, render } from '../tests/render'; import ContactGroupEditModal, { ContactGroupEditProps } from './ContactGroupEditModal'; describe('ContactGroupEditModal', () => { const props: ContactGroupEditProps = { contactGroupID: 'ContactGroupID', selectedContactEmails: [], onDelayedSave: jest.fn(), }; const group: ContactGroup = { ID: 'ContactGroupID', Name: 'GroupName', Color: 'GroupColor', Path: '/ContactGroupID', Display: 1, Exclusive: 1, Notify: 1, Order: 1, Type: LABEL_TYPE.CONTACT_GROUP, }; const contactEmail1: ContactEmail = { ID: 'ContactEmail1', Email: '[email protected]', Name: 'email1', Type: [], Defaults: 1, Order: 1, ContactID: 'ContactID', LabelIDs: ['ContactGroupID'], LastUsedTime: 1, }; const contactEmail2: ContactEmail = { ...contactEmail1, ID: 'ContactEmail2', Email: '[email protected]', Name: 'email2', }; const contactEmail3: ContactEmail = { ...contactEmail1, ID: 'ContactEmail3', Email: '[email protected]', Name: 'email3', }; beforeAll(() => { CryptoProxy.setEndpoint(mockedCryptoApi); }); beforeEach(clearAll); afterAll(async () => { await CryptoProxy.releaseEndpoint(); }); it('should display a contact group', async () => { minimalCache(); cache.set('Labels', { status: STATUS.RESOLVED, value: [group] }); cache.set('ContactEmails', { status: STATUS.RESOLVED, value: [contactEmail1, contactEmail2, contactEmail3] }); cache.set('MailSettings', { RecipientLimit: MAX_RECIPIENTS }); const updateSpy = jest.fn(); const createContactSpy = jest.fn(); const labelSpy = jest.fn(); const unlabelSpy = jest.fn(); api.mockImplementation(async (args: any): Promise<any> => { if (args.url === `core/v4/labels/${group.ID}`) { updateSpy(args.data); return { Label: { ID: group.ID } }; } if (args.url === 'contacts/v4/contacts') { createContactSpy(args.data); return {}; } if (args.url === 'contacts/v4/contacts/emails/label') { labelSpy(args.data); return {}; } if (args.url === 'contacts/v4/contacts/emails/unlabel') { unlabelSpy(args.data); return {}; } }); const { getByTestId, getByText, getAllByText } = render( <ContactGroupEditModal open={true} {...props} />, false ); const name = document.getElementById('contactGroupName') as HTMLElement; fireEvent.change(name, { target: { value: 'NewName' } }); const colorDropdown = getByTestId('dropdown-button'); fireEvent.click(colorDropdown); const colorButton = document.getElementById('contactGroupColor') as HTMLElement; fireEvent.click(colorButton); const colorRadio = getByDisplayValue(document.body, ACCENT_COLORS[0]); fireEvent.click(colorRadio); const removeButtons = getAllByText('Remove'); fireEvent.click(removeButtons[2]); const email = document.getElementById('contactGroupEmail') as HTMLElement; fireEvent.change(email, { target: { value: '[email protected]' } }); const addButton = getByText('Add'); fireEvent.click(addButton); const saveButton = getByText('Save'); fireEvent.click(saveButton); await waitFor(() => { expect(updateSpy).toHaveBeenCalled(); }); await waitFor(() => { expect(createContactSpy).toHaveBeenCalled(); }); await waitFor(() => { expect(labelSpy).toHaveBeenCalled(); }); await waitFor(() => { expect(unlabelSpy).toHaveBeenCalled(); }); const updateData = updateSpy.mock.calls[0][0]; expect(updateData.Name).toBe('NewName'); expect(updateData.Color).toBe(ACCENT_COLORS[0]); const createContactData = createContactSpy.mock.calls[0][0]; const cards = createContactData.Contacts[0].Cards; const signed = getCard(cards); expect(signed).toContain('ITEM1.EMAIL;PREF=1:[email protected]'); const labelData = labelSpy.mock.calls[0][0]; expect(labelData.ContactEmailIDs).toEqual([contactEmail1.ID, contactEmail2.ID]); const unlabelData = unlabelSpy.mock.calls[0][0]; expect(unlabelData.ContactEmailIDs).toEqual([contactEmail3.ID]); }); });
6,055
0
petrpan-code/ProtonMail/WebClients/packages/components/containers/contacts
petrpan-code/ProtonMail/WebClients/packages/components/containers/contacts/import/ContactImportModal.test.tsx
import { fireEvent, waitFor } from '@testing-library/react'; import { CryptoProxy } from '@proton/crypto'; import { API_CODES } from '@proton/shared/lib/constants'; import range from '@proton/utils/range'; import { api, clearAll, getCard, mockedCryptoApi, render } from '../tests/render'; import ContactImportModal from './ContactImportModal'; jest.mock('../../../hooks/useFeature', () => () => ({ feature: {}, update: jest.fn() })); describe('ContactImportModal', () => { beforeAll(() => { CryptoProxy.setEndpoint(mockedCryptoApi); }); beforeEach(clearAll); afterAll(async () => { await CryptoProxy.releaseEndpoint(); }); it('should succeed to import a simple CSV file', async () => { const csv = `first name,last name,email-address ,nickname,organization,birthday,home phone,work phone,mobile phone,city,state,zip,country,Job title,personal web page,business website,group membership,Timezone,notes,home John,Smith,[email protected],,Smith Inc.,,123-456-789,,,New Orleans,LA,94958,USA,Head honcho,,,,GMT-7,, Jane,Doe,[email protected],,Example UK,,,(44)12345678,(44)12345678,Brighton,East Sussex,BR7 7HT,UK,,www.customdomain.com,,Brighton kite Flyers,GMT,Likes to party!, Peter,Rabbit,[email protected],Carrot,,03/12/1969,856-264-4130,123-456-789,123-456-789,Bridgeport,NJ,8014,USA,,,www.customdomain.com,,GMT-4,, Botman,,[email protected],,,,,,,Skopje,,,,,,,,,,Partizanska`; const file = new File([csv], 'test.csv', { type: 'text/csv' }); const saveRequestSpy = jest.fn(); const Responses = range(0, 4).map((i) => ({ Index: 0, Response: { Code: API_CODES.SINGLE_SUCCESS, Contact: { ID: `ContactID${i}`, ContactEmails: [] } }, })); api.mockImplementation(async (args: any): Promise<any> => { if (args.url === 'contacts/v4/contacts') { saveRequestSpy(args.data); return { Responses }; } }); const { getByText } = render(<ContactImportModal open={true} />); const input = document.querySelector('input[type="file"]') as HTMLInputElement; fireEvent.change(input, { target: { files: [file] } }); let importButton = getByText('Import', { selector: 'button' }); fireEvent.click(importButton); await waitFor(() => getByText('We have detected', { exact: false })); importButton = getByText('Import', { selector: 'button' }); fireEvent.click(importButton); await waitFor(() => getByText('4/4', { exact: false })); const sentData = saveRequestSpy.mock.calls[0][0]; const contact0Cards = sentData.Contacts[0].Cards; const signed0 = getCard(contact0Cards, false); expect(signed0).toContain('FN;PREF=1:John Smith'); expect(signed0).toContain('ITEM1.EMAIL;TYPE=;PREF=1:[email protected]'); const encrypted0 = getCard(contact0Cards, true); expect(encrypted0).toContain('ADR;TYPE=;PREF=1:;;;New Orleans;LA;94958;USA'); expect(encrypted0).toContain('ORG:Smith Inc.'); expect(encrypted0).toContain('TEL;TYPE=home;PREF=1:123-456-789'); expect(encrypted0).toContain('TITLE:Head honcho'); expect(encrypted0).toContain('TZ:GMT-7'); const contact1Cards = sentData.Contacts[1].Cards; const signed1 = getCard(contact1Cards, false); expect(signed1).toContain('FN;PREF=1:Jane Doe'); expect(signed1).toContain('ITEM1.EMAIL;TYPE=;PREF=1:[email protected]'); const encrypted1 = getCard(contact1Cards, true); expect(encrypted1).toContain('ADR;TYPE=;PREF=1:;;;Brighton;East Sussex;BR7 7HT;UK'); expect(encrypted1).toContain('NOTE:Likes to party!'); expect(encrypted1).toContain('ORG:Example UK'); expect(encrypted1).toContain('TEL;TYPE=work;PREF=1:(44)12345678'); expect(encrypted1).toContain('TEL;TYPE=cell;PREF=2:(44)12345678'); expect(encrypted1).toContain('URL:www.customdomain.com'); expect(encrypted1).toContain('TZ:GMT'); const contact2Cards = sentData.Contacts[2].Cards; const signed2 = getCard(contact2Cards, false); expect(signed2).toContain('FN;PREF=1:Peter Rabbit'); expect(signed2).toContain('ITEM1.EMAIL;TYPE=;PREF=1:[email protected]'); const encrypted2 = getCard(contact2Cards, true); expect(encrypted2).toContain('ADR;TYPE=;PREF=1:;;;Bridgeport;NJ;8014;USA'); expect(encrypted2).toContain('NOTE:nickname: Carrot'); expect(encrypted2).toContain('BDAY:19690312'); expect(encrypted2).toContain('TEL;TYPE=home;PREF=1:856-264-4130'); expect(encrypted2).toContain('TEL;TYPE=work;PREF=2:123-456-789'); expect(encrypted2).toContain('TEL;TYPE=cell;PREF=3:123-456-789'); expect(encrypted2).toContain('URL:www.customdomain.com'); expect(encrypted2).toContain('TZ:GMT-4'); const contact3Cards = sentData.Contacts[3].Cards; const signed3 = getCard(contact3Cards, false); expect(signed3).toContain('FN;PREF=1:Botman'); expect(signed3).toContain('ITEM1.EMAIL;TYPE=;PREF=1:[email protected]'); const encrypted3 = getCard(contact3Cards, true); expect(encrypted3).toContain('ADR;TYPE=;PREF=1:;;;Skopje;;;'); expect(encrypted3).toContain('NOTE:home: Partizanska'); }); });
6,082
0
petrpan-code/ProtonMail/WebClients/packages/components/containers/contacts
petrpan-code/ProtonMail/WebClients/packages/components/containers/contacts/merge/ContactMergingContent.test.tsx
import { render, waitFor } from '@testing-library/react'; import { prepareVCardContact } from '@proton/shared/lib/contacts/encrypt'; import useApi from '../../../hooks/useApi'; import ContactMergingContent from './ContactMergingContent'; const encrypt = prepareVCardContact as jest.Mock; jest.mock('../../../hooks/useApi', () => { const apiMock = jest.fn(({ url, method }) => { if (method === 'get') { const parts = url.split('/'); return Promise.resolve({ Contact: { ID: parts[parts.length - 1] } }); } if (method === 'post') { return Promise.resolve({ Responses: [{ Response: { Code: 1000, Contact: { ID: 'id1' } } }] }); } if (method === 'put') { return Promise.resolve(); } }); return () => apiMock; }); jest.mock('../../../hooks/useUserKeys', () => { return { useUserKeys: () => [[]], }; }); jest.mock('@proton/shared/lib/contacts/decrypt', () => { return { prepareVCardContact: jest.fn(({ ID }) => { return Promise.resolve({ vCardContact: { nickname: [{ field: 'nickname', value: ID }] }, errors: [] }); }), }; }); jest.mock('@proton/shared/lib/contacts/encrypt', () => { return { prepareVCardContact: jest.fn(() => { return Promise.resolve({ Cards: ['something encrypted'] }); }), }; }); window.ResizeObserver = window.ResizeObserver || jest.fn().mockImplementation(() => ({ disconnect: jest.fn(), observe: jest.fn(), unobserve: jest.fn(), })); describe('ContactMergingContent', () => { const id1 = 'id1'; const id2 = 'id2'; it('should perform a simple merge', async () => { render( <ContactMergingContent // userKeysList={[]} mergeFinished={false} beMergedModel={{ [id1]: [id1, id2] }} beDeletedModel={{}} totalBeMerged={1} totalBeDeleted={1} onFinish={jest.fn()} /> ); const apiMock = useApi() as jest.Mock; await waitFor(() => { expect(apiMock).toHaveBeenCalledTimes(4); // 2 gets, 1 update, 1 delete }); const encryptedProps = encrypt.mock.calls[0][0]; expect(encryptedProps.nickname[0].field).toBe('nickname'); expect(encryptedProps.nickname[0].value).toBe(id1); expect(encryptedProps.nickname[1].field).toBe('nickname'); expect(encryptedProps.nickname[1].value).toBe(id2); const updateCall = apiMock.mock.calls[2]; expect(updateCall[0].data.Contacts[0].Cards[0]).toBe('something encrypted'); const deleteCall = apiMock.mock.calls[3]; expect(deleteCall[0].data.IDs).toEqual([id2]); }); });
6,093
0
petrpan-code/ProtonMail/WebClients/packages/components/containers/contacts
petrpan-code/ProtonMail/WebClients/packages/components/containers/contacts/modals/ContactExportingModal.test.tsx
import { fireEvent } from '@testing-library/react'; import { CryptoProxy } from '@proton/crypto'; import downloadFile from '@proton/shared/lib/helpers/downloadFile'; import { STATUS } from '@proton/shared/lib/models/cache'; import { api, cache, clearAll, minimalCache, mockedCryptoApi, prepareContact, render } from '../tests/render'; import ContactExportingModal, { ContactExportingProps } from './ContactExportingModal'; jest.mock('@proton/shared/lib/helpers/downloadFile', () => { return jest.fn(); }); describe('ContactExportingModal', () => { const props: ContactExportingProps = { contactGroupID: 'contactGroupID', onSave: jest.fn(), }; const contact1 = { ID: 'ContactID1', LabelIDs: [props.contactGroupID], }; const vcard1 = `BEGIN:VCARD VERSION:4.0 UID:urn:uuid:4fbe8971-0bc3-424c-9c26-36c3e1eff6b1 FN:J. Doe EMAIL:[email protected] TEL:testtel END:VCARD`; const contact2 = { ID: 'ContactID2', LabelIDs: [props.contactGroupID], }; const vcard2 = `BEGIN:VCARD VERSION:4.0 UID:urn:uuid:4fbe8971-0bc3-424c-9c26-36c3e1eff6b2 FN:Jane Doe EMAIL:[email protected] TEL:testteltt END:VCARD`; beforeAll(() => { CryptoProxy.setEndpoint(mockedCryptoApi); }); beforeEach(clearAll); afterAll(async () => { await CryptoProxy.releaseEndpoint(); }); it('should export two contacts', async () => { const { Cards: Cards1 } = await prepareContact(vcard1); const { Cards: Cards2 } = await prepareContact(vcard2); api.mockImplementation(async (args: any): Promise<any> => { if (args.url === 'contacts/v4/contacts/export') { return { Contacts: [ { ID: contact1.ID, Cards: Cards1 }, { ID: contact2.ID, Cards: Cards2 }, ], }; } }); minimalCache(); cache.set('Contacts', { status: STATUS.RESOLVED, value: [contact1, contact2] }); const { findByText, getByText } = render(<ContactExportingModal open={true} {...props} />, false); await findByText('2 out of 2', { exact: false }); const saveButton = getByText('Save'); fireEvent.click(saveButton); expect(downloadFile).toHaveBeenCalled(); const args = (downloadFile as jest.Mock).mock.calls[0]; const blob = args[0] as Blob; const content = await new Promise((resolve) => { var reader = new FileReader(); reader.onload = () => resolve(reader.result); reader.readAsText(blob); }); const expected = `BEGIN:VCARD\r\nVERSION:4.0\r\nFN;PREF=1:J. Doe\r\nTEL;PREF=1:testtel\r\nUID:urn:uuid:4fbe8971-0bc3-424c-9c26-36c3e1eff6b1\r\nITEM1.EMAIL;PREF=1:[email protected]\r\nEND:VCARD\r\nBEGIN:VCARD\r\nVERSION:4.0\r\nFN;PREF=1:Jane Doe\r\nTEL;PREF=1:testteltt\r\nUID:urn:uuid:4fbe8971-0bc3-424c-9c26-36c3e1eff6b2\r\nITEM1.EMAIL;PREF=1:[email protected]\r\nEND:VCARD`; expect(content).toBe(expected); }); });
6,108
0
petrpan-code/ProtonMail/WebClients/packages/components/containers/contacts
petrpan-code/ProtonMail/WebClients/packages/components/containers/contacts/view/ContactDetailsModal.test.tsx
import { CryptoProxy } from '@proton/crypto'; import { SHOW_IMAGES } from '@proton/shared/lib/mail/mailSettings'; import { addToCache, api, clearAll, minimalCache, mockedCryptoApi, prepareContact, render } from '../tests/render'; import ContactDetailsModal, { ContactDetailsProps } from './ContactDetailsModal'; jest.mock('../../../hooks/useConfig', () => () => ({ API_URL: 'api' })); describe('ContactDetailsModal', () => { const props: ContactDetailsProps = { contactID: 'ContactID', onEdit: jest.fn(), onDelete: jest.fn(), onMailTo: jest.fn(), onEmailSettings: jest.fn(), onGroupDetails: jest.fn(), onGroupEdit: jest.fn(), onUpgrade: jest.fn(), onDecryptionError: jest.fn(), onSignatureError: jest.fn(), }; beforeAll(() => { CryptoProxy.setEndpoint(mockedCryptoApi); }); beforeEach(clearAll); afterAll(async () => { await CryptoProxy.releaseEndpoint(); }); it('should show basic contact informations', async () => { const vcard = `BEGIN:VCARD VERSION:4.0 UID:urn:uuid:4fbe8971-0bc3-424c-9c26-36c3e1eff6b1 FN:J. Doe FN:FN2 EMAIL:[email protected] NOTE:TestNote ADR:1;2;3;4;5;6;7 ADR:;;;;;;testadr TEL:testtel PHOTO:https://example.com/myphoto.jpg END:VCARD`; const { Cards } = await prepareContact(vcard); api.mockImplementation(async (args: any): Promise<any> => { if (args.url === 'contacts/v4/contacts/ContactID') { return { Contact: { ID: 'ID', ContactID: 'ContactID', Cards } }; } }); minimalCache(); addToCache('MailSettings', { HideRemoteImages: SHOW_IMAGES.HIDE }); const { findByText } = render(<ContactDetailsModal open={true} {...props} />, false); await findByText('J. Doe'); await findByText('Load image'); await findByText('FN2'); await findByText('[email protected]'); await findByText('testtel'); await findByText(/3.*2.*6, 4.*1.*5, 7/); await findByText('testadr'); await findByText('TestNote'); }); });
6,241
0
petrpan-code/ProtonMail/WebClients/packages/components/containers/filters
petrpan-code/ProtonMail/WebClients/packages/components/containers/filters/modal/useFilterConditions.test.ts
import { renderHook } from '@testing-library/react-hooks'; import { Condition } from '../interfaces'; import useFilterConditions from './useFilterConditions'; describe('useFilterConditions', () => { const condition = { id: 'test' } as Condition; const initialConditions = [condition]; const onChangeConditions = jest.fn(); it('should generate an initial condition', () => { const { result } = renderHook(() => useFilterConditions()); expect(result.current.conditions).toHaveLength(1); }); it('should handle initial conditions', () => { const { result } = renderHook(() => useFilterConditions(initialConditions)); expect(result.current.conditions).toEqual(initialConditions); }); it('should add a condition', () => { const { result } = renderHook(() => useFilterConditions(initialConditions, onChangeConditions)); result.current.onAddCondition(); expect(result.current.conditions).toHaveLength(2); expect(onChangeConditions).toHaveBeenCalled(); }); it('should delete a condition', () => { const { result } = renderHook(() => useFilterConditions(initialConditions, onChangeConditions)); result.current.onDeleteCondition(0); expect(result.current.conditions).toHaveLength(0); expect(onChangeConditions).toHaveBeenCalled(); }); it('should update a condition', () => { const { result } = renderHook(() => useFilterConditions(initialConditions, onChangeConditions)); result.current.onUpdateCondition(0, condition); expect(result.current.conditions).toEqual([condition]); expect(onChangeConditions).toHaveBeenCalled(); }); });
6,257
0
petrpan-code/ProtonMail/WebClients/packages/components/containers/filters/spams
petrpan-code/ProtonMail/WebClients/packages/components/containers/filters/spams/test/Spams.test.tsx
import React from 'react'; import { fireEvent, screen } from '@testing-library/react'; import userEvent from '@testing-library/user-event'; import { clearAll, render } from '@proton/components/containers/contacts/tests/render'; import Spams from '../Spams'; import SpamModal from '../modals/SpamModal'; describe('Spams - Incoming defaults', () => { afterEach(() => { clearAll(); }); it('Should display an empty list', () => { render(<Spams />); expect(screen.getByRole('button', { name: 'Add address or domain' })).toBeInTheDocument(); expect(screen.queryByRole('table')).not.toBeInTheDocument(); }); it('Should display blocked email modal', async () => { render(<Spams />); fireEvent.click(screen.getByRole('button', { name: 'Add address or domain' })); fireEvent.click(screen.getByRole('button', { name: 'Block' })); const modal = await screen.findByTestId('spam-modal'); expect(modal).toHaveTextContent('Add to block list'); }); it('Should display blocked email modal with organization', async () => { render(<Spams isOrganization />); fireEvent.click(screen.getByRole('button', { name: 'Add address or domain' })); fireEvent.click(screen.getByRole('button', { name: 'Block' })); const modal = await screen.findByTestId('spam-modal'); expect(modal).toHaveTextContent('Add to block list'); }); it('Modal submission should return correct values', async () => { const mockedSubmit = jest.fn(); const EMAIL = '[email protected]'; render( <SpamModal modalProps={{ open: true, }} type="SPAM" onAdd={mockedSubmit} /> ); const emailInputs = screen.getAllByLabelText('Email'); const emailRadio = emailInputs[0]; const emailInput = emailInputs[1]; await userEvent.click(emailRadio); expect(emailRadio).toBeChecked(); await userEvent.type(emailInput, EMAIL); // Dom actually got 2 button called "add address" at this moment. The submit one is the second const submitButton = screen.getByRole('button', { name: 'Add address' }); await userEvent.click(submitButton); const submitCalls = mockedSubmit.mock.calls.length; const submitCallsMode = mockedSubmit.mock.calls[0][0]; const submitCallsEmail = mockedSubmit.mock.calls[0][1]; expect(submitCalls).toBe(1); expect(submitCallsMode).toBe('email'); expect(submitCallsEmail).toBe(EMAIL); }); });
6,285
0
petrpan-code/ProtonMail/WebClients/packages/components/containers
petrpan-code/ProtonMail/WebClients/packages/components/containers/forward/helpers.test.ts
import { ForwardingType, OutgoingAddressForwarding } from '@proton/shared/lib/interfaces'; import { isLastOutgoingNonE2EEForwarding } from './helpers'; describe('isLastOutgoingNonE2EEForwarding', () => { describe('when forward is encrypted', () => { it('should return false', () => { const forward = { Type: ForwardingType.InternalEncrypted } as OutgoingAddressForwarding; const forwarding = [forward]; const result = isLastOutgoingNonE2EEForwarding(forward, forwarding); expect(result).toBeFalsy(); }); }); describe('when there is multiple external outgoing setup', () => { it('should return false', () => { const forward = { ForwarderAddressID: 'ForwarderAddressID', Type: ForwardingType.ExternalUnencrypted, } as OutgoingAddressForwarding; const forwarding = [forward, forward]; const result = isLastOutgoingNonE2EEForwarding(forward, forwarding); expect(result).toBeFalsy(); }); }); describe('when it is the latest external outgoing setup', () => { it('should return true', () => { const forward = { ForwarderAddressID: 'ForwarderAddressID', Type: ForwardingType.ExternalUnencrypted, } as OutgoingAddressForwarding; const internalForwarding = { ForwarderAddressID: 'ForwarderAddressID', Type: ForwardingType.ExternalEncrypted, } as OutgoingAddressForwarding; const forwarding = [forward, internalForwarding]; const result = isLastOutgoingNonE2EEForwarding(forward, forwarding); expect(result).toBeTruthy(); }); }); });
6,319
0
petrpan-code/ProtonMail/WebClients/packages/components/containers
petrpan-code/ProtonMail/WebClients/packages/components/containers/invoices/InvoicesSection.test.tsx
import { render } from '@testing-library/react'; import { useSubscribeEventManager } from '../../hooks'; import InvoicesSection from './InvoicesSection'; jest.mock('../../hooks/useHandler', () => { return { __esModule: true, ...jest.requireActual('../../hooks/useHandler'), useSubscribeEventManager: jest.fn(), }; }); let requestMock: jest.Mock; jest.mock('../../hooks/useApiResult', () => { let request = jest.fn(); requestMock = request; return { __esModule: true, ...jest.requireActual('../../hooks/useApiResult'), default: jest.fn().mockReturnValue({ request, }), }; }); jest.mock('../../hooks/useUser', () => { return { __esModule: true, default: jest.fn().mockReturnValue([ { isPaid: false, }, ]), }; }); jest.mock('../../hooks/useSubscription', () => { return { __esModule: true, default: jest.fn().mockReturnValue([]), }; }); jest.mock('../../hooks/useModals', () => { return { __esModule: true, default: jest.fn().mockReturnValue({ createModal: jest.fn(), }), }; }); describe('InvoicesSection', () => { let useSubscribeEventManagerMock: jest.Mock; beforeAll(() => { useSubscribeEventManagerMock = useSubscribeEventManager as jest.Mock; }); beforeEach(() => { requestMock.mockReset(); useSubscribeEventManagerMock.mockReset(); }); it('should request the list of invoices again when there is an Invoices event', () => { render(<InvoicesSection />); expect(useSubscribeEventManagerMock).toHaveBeenCalledTimes(1); let [callback] = useSubscribeEventManagerMock.mock.lastCall; callback({ Invoices: [{ ID: '123' }], }); expect(requestMock).toHaveBeenCalledTimes(1); }); it('should not request invoices if the Invoices array is empty', () => { render(<InvoicesSection />); expect(useSubscribeEventManagerMock).toHaveBeenCalledTimes(1); let [callback] = useSubscribeEventManagerMock.mock.lastCall; callback({ Invoices: [], }); expect(requestMock).toHaveBeenCalledTimes(0); }); it('should not request invoices if the Invoices are not there ', () => { render(<InvoicesSection />); let useSubscribeEventManagerMock = useSubscribeEventManager as jest.Mock; expect(useSubscribeEventManagerMock).toHaveBeenCalledTimes(1); let [callback] = useSubscribeEventManagerMock.mock.lastCall; callback({}); expect(requestMock).toHaveBeenCalledTimes(0); }); it('should not request invoices if the callback does not have an argument', () => { render(<InvoicesSection />); let useSubscribeEventManagerMock = useSubscribeEventManager as jest.Mock; expect(useSubscribeEventManagerMock).toHaveBeenCalledTimes(1); let [callback] = useSubscribeEventManagerMock.mock.lastCall; callback(); expect(requestMock).toHaveBeenCalledTimes(0); }); });
6,378
0
petrpan-code/ProtonMail/WebClients/packages/components/containers/keys
petrpan-code/ProtonMail/WebClients/packages/components/containers/keys/shared/getPermissions.test.ts
import getPermissions from './getPermissions'; describe('getPermissions', () => { describe('when isForwarding is true', () => { it('should return the correct permissions', () => { const permissions = getPermissions({ canModify: false, isDecrypted: false, isAddressDisabled: false, isCompromised: false, isObsolete: false, canEncryptAndSign: false, isAddressKey: false, isPrimary: false, hasUserPermission: false, isForwarding: true, canDeleteForwarding: true, isLoading: false, isWeak: false, }); expect(permissions).toEqual({ canExportPublicKey: false, canExportPrivateKey: false, canSetPrimary: false, canSetObsolete: false, canSetNotObsolete: false, canSetCompromised: false, canSetNotCompromised: false, canDelete: true, }); }); }); describe('when isForwarding is false', () => { it('should return the correct permissions', () => { const permissions = getPermissions({ canModify: true, isDecrypted: true, isAddressDisabled: false, isCompromised: false, isObsolete: false, canEncryptAndSign: true, isAddressKey: true, isPrimary: false, hasUserPermission: true, isForwarding: false, canDeleteForwarding: true, isLoading: false, isWeak: false, }); expect(permissions).toEqual({ canExportPublicKey: true, canExportPrivateKey: true, canSetPrimary: true, canSetObsolete: true, canSetNotObsolete: false, canSetCompromised: true, canSetNotCompromised: false, canDelete: true, }); }); }); });
6,468
0
petrpan-code/ProtonMail/WebClients/packages/components/containers/members
petrpan-code/ProtonMail/WebClients/packages/components/containers/members/multipleUserCreation/csv.test.ts
import { BASE_SIZE, GIGA } from '@proton/shared/lib/constants'; import { UserManagementMode } from '../types'; import { getSampleCSV, getVpnB2BSampleCSV, parseMultiUserCsv } from './csv'; import { CSV_CONVERSION_ERROR_TYPE } from './errors/CsvConversionError'; import { ExportedCSVUser, ExportedVpnB2BCSVUser } from './types'; describe('multi user upload csv.ts', () => { const defaultFileName = 'filename'; const getFile = (fileContent: string, filename: string = defaultFileName) => { const blob = new Blob([fileContent]); return new File([blob], filename); }; describe('parseMultiUserCsv (default)', () => { const defaultUser: ExportedCSVUser = { DisplayName: 'Alice', EmailAddresses: '[email protected]', Password: 'alice_password', TotalStorage: GIGA, VPNAccess: 1, PrivateSubUser: 0, }; const defaultCsvFields = `DisplayName,EmailAddresses,Password,TotalStorage,VPNAccess,PrivateSubUser`; const mode = UserManagementMode.DEFAULT; describe('errors', () => { it('throws error if no files are passed', async () => { await expect(parseMultiUserCsv([], mode)).rejects.toThrow( 'An error occurred uploading your file. No file has been selected.' ); }); it('throws error if file is empty', async () => { const filename = 'filename'; const file = new File([], filename); await expect(parseMultiUserCsv([file], mode)).rejects.toThrow('Your file "filename" is empty.'); }); it('throws error if file is > 10MB', async () => { const file = getFile(getSampleCSV([defaultUser])); /** * Mock large file size */ Object.defineProperty(file, 'size', { value: 10 * BASE_SIZE ** 2 + 1 }); await expect(parseMultiUserCsv([file], mode)).rejects.toThrow( 'An error occurred uploading your file "filename". Maximum file size is 10 MB.' ); }); it('does not throw error if file is <= 10MB', async () => { const file = getFile(getSampleCSV([defaultUser])); /** * Mock ok file size */ Object.defineProperty(file, 'size', { value: 10 * BASE_SIZE ** 2 }); await expect(parseMultiUserCsv([file], mode)).resolves.not.toThrow( 'An error occurred uploading your file "filename". Maximum file size is 10 MB.' ); }); it('throws error if there are > 750 rows', async () => { const rows = Array.from({ length: 751 }, () => defaultUser); const file = getFile(getSampleCSV(rows)); await expect(parseMultiUserCsv([file], mode)).rejects.toThrowError( 'Upload a CSV file with 750 user accounts or less.' ); }); it('does not throw error if there are <= 750 rows', async () => { const rows = Array.from({ length: 750 }, () => defaultUser); const file = getFile(getSampleCSV(rows)); await expect(parseMultiUserCsv([file], mode)).resolves.not.toThrowError( 'Upload a CSV file with 750 user accounts or less.' ); }); it('throws error if the EmailAddress field is not defined', async () => { const fileContent = ['Password', 'alice_password'].join('\n'); const file = getFile(fileContent); await expect(parseMultiUserCsv([file], mode)).rejects.toThrowError( `It looks like your file is missing the 'EmailAddresses' header.` ); }); it('throws error if the Password field is not defined', async () => { const fileContent = ['EmailAddresses', '[email protected]'].join('\n'); const file = getFile(fileContent); await expect(parseMultiUserCsv([file], mode)).rejects.toThrowError( `It looks like your file is missing the 'Password' header.` ); }); it('throws error if a row contains too few fields', async () => { const fileContent = [defaultCsvFields, '[email protected],alice_password,1073741824,1,0'].join('\n'); const file = getFile(fileContent); await expect(parseMultiUserCsv([file], mode)).rejects.toThrowError('Error on row 1.'); }); it('throws error if a row contains too many fields', async () => { const fileContent = [ defaultCsvFields, 'Alice,[email protected],alice_password,1073741824,1,0' + ',ExtraItem', ].join('\n'); const file = getFile(fileContent); await expect(parseMultiUserCsv([file], mode)).rejects.toThrowError('Error on row 1.'); }); }); describe('parsing', () => { it('parses the sample CSV with no errors', async () => { const file = getFile(getSampleCSV()); const result = await parseMultiUserCsv([file], mode); expect(result.errors.length).toBe(0); }); it('trims whitespace', async () => { const fileContent = [ ` DisplayName , EmailAddresses,Password ,TotalStorage , VPNAccess,PrivateSubUser `, /** * `Alice,"` must be of this form - it will parse incorrectly if there is a space before the `"" ie `Alice, "` */ ` Alice," [email protected] , [email protected] ",alice_password, 2 ,1 ,0 `, ].join('\n'); const file = getFile(fileContent); const result = await parseMultiUserCsv([file], mode); const user = result.users[0]; expect(result.errors.length).toBe(0); expect(user.id).toBe('1'); expect(user.displayName).toBe('Alice'); expect(user.emailAddresses.length).toBe(2); expect(user.emailAddresses[0]).toBe('[email protected]'); expect(user.emailAddresses[1]).toBe('[email protected]'); expect(user.password).toBe('alice_password'); expect(user.totalStorage).toBe(2 * GIGA); expect(user.vpnAccess).toBe(true); expect(user.privateSubUser).toBe(false); }); describe('id', () => { it('equals the row number', async () => { const fileContent = [ defaultCsvFields, `Alice,[email protected],alice_password,1073741824,1,0`, `Bob,[email protected],bob_password,1073741824,1,0`, `Charlie,[email protected],charlie_password,1073741824,1,0`, ].join('\n'); const file = getFile(fileContent); const result = await parseMultiUserCsv([file], mode); expect(result.errors.length).toBe(0); expect(result.users[0].id).toBe('1'); expect(result.users[1].id).toBe('2'); expect(result.users[2].id).toBe('3'); }); }); describe('displayName', () => { it('returns no errors if display name is a string', async () => { const displayName = 'Alice'; const fileContent = [ defaultCsvFields, `${displayName},[email protected],alice_password,1073741824,1,0`, ].join('\n'); const file = getFile(fileContent); const result = await parseMultiUserCsv([file], mode); const user = result.users[0]; expect(result.errors.length).toBe(0); expect(user.displayName).toBe('Alice'); }); it('defaults to first address if DisplayName is missing', async () => { const displayName = ''; const fileContent = [ defaultCsvFields, `${displayName},[email protected],alice_password,1073741824,1,0`, ].join('\n'); const file = getFile(fileContent); const result = await parseMultiUserCsv([file], mode); const user = result.users[0]; expect(result.errors.length).toBe(0); expect(user.displayName).toBe('[email protected]'); }); it('casts to a string', async () => { const displayName = 123; const fileContent = [ defaultCsvFields, `${displayName},[email protected],alice_password,1073741824,1,0`, ].join('\n'); const file = getFile(fileContent); const result = await parseMultiUserCsv([file], mode); const user = result.users[0]; expect(result.errors.length).toBe(0); expect(user.displayName).toBe('123'); }); }); describe('emailAddresses', () => { it('adds error if no email addresses are defined', async () => { const emailAddresses = ''; const fileContent = [ defaultCsvFields, `Alice,${emailAddresses},alice_password,1073741824,1,0`, ].join('\n'); const file = getFile(fileContent); const result = await parseMultiUserCsv([file], mode); expect(result.errors.length).toBe(1); expect(result.errors[0].rowNumber).toBe(1); expect(result.errors[0].type).toBe(CSV_CONVERSION_ERROR_TYPE.EMAIL_REQUIRED); }); it('returns no errors if emailAddresses is a string', async () => { const emailAddresses = '[email protected]'; const fileContent = [ defaultCsvFields, `Alice,${emailAddresses},alice_password,1073741824,1,0`, ].join('\n'); const file = getFile(fileContent); const result = await parseMultiUserCsv([file], mode); const user = result.users[0]; expect(result.errors.length).toBe(0); expect(user.emailAddresses.length).toBe(1); expect(user.emailAddresses[0]).toBe('[email protected]'); }); it('parses a list of email addresses', async () => { const emailAddresses = ['[email protected]', '[email protected]']; const fileContent = [ defaultCsvFields, `Alice,"${emailAddresses.join(',')}",alice_password,1073741824,1,0`, ].join('\n'); const file = getFile(fileContent); const result = await parseMultiUserCsv([file], mode); const user = result.users[0]; expect(result.errors.length).toBe(0); expect(user.emailAddresses.length).toBe(2); expect(user.emailAddresses[0]).toBe('[email protected]'); expect(user.emailAddresses[1]).toBe('[email protected]'); }); it('is considered to be defined if set to falsy 0 value', async () => { const emailAddresses = 0; const fileContent = [ defaultCsvFields, `Alice,${emailAddresses},alice_password,1073741824,1,0`, ].join('\n'); const file = getFile(fileContent); const result = await parseMultiUserCsv([file], mode); const user = result.users[0]; expect(result.errors.length).toBe(0); expect(user.emailAddresses.length).toBe(1); expect(user.emailAddresses[0]).toBe('0'); }); it('casts to a string', async () => { const emailAddresses = 123; const fileContent = [ defaultCsvFields, `Alice,${emailAddresses},alice_password,1073741824,1,0`, ].join('\n'); const file = getFile(fileContent); const result = await parseMultiUserCsv([file], mode); const user = result.users[0]; expect(result.errors.length).toBe(0); expect(user.emailAddresses.length).toBe(1); expect(user.emailAddresses[0]).toBe('123'); }); }); describe('password', () => { it('adds error if no password is defined', async () => { const password = ''; const fileContent = [defaultCsvFields, `Alice,[email protected],${password},1073741824,1,0`].join( '\n' ); const file = getFile(fileContent); const result = await parseMultiUserCsv([file], mode); expect(result.errors.length).toBe(1); expect(result.errors[0].rowNumber).toBe(1); expect(result.errors[0].type).toBe(CSV_CONVERSION_ERROR_TYPE.PASSWORD_REQUIRED); }); it('returns no errors if password is a string', async () => { const password = 'alice_password'; const fileContent = [defaultCsvFields, `Alice,[email protected],${password},1073741824,1,0`].join( '\n' ); const file = getFile(fileContent); const result = await parseMultiUserCsv([file], mode); const user = result.users[0]; expect(result.errors.length).toBe(0); expect(user.password).toBe('alice_password'); }); it('is considered to be defined if set to falsy 0 value', async () => { const password = 0; const fileContent = [defaultCsvFields, `Alice,[email protected],${password},1073741824,1,0`].join( '\n' ); const file = getFile(fileContent); const result = await parseMultiUserCsv([file], mode); const user = result.users[0]; expect(result.errors.length).toBe(0); expect(user.password).toBe(`0`); }); it('casts to a string', async () => { const password = 123; const fileContent = [defaultCsvFields, `Alice,[email protected],${password},1073741824,1,0`].join( '\n' ); const file = getFile(fileContent); const result = await parseMultiUserCsv([file], mode); const user = result.users[0]; expect(result.errors.length).toBe(0); expect(user.password).toBe(`123`); }); }); describe('totalStorage', () => { it('returns no errors if set to a valid number', async () => { const totalStorage = '123'; const fileContent = [ defaultCsvFields, `Alice,[email protected],alice_password,${totalStorage},1,0`, ].join('\n'); const file = getFile(fileContent); const result = await parseMultiUserCsv([file], mode); const user = result.users[0]; expect(result.errors.length).toBe(0); expect(user.totalStorage).toBe(123 * GIGA); }); it('uses default if value is not a valid number', async () => { const totalStorage = 'not a number'; const fileContent = [ defaultCsvFields, `Alice,[email protected],alice_password,${totalStorage},1,0`, ].join('\n'); const file = getFile(fileContent); const result = await parseMultiUserCsv([file], mode); const user = result.users[0]; expect(result.errors.length).toBe(0); expect(user.totalStorage).toBe(0); }); it('defaults to 0', async () => { const fileContent = ['EmailAddresses,Password', `[email protected],alice_password`].join('\n'); const file = getFile(fileContent); const result = await parseMultiUserCsv([file], mode); const user = result.users[0]; expect(result.errors.length).toBe(0); expect(user.totalStorage).toBe(0); }); it('allows decimal values', async () => { const totalStorage = 1.5; const fileContent = [ defaultCsvFields, `Alice,[email protected],alice_password,${totalStorage},1,0`, ].join('\n'); const file = getFile(fileContent); const result = await parseMultiUserCsv([file], mode); const user = result.users[0]; expect(result.errors.length).toBe(0); expect(user.totalStorage).toBe(1.5 * GIGA); }); }); describe('vpnAccess', () => { it('returns no errors if set to 0', async () => { const vpnAccess = 0; const fileContent = [ defaultCsvFields, `Alice,[email protected],alice_password,1073741824,${vpnAccess},0`, ].join('\n'); const file = getFile(fileContent); const result = await parseMultiUserCsv([file], mode); const user = result.users[0]; expect(result.errors.length).toBe(0); expect(user.vpnAccess).toBe(false); }); it('returns no errors if set to 1', async () => { const vpnAccess = 1; const fileContent = [ defaultCsvFields, `Alice,[email protected],alice_password,1073741824,${vpnAccess},0`, ].join('\n'); const file = getFile(fileContent); const result = await parseMultiUserCsv([file], mode); const user = result.users[0]; expect(result.errors.length).toBe(0); expect(user.vpnAccess).toBe(true); }); it('uses default if value is not a valid number', async () => { const vpnAccess = 'not a number'; const fileContent = [ defaultCsvFields, `Alice,[email protected],alice_password,1073741824,${vpnAccess},0`, ].join('\n'); const file = getFile(fileContent); const result = await parseMultiUserCsv([file], mode); const user = result.users[0]; expect(result.errors.length).toBe(0); expect(user.vpnAccess).toBe(false); }); it('defaults to false', async () => { const fileContent = ['EmailAddresses,Password', `[email protected],alice_password`].join('\n'); const file = getFile(fileContent); const result = await parseMultiUserCsv([file], mode); const user = result.users[0]; expect(result.errors.length).toBe(0); expect(user.vpnAccess).toBe(false); }); }); describe('privateSubUser', () => { it('returns no errors if set to 0', async () => { const privateSubUser = 0; const fileContent = [ defaultCsvFields, `Alice,[email protected],alice_password,1073741824,1,${privateSubUser}`, ].join('\n'); const file = getFile(fileContent); const result = await parseMultiUserCsv([file], mode); const user = result.users[0]; expect(result.errors.length).toBe(0); expect(user.privateSubUser).toBe(false); }); it('returns no errors if set to 1', async () => { const privateSubUser = 1; const fileContent = [ defaultCsvFields, `Alice,[email protected],alice_password,1073741824,1,${privateSubUser}`, ].join('\n'); const file = getFile(fileContent); const result = await parseMultiUserCsv([file], mode); const user = result.users[0]; expect(result.errors.length).toBe(0); expect(user.privateSubUser).toBe(true); }); it('uses default if value is not a valid number', async () => { const privateSubUser = 'not a number'; const fileContent = [ defaultCsvFields, `Alice,[email protected],alice_password,1073741824,1,${privateSubUser}`, ].join('\n'); const file = getFile(fileContent); const result = await parseMultiUserCsv([file], mode); const user = result.users[0]; expect(result.errors.length).toBe(0); expect(user.privateSubUser).toBe(false); }); it('defaults to false', async () => { const fileContent = ['EmailAddresses,Password', `[email protected],alice_password`].join('\n'); const file = getFile(fileContent); const result = await parseMultiUserCsv([file], mode); const user = result.users[0]; expect(result.errors.length).toBe(0); expect(user.privateSubUser).toBe(false); }); }); }); }); describe('parseMultiUserCsv (VPN B2B)', () => { const defaultUser: ExportedVpnB2BCSVUser = { Name: 'Alice', EmailAddress: '[email protected]', Password: 'alice_password', }; const mode = UserManagementMode.VPN_B2B; const defaultCsvFields = `Name,EmailAddress,Password`; describe('errors', () => { it('throws error if no files are passed', async () => { await expect(parseMultiUserCsv([], mode)).rejects.toThrow( 'An error occurred uploading your file. No file has been selected.' ); }); it('throws error if file is empty', async () => { const filename = 'filename'; const file = new File([], filename); await expect(parseMultiUserCsv([file], mode)).rejects.toThrow('Your file "filename" is empty.'); }); it('throws error if file is > 10MB', async () => { const file = getFile(getVpnB2BSampleCSV([defaultUser])); /** * Mock large file size */ Object.defineProperty(file, 'size', { value: 10 * BASE_SIZE ** 2 + 1 }); await expect(parseMultiUserCsv([file], mode)).rejects.toThrow( 'An error occurred uploading your file "filename". Maximum file size is 10 MB.' ); }); it('does not throw error if file is <= 10MB', async () => { const file = getFile(getVpnB2BSampleCSV([defaultUser])); /** * Mock ok file size */ Object.defineProperty(file, 'size', { value: 10 * BASE_SIZE ** 2 }); await expect(parseMultiUserCsv([file], mode)).resolves.not.toThrow( 'An error occurred uploading your file "filename". Maximum file size is 10 MB.' ); }); it('throws error if there are > 750 rows', async () => { const rows = Array.from({ length: 751 }, () => defaultUser); const file = getFile(getVpnB2BSampleCSV(rows)); await expect(parseMultiUserCsv([file], mode)).rejects.toThrowError( 'Upload a CSV file with 750 user accounts or less.' ); }); it('does not throw error if there are <= 750 rows', async () => { const rows = Array.from({ length: 750 }, () => defaultUser); const file = getFile(getVpnB2BSampleCSV(rows)); await expect(parseMultiUserCsv([file], mode)).resolves.not.toThrowError( 'Upload a CSV file with 750 user accounts or less.' ); }); it('throws error if the EmailAddress field is not defined', async () => { const fileContent = ['Password', 'alice_password'].join('\n'); const file = getFile(fileContent); await expect(parseMultiUserCsv([file], mode)).rejects.toThrowError( `It looks like your file is missing the 'EmailAddress' header.` ); }); it('throws error if the Password field is not defined', async () => { const fileContent = ['EmailAddress', '[email protected]'].join('\n'); const file = getFile(fileContent); await expect(parseMultiUserCsv([file], mode)).rejects.toThrowError( `It looks like your file is missing the 'Password' header.` ); }); it('throws error if a row contains too few fields', async () => { const fileContent = [defaultCsvFields, '[email protected],alice_password'].join('\n'); const file = getFile(fileContent); await expect(parseMultiUserCsv([file], mode)).rejects.toThrowError('Error on row 1.'); }); it('throws error if a row contains too many fields', async () => { const fileContent = [ defaultCsvFields, 'Alice,[email protected],alice_password,1073741824,1,0' + ',ExtraItem', ].join('\n'); const file = getFile(fileContent); await expect(parseMultiUserCsv([file], mode)).rejects.toThrowError('Error on row 1.'); }); }); describe('parsing', () => { it('parses the sample CSV with no errors', async () => { const file = getFile(getVpnB2BSampleCSV()); const result = await parseMultiUserCsv([file], mode); expect(result.errors.length).toBe(0); }); it('trims whitespace', async () => { const fileContent = [ ` Name , EmailAddress,Password `, /** * `Alice,"` must be of this form - it will parse incorrectly if there is a space before the `"" ie `Alice, "` */ ` Alice, [email protected] ,alice_password`, ].join('\n'); const file = getFile(fileContent); const result = await parseMultiUserCsv([file], mode); const user = result.users[0]; expect(result.errors.length).toBe(0); expect(user.id).toBe('1'); expect(user.displayName).toBe('Alice'); expect(user.emailAddresses.length).toBe(1); expect(user.emailAddresses[0]).toBe('[email protected]'); expect(user.password).toBe('alice_password'); }); describe('id', () => { it('equals the row number', async () => { const fileContent = [ defaultCsvFields, `Alice,[email protected],alice_password`, `Bob,[email protected],bob_password`, `Charlie,[email protected],charlie_password`, ].join('\n'); const file = getFile(fileContent); const result = await parseMultiUserCsv([file], mode); expect(result.errors.length).toBe(0); expect(result.users[0].id).toBe('1'); expect(result.users[1].id).toBe('2'); expect(result.users[2].id).toBe('3'); }); }); describe('name', () => { it('returns no errors if Name is a string', async () => { const name = 'Alice'; const fileContent = [defaultCsvFields, `${name},[email protected],alice_password`].join('\n'); const file = getFile(fileContent); const result = await parseMultiUserCsv([file], mode); const user = result.users[0]; expect(result.errors.length).toBe(0); expect(user.displayName).toBe('Alice'); }); it('defaults to address if Name is missing', async () => { const name = ''; const fileContent = [defaultCsvFields, `${name},[email protected],alice_password`].join('\n'); const file = getFile(fileContent); const result = await parseMultiUserCsv([file], mode); const user = result.users[0]; expect(result.errors.length).toBe(0); expect(user.displayName).toBe('[email protected]'); }); it('casts to a string', async () => { const name = 123; const fileContent = [defaultCsvFields, `${name},[email protected],alice_password`].join('\n'); const file = getFile(fileContent); const result = await parseMultiUserCsv([file], mode); const user = result.users[0]; expect(result.errors.length).toBe(0); expect(user.displayName).toBe('123'); }); }); describe('emailAddress', () => { it('adds error if no email addresses are defined', async () => { const emailAddress = ''; const fileContent = [defaultCsvFields, `Alice,${emailAddress},alice_password`].join('\n'); const file = getFile(fileContent); const result = await parseMultiUserCsv([file], mode); expect(result.errors.length).toBe(1); expect(result.errors[0].rowNumber).toBe(1); expect(result.errors[0].type).toBe(CSV_CONVERSION_ERROR_TYPE.EMAIL_REQUIRED); }); it('returns no errors if emailAddress is a string', async () => { const emailAddress = '[email protected]'; const fileContent = [defaultCsvFields, `Alice,${emailAddress},alice_password`].join('\n'); const file = getFile(fileContent); const result = await parseMultiUserCsv([file], mode); const user = result.users[0]; expect(result.errors.length).toBe(0); expect(user.emailAddresses.length).toBe(1); expect(user.emailAddresses[0]).toBe('[email protected]'); }); it('should throw error if email address is a list', async () => { const emailAddress = ['[email protected]', '[email protected]']; const fileContent = [defaultCsvFields, `Alice,"${emailAddress.join(',')}",alice_password`].join( '\n' ); const file = getFile(fileContent); const result = await parseMultiUserCsv([file], mode); expect(result.errors.length).toBe(1); expect(result.errors[0].rowNumber).toBe(1); expect(result.errors[0].type).toBe(CSV_CONVERSION_ERROR_TYPE.INVALID_TYPE); }); it('is considered to be defined if set to falsy 0 value', async () => { const emailAddresses = 0; const fileContent = [defaultCsvFields, `Alice,${emailAddresses},alice_password`].join('\n'); const file = getFile(fileContent); const result = await parseMultiUserCsv([file], mode); const user = result.users[0]; expect(result.errors.length).toBe(0); expect(user.emailAddresses.length).toBe(1); expect(user.emailAddresses[0]).toBe('0'); }); it('casts to a string', async () => { const emailAddresses = 123; const fileContent = [defaultCsvFields, `Alice,${emailAddresses},alice_password`].join('\n'); const file = getFile(fileContent); const result = await parseMultiUserCsv([file], mode); const user = result.users[0]; expect(result.errors.length).toBe(0); expect(user.emailAddresses.length).toBe(1); expect(user.emailAddresses[0]).toBe('123'); }); }); describe('password', () => { it('adds error if no password is defined', async () => { const password = ''; const fileContent = [defaultCsvFields, `Alice,[email protected],${password}`].join('\n'); const file = getFile(fileContent); const result = await parseMultiUserCsv([file], mode); expect(result.errors.length).toBe(1); expect(result.errors[0].rowNumber).toBe(1); expect(result.errors[0].type).toBe(CSV_CONVERSION_ERROR_TYPE.PASSWORD_REQUIRED); }); it('returns no errors if password is a string', async () => { const password = 'alice_password'; const fileContent = [defaultCsvFields, `Alice,[email protected],${password}`].join('\n'); const file = getFile(fileContent); const result = await parseMultiUserCsv([file], mode); const user = result.users[0]; expect(result.errors.length).toBe(0); expect(user.password).toBe('alice_password'); }); it('is considered to be defined if set to falsy 0 value', async () => { const password = 0; const fileContent = [defaultCsvFields, `Alice,[email protected],${password}`].join('\n'); const file = getFile(fileContent); const result = await parseMultiUserCsv([file], mode); const user = result.users[0]; expect(result.errors.length).toBe(0); expect(user.password).toBe(`0`); }); it('casts to a string', async () => { const password = 123; const fileContent = [defaultCsvFields, `Alice,[email protected],${password}`].join('\n'); const file = getFile(fileContent); const result = await parseMultiUserCsv([file], mode); const user = result.users[0]; expect(result.errors.length).toBe(0); expect(user.password).toBe(`123`); }); }); }); }); });
6,488
0
petrpan-code/ProtonMail/WebClients/packages/components/containers
petrpan-code/ProtonMail/WebClients/packages/components/containers/messages/MessagesSection.test.tsx
import { render, screen, waitFor } from '@testing-library/react'; import userEvent from '@testing-library/user-event'; import { mockUseApi, mockUseEventManager, mockUseFeature, mockUseMailSettings, mockUseNotifications, mockUseUser, } from '@proton/testing/index'; import { FeatureCode } from '../features'; import MessagesSection from './MessagesSection'; describe('MessagesSection', () => { let mockedApi: jest.Mock; let mockedCall: jest.Mock; beforeEach(() => { mockedApi = jest.fn(); mockedCall = jest.fn(); mockUseApi(mockedApi); mockUseEventManager({ call: mockedCall }); mockUseMailSettings(); mockUseNotifications(); mockUseFeature(); mockUseUser(); }); describe('when AlmostAllMail is not enabled', () => { it('should not render AlmostAllMail toggle', () => { mockUseFeature().mockImplementation((code) => { if (code === FeatureCode.AlmostAllMail) { return { feature: { Value: false } } as any; } return { feature: { Value: true } } as any; }); render(<MessagesSection />); expect(screen.queryByText('Exclude Spam/Trash from All mail')).not.toBeInTheDocument(); }); }); describe('when AlmostAllMail is enabled', () => { beforeEach(() => { mockUseFeature({ feature: { Value: true } }); }); it('should render AlmostAllMail toggle', () => { render(<MessagesSection />); expect(screen.getByText('Exclude Spam/Trash from All mail')).toBeInTheDocument(); }); it('should toggle setting on click', async () => { render(<MessagesSection />); const setting = screen.getByText('Exclude Spam/Trash from All mail'); await userEvent.click(setting); await waitFor(() => { expect(mockedApi).toHaveBeenCalledTimes(1); }); expect(mockedApi).toHaveBeenCalledWith({ data: { AlmostAllMail: 1 }, method: 'put', url: 'mail/v4/settings/almost-all-mail', }); await userEvent.click(setting); await waitFor(() => { expect(mockedApi).toHaveBeenCalledTimes(2); }); expect(mockedApi).toHaveBeenLastCalledWith({ data: { AlmostAllMail: 0 }, method: 'put', url: 'mail/v4/settings/almost-all-mail', }); }); }); });
6,521
0
petrpan-code/ProtonMail/WebClients/packages/components/containers
petrpan-code/ProtonMail/WebClients/packages/components/containers/notifications/manager.test.tsx
import { useState } from 'react'; import { act, renderHook } from '@testing-library/react-hooks'; import noop from '@proton/utils/noop'; import { Notification } from './interfaces'; import createNotificationManager from './manager'; describe('notification manager', () => { it('should create a notification', () => { const { result } = renderHook(() => useState<Notification[]>([])); const [, setState] = result.current; const manager = createNotificationManager(setState, noop); expect(result.current[0]).toStrictEqual([]); act(() => { manager.createNotification({ text: 'hello', }); }); expect(result.current[0]).toStrictEqual([expect.objectContaining({ text: 'hello' })]); }); describe('deduplication', () => { describe('when deduplicate true', () => { it('should remove duplicate notifications', () => { const { result } = renderHook(() => useState<Notification[]>([])); const [, setState] = result.current; const manager = createNotificationManager(setState, noop); act(() => { manager.createNotification({ text: 'foo', type: 'success', deduplicate: true, }); manager.createNotification({ text: 'foo', type: 'success', deduplicate: true, }); manager.createNotification({ text: 'bar', type: 'success', }); }); expect(result.current[0]).toStrictEqual([ expect.objectContaining({ text: 'bar' }), expect.objectContaining({ text: 'foo' }), ]); }); }); describe('when deduplicate false', () => { it('should not remove duplicate notifications', () => { const { result } = renderHook(() => useState<Notification[]>([])); const [, setState] = result.current; const manager = createNotificationManager(setState, noop); act(() => { manager.createNotification({ text: 'foo', type: 'error', deduplicate: false, }); manager.createNotification({ text: 'foo', type: 'error', }); manager.createNotification({ text: 'bar', type: 'error', }); }); expect(result.current[0]).toStrictEqual([ expect.objectContaining({ text: 'bar' }), expect.objectContaining({ text: 'foo' }), expect.objectContaining({ text: 'foo' }), ]); }); }); describe('when deduplicate is undefined', () => { it('should deduplicate a success notification', () => { const { result } = renderHook(() => useState<Notification[]>([])); const [, setState] = result.current; const manager = createNotificationManager(setState, noop); act(() => { manager.createNotification({ text: 'foo', type: 'success', }); manager.createNotification({ text: 'foo', type: 'success', }); manager.createNotification({ text: 'bar', type: 'success', }); }); expect(result.current[0]).toStrictEqual([ expect.objectContaining({ text: 'bar' }), expect.objectContaining({ text: 'foo' }), ]); }); it('should deduplicate a warning notification', () => { const { result } = renderHook(() => useState<Notification[]>([])); const [, setState] = result.current; const manager = createNotificationManager(setState, noop); act(() => { manager.createNotification({ text: 'foo', type: 'warning', }); manager.createNotification({ text: 'foo', type: 'warning', }); manager.createNotification({ text: 'bar', type: 'warning', }); }); expect(result.current[0]).toStrictEqual([ expect.objectContaining({ text: 'bar' }), expect.objectContaining({ text: 'foo' }), ]); }); it('should deduplicate a info notification', () => { const { result } = renderHook(() => useState<Notification[]>([])); const [, setState] = result.current; const manager = createNotificationManager(setState, noop); act(() => { manager.createNotification({ text: 'foo', type: 'info', }); manager.createNotification({ text: 'foo', type: 'info', }); manager.createNotification({ text: 'bar', type: 'info', }); }); expect(result.current[0]).toStrictEqual([ expect.objectContaining({ text: 'bar' }), expect.objectContaining({ text: 'foo' }), ]); }); it('should deduplicate an error notification', () => { const { result } = renderHook(() => useState<Notification[]>([])); const [, setState] = result.current; const manager = createNotificationManager(setState, noop); act(() => { manager.createNotification({ text: 'foo', type: 'error', }); manager.createNotification({ text: 'foo', type: 'error', }); manager.createNotification({ text: 'bar', type: 'error', }); }); expect(result.current[0]).toStrictEqual([ expect.objectContaining({ text: 'bar' }), expect.objectContaining({ text: 'foo' }), ]); }); }); it('should deduplicate react elements using the provided key', () => { const { result } = renderHook(() => useState<Notification[]>([])); const [, setState] = result.current; const manager = createNotificationManager(setState, noop); act(() => { manager.createNotification({ text: <div>text</div>, key: 'item1', type: 'error', }); manager.createNotification({ text: <div>text</div>, key: 'item1', type: 'error', }); manager.createNotification({ text: 'bar', key: 'item2', type: 'error', }); // Do not deduplicate if key is not provided manager.createNotification({ text: <div>text</div>, type: 'error', }); }); expect(result.current[0]).toStrictEqual([ expect.objectContaining({ text: <div>text</div> }), expect.objectContaining({ text: 'bar', key: 'item2' }), expect.objectContaining({ text: <div>text</div>, key: 'item1' }), ]); }); }); it('should allow to create notifications with raw html text and deduplicate it', () => { const { result } = renderHook(() => useState<Notification[]>([])); const [, setState] = result.current; const manager = createNotificationManager(setState, noop); act(() => { manager.createNotification({ text: 'Foo <a href="https://foo.bar">text</a>', type: 'error', }); manager.createNotification({ text: 'Foo <a href="https://foo.bar">text</a>', type: 'error', }); }); expect(result.current[0]).toStrictEqual([ expect.objectContaining({ text: ( <div dangerouslySetInnerHTML={{ __html: 'Foo <a href="https://foo.bar" rel="noopener noreferrer" target="_blank" class="color-inherit">text</a>', }} /> ), key: 'Foo <a href="https://foo.bar">text</a>', }), ]); }); });
6,527
0
petrpan-code/ProtonMail/WebClients/packages/components/containers
petrpan-code/ProtonMail/WebClients/packages/components/containers/offers/Offers.test.tsx
import { fireEvent, render, screen } from '@testing-library/react'; import { FeatureCode, TopNavbarUpsell } from '@proton/components'; import { UserModel } from '@proton/shared/lib/models'; import { OffersTestProvider, offersCache } from './Offers.test.helpers'; import { OfferConfig } from './interface'; const OFFER_CONTENT = 'deal deal deal deal deal'; const offerConfig: OfferConfig = { deals: [], featureCode: 'testOffer2022' as FeatureCode, layout: () => <div>{OFFER_CONTENT}</div>, ID: 'test-offer-2022' as OfferConfig['ID'], canBeDisabled: true, }; const offerConfigAutopopup: OfferConfig = { deals: [], featureCode: 'testOffer2022' as FeatureCode, layout: () => <div>{OFFER_CONTENT}</div>, ID: 'test-offer-2022' as OfferConfig['ID'], canBeDisabled: true, autoPopUp: 'one-time', }; jest.mock('./hooks/useOfferConfig', function () { return { __esModule: true, default: jest .fn() .mockReturnValueOnce([undefined, false]) .mockReturnValueOnce([undefined, false]) .mockReturnValueOnce([offerConfig, false]) .mockReturnValueOnce([offerConfig, false]) .mockReturnValue([offerConfigAutopopup, false]), }; }); jest.mock('./hooks/useFetchOffer', function () { return { __esModule: true, default: jest.fn(({ offerConfig }) => [offerConfig, false]), }; }); jest.mock('./hooks/useOfferFlags', function () { return { __esModule: true, default: jest.fn(() => ({ isVisited: false, loading: false, isActive: true, handleVisit: () => {}, handleHide: () => {}, })), }; }); afterEach(() => { offersCache.clear(); }); const TopNavbarComponent = () => ( <OffersTestProvider> <TopNavbarUpsell /> </OffersTestProvider> ); describe('Offers', () => { describe('Offers display', () => { it('Should display upgrade button for free users', () => { offersCache.add(UserModel.key, { isFree: true }); render(<TopNavbarComponent />); const link = screen.getByTestId('cta:upgrade-plan'); expect(link.textContent).toContain('Upgrade'); expect(link.tagName).toBe('A'); }); it('Should display nothing for paid users with offers', () => { offersCache.add(UserModel.key, { isFree: false }); render(<TopNavbarComponent />); expect(screen.queryByTestId('cta:upgrade-plan')).toBeNull(); }); describe('Non free user with valid offer', () => { it('Should display an offer button', () => { offersCache.add(UserModel.key, { isFree: false }); render(<TopNavbarComponent />); expect(screen.getByTestId('cta:special-offer')?.textContent).toBe('Special offer'); }); it('Should open a modal with offer content', () => { offersCache.add(UserModel.key, { isFree: false }); render(<TopNavbarComponent />); const specialOfferCta = screen.getByTestId('cta:special-offer'); fireEvent.click(specialOfferCta); screen.getByText(OFFER_CONTENT); }); it.skip('Should open a modal when autopopup', () => { offersCache.add(UserModel.key, { isFree: false }); render(<TopNavbarComponent />); screen.getByText(OFFER_CONTENT); }); }); }); });
6,556
0
petrpan-code/ProtonMail/WebClients/packages/components/containers/offers
petrpan-code/ProtonMail/WebClients/packages/components/containers/offers/helpers/dealPrices.test.ts
import { CYCLE } from '@proton/shared/lib/constants'; import { DealWithPrices } from '../interface'; import { getDiscount, getDiscountWithCoupon } from './dealPrices'; describe('getDiscountWithCoupon', () => { it('should return discount', () => { expect( getDiscountWithCoupon({ cycle: CYCLE.YEARLY, prices: { withCoupon: 44, withoutCouponMonthly: 77, }, } as DealWithPrices) ).toBe(95); }); it('should return custom discount for 15 months', () => { expect( getDiscountWithCoupon({ cycle: CYCLE.FIFTEEN, prices: { withCoupon: 7188, withoutCoupon: 14985, withoutCouponMonthly: 999, }, } as DealWithPrices) ).toBe(52); }); it('should return custom discount for 30 months', () => { expect( getDiscountWithCoupon({ cycle: CYCLE.THIRTY, prices: { withCoupon: 11976, withoutCoupon: 29970, withoutCouponMonthly: 999, }, } as DealWithPrices) ).toBe(60); }); }); describe('getDiscount', () => { it('should return discount', () => { expect( getDiscount({ cycle: CYCLE.YEARLY, prices: { withoutCoupon: 44, withoutCouponMonthly: 77, }, } as DealWithPrices) ).toBe(95); }); });
6,585
0
petrpan-code/ProtonMail/WebClients/packages/components/containers/offers/operations
petrpan-code/ProtonMail/WebClients/packages/components/containers/offers/operations/blackFridayInbox2023Free/eligibility.test.ts
import { getUnixTime } from 'date-fns'; import { APPS, COUPON_CODES } from '@proton/shared/lib/constants'; import { ProtonConfig, Subscription, UserModel } from '@proton/shared/lib/interfaces'; import isEligible from './eligibility'; describe('BF 2023 Inbox offer for Free', () => { const protonConfig = { APP_NAME: APPS.PROTONMAIL } as ProtonConfig; const user = { isFree: true, isDelinquent: false, canPay: true } as UserModel; const pathname = '/u/1/mail/'; beforeAll(() => { Object.defineProperty(window, 'location', { value: { pathname }, writable: true, }); }); it('should be available for free account', () => { expect(isEligible({ user, protonConfig })).toBeTruthy(); expect(isEligible({ user, protonConfig: { ...protonConfig, APP_NAME: APPS.PROTONCALENDAR } })).toBeTruthy(); expect(isEligible({ user, protonConfig: { ...protonConfig, APP_NAME: APPS.PROTONACCOUNT } })).toBeTruthy(); }); it('should be available for trial account', () => { const subscription = { CouponCode: COUPON_CODES.REFERRAL } as Subscription; expect(isEligible({ user: { ...user, isPaid: true, isFree: false }, subscription, protonConfig })).toBeTruthy(); }); it('should not be available to downgrader', () => { const date = new Date(2023, 9, 2, 0, 0, 0); // October 2 2023 00:00:00 UTC const lastSubscriptionEnd = getUnixTime(date); expect(isEligible({ protonConfig, user, lastSubscriptionEnd })).toBeFalsy(); }); });
6,686
0
petrpan-code/ProtonMail/WebClients/packages/components/containers
petrpan-code/ProtonMail/WebClients/packages/components/containers/payments/Bitcoin.test.tsx
import { render, waitFor } from '@testing-library/react'; import { createToken, getTokenStatus } from '@proton/shared/lib/api/payments'; import { Api, Currency } from '@proton/shared/lib/interfaces'; import { addApiMock, apiMock, flushPromises } from '@proton/testing'; import { PAYMENT_METHOD_TYPES, PAYMENT_TOKEN_STATUS } from '../../payments/core'; import Bitcoin from './Bitcoin'; import useBitcoin, { BITCOIN_POLLING_INTERVAL, OnBitcoinAwaitingPayment, OnBitcoinTokenValidated } from './useBitcoin'; const onTokenValidated = jest.fn(); const onAwaitingPayment = jest.fn(); type InnerProps = { onTokenValidated: OnBitcoinTokenValidated; onAwaitingPayment: OnBitcoinAwaitingPayment; api: Api; amount: number; currency: Currency; processingToken: boolean; }; const BitcoinTestComponent = (props: InnerProps) => { const bitcoinHook = useBitcoin({ api: props.api, Amount: props.amount, Currency: props.currency, onTokenValidated: props.onTokenValidated, onAwaitingPayment: props.onAwaitingPayment, enablePolling: true, }); return <Bitcoin {...props} {...bitcoinHook} />; }; beforeAll(() => { jest.useFakeTimers(); }); afterAll(() => { jest.useRealTimers(); }); const createTokenUrl = createToken({} as any).url; const defaultTokenResponse = { Token: 'token-123', Data: { CoinAddress: 'address-123', CoinAmount: '0.00135', }, }; beforeEach(() => { jest.clearAllMocks(); addApiMock(createTokenUrl, () => defaultTokenResponse); }); it('should render', async () => { const { container } = render( <BitcoinTestComponent api={apiMock} amount={1000} currency="USD" onTokenValidated={onTokenValidated} onAwaitingPayment={onAwaitingPayment} processingToken={false} /> ); await waitFor(() => { expect(container).not.toBeEmptyDOMElement(); }); expect(container).toHaveTextContent('address-123'); expect(container).toHaveTextContent('0.00135'); }); it('should render for signup-pass', async () => { const { container } = render( <BitcoinTestComponent api={apiMock} amount={1000} currency="USD" onTokenValidated={onTokenValidated} onAwaitingPayment={onAwaitingPayment} processingToken={false} /> ); await waitFor(() => { expect(container).not.toBeEmptyDOMElement(); }); expect(container).toHaveTextContent('address-123'); expect(container).toHaveTextContent('0.00135'); }); it('should show loading during the initial fetching', async () => { const { queryByTestId } = render( <BitcoinTestComponent api={apiMock} amount={1000} currency="USD" onTokenValidated={onTokenValidated} onAwaitingPayment={onAwaitingPayment} processingToken={false} /> ); expect(queryByTestId('circle-loader')).toBeInTheDocument(); }); it('should check the token every 10 seconds', async () => { addApiMock(getTokenStatus('token-123').url, () => { return { Status: PAYMENT_TOKEN_STATUS.STATUS_PENDING }; }); render( <BitcoinTestComponent api={apiMock} amount={1000} currency="USD" onTokenValidated={onTokenValidated} onAwaitingPayment={onAwaitingPayment} processingToken={false} /> ); jest.advanceTimersByTime(BITCOIN_POLLING_INTERVAL); await flushPromises(); addApiMock(getTokenStatus('token-123').url, function second() { return { Status: PAYMENT_TOKEN_STATUS.STATUS_CHARGEABLE }; }); jest.advanceTimersByTime(BITCOIN_POLLING_INTERVAL); await flushPromises(); expect(onTokenValidated).toHaveBeenCalledTimes(1); expect(onTokenValidated).toHaveBeenLastCalledWith({ Payment: { Type: PAYMENT_METHOD_TYPES.TOKEN, Details: { Token: 'token-123', }, }, cryptoAddress: 'address-123', cryptoAmount: '0.00135', }); jest.advanceTimersByTime(BITCOIN_POLLING_INTERVAL); await flushPromises(); expect(onTokenValidated).toHaveBeenCalledTimes(1); // check that it's called only once }); it('should render Try again button in case of error', async () => { addApiMock(createTokenUrl, () => { return Promise.reject('error'); }); const { queryByTestId, container } = render( <BitcoinTestComponent api={apiMock} amount={1000} currency="USD" onTokenValidated={onTokenValidated} onAwaitingPayment={onAwaitingPayment} processingToken={false} /> ); await waitFor(() => { expect(queryByTestId('bitcoin-try-again')).toBeInTheDocument(); }); addApiMock(createTokenUrl, () => defaultTokenResponse); queryByTestId('bitcoin-try-again')?.click(); await waitFor(() => { expect(container).toHaveTextContent('address-123'); }); await waitFor(() => { expect(container).toHaveTextContent('0.00135'); }); }); it('should render warning if the amount is too low', async () => { const { container } = render( <BitcoinTestComponent api={apiMock} amount={100} currency="USD" onTokenValidated={onTokenValidated} onAwaitingPayment={onAwaitingPayment} processingToken={false} /> ); await waitFor(() => { expect(container).toHaveTextContent('Amount below minimum'); }); }); it('should render warning if the amount is too high', async () => { const { container } = render( <BitcoinTestComponent api={apiMock} amount={4000100} currency="USD" onTokenValidated={onTokenValidated} onAwaitingPayment={onAwaitingPayment} processingToken={false} /> ); await waitFor(() => { expect(container).toHaveTextContent('Amount above maximum'); }); }); it('should call awaitingPayment callback when the token is created', async () => { const onAwaitingPayment = jest.fn(); render( <BitcoinTestComponent api={apiMock} amount={1000} currency="USD" onTokenValidated={onTokenValidated} onAwaitingPayment={onAwaitingPayment} processingToken={false} /> ); expect(onAwaitingPayment).toHaveBeenLastCalledWith(false); await waitFor(() => { expect(onAwaitingPayment).toHaveBeenLastCalledWith(true); }); }); it('should call awaitingPayment callback when the token is validated', async () => { const onAwaitingPayment = jest.fn(); render( <BitcoinTestComponent api={apiMock} amount={1000} currency="USD" onTokenValidated={onTokenValidated} onAwaitingPayment={onAwaitingPayment} processingToken={false} /> ); jest.advanceTimersByTime(BITCOIN_POLLING_INTERVAL); await flushPromises(); expect(onAwaitingPayment).toHaveBeenLastCalledWith(false); }); it('should call awaitingPayment callback when amount or currency is changed', async () => { const onAwaitingPayment = jest.fn(); const { rerender } = render( <BitcoinTestComponent api={apiMock} amount={1000} currency="USD" onTokenValidated={onTokenValidated} onAwaitingPayment={onAwaitingPayment} processingToken={false} /> ); rerender( <BitcoinTestComponent api={apiMock} amount={2000} currency="USD" onTokenValidated={onTokenValidated} onAwaitingPayment={onAwaitingPayment} processingToken={false} /> ); jest.advanceTimersByTime(BITCOIN_POLLING_INTERVAL); await flushPromises(); expect(onAwaitingPayment).toHaveBeenLastCalledWith(false); });
6,696
0
petrpan-code/ProtonMail/WebClients/packages/components/containers
petrpan-code/ProtonMail/WebClients/packages/components/containers/payments/CreditCard.test.tsx
import { render } from '@testing-library/react'; import userEvent from '@testing-library/user-event'; import { useCard } from '@proton/components/payments/react-extensions'; import { apiMock } from '@proton/testing'; import CreditCard, { Props } from './CreditCard'; beforeEach(() => { jest.clearAllMocks(); }); const TestComponent = (rest?: Partial<Props>) => { const cardHook = useCard( { amountAndCurrency: { Amount: 0, Currency: 'USD', }, }, { api: apiMock, verifyPayment: jest.fn(), } ); return ( <CreditCard card={cardHook.card} errors={cardHook.errors} fieldsStatus={cardHook.fieldsStatus} onChange={cardHook.setCardProperty} {...rest} /> ); }; it('should render', () => { const { container } = render(<TestComponent />); expect(container).not.toBeEmptyDOMElement(); }); it('should be not narrow by default', () => { const { queryByTestId } = render(<TestComponent />); expect(queryByTestId('credit-card-form-container')).toHaveClass('field-two-container'); expect(queryByTestId('credit-card-form-container')).not.toHaveClass('credit-card-form--narrow'); }); it('should render narrow', () => { const { queryByTestId } = render(<TestComponent forceNarrow />); expect(queryByTestId('credit-card-form-container')).toHaveClass('field-two-container'); expect(queryByTestId('credit-card-form-container')).toHaveClass('credit-card-form--narrow'); }); it('should not accept invalid CVC input', async () => { const { queryByTestId } = render(<TestComponent />); const cvcInput = queryByTestId('cvc') as HTMLInputElement; await userEvent.type(cvcInput, 'abc'); expect(cvcInput.value).toBe(''); }); describe('autoadvancer', () => { it('should move the cursor to the expiration date when credit card number is entered', async () => { const { queryByTestId } = render(<TestComponent />); const ccNumber = queryByTestId('ccnumber') as HTMLInputElement; await userEvent.type(ccNumber, '4242424242424242'); const expInput = queryByTestId('exp') as HTMLInputElement; expect(expInput).toHaveFocus(); }); it('should move the cursor to the cvc when expiration date is entered', async () => { const { queryByTestId } = render(<TestComponent />); const expInput = queryByTestId('exp') as HTMLInputElement; await userEvent.type(expInput, '1232'); const cvcInput = queryByTestId('cvc') as HTMLInputElement; expect(cvcInput).toHaveFocus(); }); it('should move the cursor to the zip when cvc is entered', async () => { const { queryByTestId } = render(<TestComponent />); const cvcInput = queryByTestId('cvc') as HTMLInputElement; await userEvent.type(cvcInput, '123'); const zipInput = queryByTestId('postalCode') as HTMLInputElement; expect(zipInput).toHaveFocus(); }); it('narrow - should move the cursor to the expiration date when credit card number is entered', async () => { const { queryByTestId } = render(<TestComponent forceNarrow />); const ccNumber = queryByTestId('ccnumber') as HTMLInputElement; await userEvent.type(ccNumber, '4242424242424242'); const expInput = queryByTestId('exp') as HTMLInputElement; expect(expInput).toHaveFocus(); }); it('narrow should move the cursor to the cvc when expiration date is entered', async () => { const { queryByTestId } = render(<TestComponent forceNarrow />); const expInput = queryByTestId('exp') as HTMLInputElement; await userEvent.type(expInput, '1232'); const cvcInput = queryByTestId('cvc') as HTMLInputElement; expect(cvcInput).toHaveFocus(); }); it('narrow should move the cursor to the zip when cvc is entered', async () => { const { queryByTestId } = render(<TestComponent forceNarrow />); const cvcInput = queryByTestId('cvc') as HTMLInputElement; await userEvent.type(cvcInput, '123'); const zipInput = queryByTestId('postalCode') as HTMLInputElement; expect(zipInput).toHaveFocus(); }); it('should not move cursor the second time, if user decides to edit the field', async () => { const { queryByTestId } = render(<TestComponent />); const ccNumber = queryByTestId('ccnumber') as HTMLInputElement; await userEvent.type(ccNumber, '4242424242424242'); expect(ccNumber.value).toBe('4242 4242 4242 4242'); // formatted const expInput = queryByTestId('exp') as HTMLInputElement; expect(expInput).toHaveFocus(); await userEvent.click(ccNumber); await userEvent.type(ccNumber, '4242424242424242'); expect(ccNumber).toHaveFocus(); }); it('should not move the cursor if the credit card number is invalid', async () => { const { queryByTestId } = render(<TestComponent />); const ccNumber = queryByTestId('ccnumber') as HTMLInputElement; await userEvent.type(ccNumber, '4000000000000000'); expect(ccNumber.value).toBe('4000 0000 0000 0000'); // formatted expect(ccNumber).toHaveFocus(); }); it('should not move the cursor if the expiration date is invalid', async () => { const { queryByTestId } = render(<TestComponent />); const expInput = queryByTestId('exp') as HTMLInputElement; await userEvent.type(expInput, '1211'); expect(expInput.value).toBe('12/11'); expect(expInput).toHaveFocus(); }); it('should not move the cursor if the cvc is invalid', async () => { const { queryByTestId } = render(<TestComponent />); const cvcInput = queryByTestId('cvc') as HTMLInputElement; await userEvent.type(cvcInput, '12'); expect(cvcInput).toHaveFocus(); }); it('should move the cursor when user enter correct AmEx card number', async () => { const { queryByTestId } = render(<TestComponent />); const ccNumber = queryByTestId('ccnumber') as HTMLInputElement; const num = '374245455400126'; expect(num.length).toBe(15); // not 16 as for Visa await userEvent.type(ccNumber, num); expect(ccNumber.value).toBe('3742 454554 00126'); // formatted const expInput = queryByTestId('exp') as HTMLInputElement; expect(expInput).toHaveFocus(); }); it('should move the cursor to ZIP when user enter correct AmEx card number and 4-digit security code', async () => { const { queryByTestId } = render(<TestComponent />); const ccNumber = queryByTestId('ccnumber') as HTMLInputElement; const num = '374245455400126'; expect(num.length).toBe(15); // not 16 as for Visa await userEvent.type(ccNumber, num); const expInput = queryByTestId('exp') as HTMLInputElement; expect(expInput).toHaveFocus(); await userEvent.type(expInput, '1232'); const cvcInput = queryByTestId('cvc') as HTMLInputElement; expect(cvcInput).toHaveFocus(); await userEvent.type(cvcInput, '1234'); const zipInput = queryByTestId('postalCode') as HTMLInputElement; expect(zipInput).toHaveFocus(); expect(cvcInput.value).toBe('1234'); }); });
6,698
0
petrpan-code/ProtonMail/WebClients/packages/components/containers
petrpan-code/ProtonMail/WebClients/packages/components/containers/payments/CreditsModal.test.tsx
import { fireEvent, render, waitFor } from '@testing-library/react'; import userEvent from '@testing-library/user-event'; import { PAYMENT_TOKEN_STATUS } from '@proton/components/payments/core'; import { buyCredit, createToken } from '@proton/shared/lib/api/payments'; import { wait } from '@proton/shared/lib/helpers/promise'; import { addApiMock, applyHOCs, mockEventManager, mockPaymentMethods, mockPaymentStatus, withApi, withAuthentication, withCache, withConfig, withDeprecatedModals, withEventManager, withNotifications, } from '@proton/testing'; // eslint-disable-next-line @typescript-eslint/no-unused-vars import PaymentMethodSelector from '../paymentMethods/PaymentMethodSelector'; import CreditsModal from './CreditsModal'; jest.mock('@proton/components/components/portal/Portal'); const createTokenMock = jest.fn((request) => { const type = request?.data?.Payment?.Type ?? ''; let Token: string; if (type === 'paypal') { Token = 'paypal-payment-token-123'; } else if (type === 'paypal-credit') { Token = 'paypal-credit-payment-token-123'; } else { Token = 'payment-token-123'; } return { Token, Status: PAYMENT_TOKEN_STATUS.STATUS_CHARGEABLE, }; }); const buyCreditUrl = buyCredit({} as any).url; const buyCreditMock = jest.fn().mockResolvedValue({}); beforeEach(() => { jest.clearAllMocks(); // That's an unresolved issue of jsdom https://github.com/jsdom/jsdom/issues/918 (window as any).SVGElement.prototype.getBBox = jest.fn().mockReturnValue({ width: 0 }); addApiMock(createToken({} as any).url, createTokenMock); addApiMock(buyCreditUrl, buyCreditMock); mockPaymentStatus(); mockPaymentMethods().noSaved(); }); const ContextCreditsModal = applyHOCs( withConfig(), withNotifications(), withEventManager(), withApi(), withCache(), withDeprecatedModals(), withAuthentication() )(CreditsModal); it('should render', () => { const { container } = render(<ContextCreditsModal open={true} />); expect(container).not.toBeEmptyDOMElement(); }); it('should display the credit card form by default', async () => { const { findByTestId } = render(<ContextCreditsModal open={true} />); const ccnumber = await findByTestId('ccnumber'); expect(ccnumber).toBeTruthy(); }); it('should display the payment method selector', async () => { const { queryByTestId } = render(<ContextCreditsModal open={true} />); await waitFor(() => { /** * That's essentially internals of {@link PaymentMethodSelector} **/ expect(queryByTestId('payment-method-selector')).toBeTruthy(); }); }); function selectMethod(container: HTMLElement, value: string) { const dropdownButton = container.querySelector('#select-method') as HTMLButtonElement; if (dropdownButton) { fireEvent.click(dropdownButton); const button = container.querySelector(`button[title="${value}"]`) as HTMLButtonElement; fireEvent.click(button); return; } const input = container.querySelector(`#${value}`) as HTMLInputElement; input.click(); } it('should select the payment method when user clicks it', async () => { const { container, queryByTestId } = render(<ContextCreditsModal open={true} />); await waitFor(() => { selectMethod(container, 'PayPal'); }); // secondary check expect(queryByTestId('payment-method-selector')).toHaveTextContent('PayPal'); // check that the credit card form is not displayed expect(queryByTestId('ccnumber')).toBeFalsy(); expect(queryByTestId('paypal-view')).toBeTruthy(); expect(queryByTestId('paypal-button')).toBeTruthy(); // switching back to credit card selectMethod(container, 'New credit/debit card'); expect(queryByTestId('ccnumber')).toBeTruthy(); expect(queryByTestId('paypal-button')).toBeFalsy(); expect(queryByTestId('top-up-button')).toBeTruthy(); }); it('should display the credit card form initially', async () => { const { queryByTestId } = render(<ContextCreditsModal open={true} />); await waitFor(() => { expect(queryByTestId('ccnumber')).toBeTruthy(); }); }); it('should remember credit card details when switching back and forth', async () => { const { container, queryByTestId } = render(<ContextCreditsModal open={true} />); await waitFor(() => {}); const ccnumber = queryByTestId('ccnumber') as HTMLInputElement; const exp = queryByTestId('exp') as HTMLInputElement; const cvc = queryByTestId('cvc') as HTMLInputElement; await userEvent.type(ccnumber, '4242424242424242'); await userEvent.type(exp, '1232'); await userEvent.type(cvc, '123'); // switching to paypal selectMethod(container, 'PayPal'); expect(queryByTestId('paypal-view')).toBeTruthy(); // switching back to credit card selectMethod(container, 'New credit/debit card'); expect((queryByTestId('ccnumber') as HTMLInputElement).value).toBe('4242 4242 4242 4242'); expect((queryByTestId('exp') as HTMLInputElement).value).toBe('12/32'); expect((queryByTestId('cvc') as HTMLInputElement).value).toBe('123'); }); it('should display validation errors after user submits credit card', async () => { const { container, findByTestId, queryByTestId } = render(<ContextCreditsModal open={true} />); await waitFor(() => {}); const ccnumber = queryByTestId('ccnumber') as HTMLInputElement; const exp = queryByTestId('exp') as HTMLInputElement; const cvc = queryByTestId('cvc') as HTMLInputElement; await userEvent.type(ccnumber, '1234567812345678'); await userEvent.type(exp, '1212'); await userEvent.type(cvc, '123'); const cardError = 'Invalid card number'; const zipError = 'Invalid postal code'; expect(container).not.toHaveTextContent(cardError); expect(container).not.toHaveTextContent(zipError); const topUpButton = await findByTestId('top-up-button'); fireEvent.click(topUpButton); expect(container).toHaveTextContent(cardError); expect(container).toHaveTextContent(zipError); }); it('should display invalid expiration date error', async () => { const { container, findByTestId, queryByTestId } = render(<ContextCreditsModal open={true} />); await waitFor(() => {}); const ccnumber = queryByTestId('ccnumber') as HTMLInputElement; const exp = queryByTestId('exp') as HTMLInputElement; const cvc = queryByTestId('cvc') as HTMLInputElement; await userEvent.type(ccnumber, '4242424242424242'); await userEvent.type(exp, '1212'); await userEvent.type(cvc, '123'); const expError = 'Invalid expiration date'; expect(container).not.toHaveTextContent(expError); const topUpButton = await findByTestId('top-up-button'); fireEvent.click(topUpButton); expect(container).toHaveTextContent(expError); }); it('should create payment token and then buy credits with it', async () => { const onClose = jest.fn(); const { findByTestId, queryByTestId } = render(<ContextCreditsModal open={true} onClose={onClose} />); await waitFor(() => {}); const ccnumber = queryByTestId('ccnumber') as HTMLInputElement; const exp = queryByTestId('exp') as HTMLInputElement; const cvc = queryByTestId('cvc') as HTMLInputElement; const postalCode = queryByTestId('postalCode') as HTMLInputElement; await userEvent.type(ccnumber, '4242424242424242'); await userEvent.type(exp, '1232'); await userEvent.type(cvc, '123'); await userEvent.type(postalCode, '11111'); const topUpButton = await findByTestId('top-up-button'); fireEvent.click(topUpButton); await waitFor(() => { expect(buyCreditMock).toHaveBeenCalled(); }); await waitFor(() => { expect(buyCreditMock).toHaveBeenCalledWith( expect.objectContaining({ data: expect.objectContaining({ Payment: expect.objectContaining({ Type: 'token', Details: expect.objectContaining({ Token: 'payment-token-123', }), }), Amount: 5000, Currency: 'EUR', }), method: 'post', url: buyCreditUrl, }) ); }); await waitFor(() => { expect(mockEventManager.call).toHaveBeenCalled(); }); await waitFor(() => { expect(onClose).toHaveBeenCalled(); }); }); it('should create payment token and then buy credits with it - custom amount', async () => { const onClose = jest.fn(); const { findByTestId, queryByTestId } = render(<ContextCreditsModal open={true} onClose={onClose} />); await waitFor(() => {}); const otherAmountInput = queryByTestId('other-amount') as HTMLInputElement; await userEvent.type(otherAmountInput, '123'); const ccnumber = queryByTestId('ccnumber') as HTMLInputElement; const exp = queryByTestId('exp') as HTMLInputElement; const cvc = queryByTestId('cvc') as HTMLInputElement; const postalCode = queryByTestId('postalCode') as HTMLInputElement; await userEvent.type(ccnumber, '4242424242424242'); await userEvent.type(exp, '1232'); await userEvent.type(cvc, '123'); await userEvent.type(postalCode, '11111'); await wait(500); const topUpButton = await findByTestId('top-up-button'); fireEvent.click(topUpButton); await waitFor(() => { expect(buyCreditMock).toHaveBeenCalled(); }); await waitFor(() => { expect(buyCreditMock).toHaveBeenCalledWith( expect.objectContaining({ data: expect.objectContaining({ Payment: expect.objectContaining({ Type: 'token', Details: expect.objectContaining({ Token: 'payment-token-123', }), }), Amount: 12300, Currency: 'EUR', }), method: 'post', url: buyCreditUrl, }) ); }); await waitFor(() => { expect(mockEventManager.call).toHaveBeenCalled(); }); await waitFor(() => { expect(onClose).toHaveBeenCalled(); }); }); it('should create payment token for paypal and then buy credits with it', async () => { const onClose = jest.fn(); const { container, queryByTestId } = render(<ContextCreditsModal open={true} onClose={onClose} />); await waitFor(() => { selectMethod(container, 'PayPal'); }); const paypalButton = queryByTestId('paypal-button') as HTMLButtonElement; fireEvent.click(paypalButton); await waitFor(() => { expect(buyCreditMock).toHaveBeenCalled(); }); await waitFor(() => { expect(buyCreditMock).toHaveBeenCalledWith( expect.objectContaining({ data: expect.objectContaining({ Payment: expect.objectContaining({ Type: 'token', Details: expect.objectContaining({ Token: 'paypal-payment-token-123', }), }), Amount: 5000, Currency: 'EUR', type: 'paypal', }), method: 'post', url: buyCreditUrl, }) ); }); await waitFor(() => { expect(mockEventManager.call).toHaveBeenCalled(); }); await waitFor(() => { expect(onClose).toHaveBeenCalled(); }); }); it('should create payment token for paypal and then buy credits with it - custom amount', async () => { const onClose = jest.fn(); const { container, queryByTestId } = render(<ContextCreditsModal open={true} onClose={onClose} />); await waitFor(() => { selectMethod(container, 'PayPal'); }); const otherAmountInput = queryByTestId('other-amount') as HTMLInputElement; await userEvent.type(otherAmountInput, '123'); await wait(1000); const paypalButton = queryByTestId('paypal-button') as HTMLButtonElement; fireEvent.click(paypalButton); await waitFor(() => { expect(buyCreditMock).toHaveBeenCalled(); }); await waitFor(() => { expect(buyCreditMock).toHaveBeenCalledWith( expect.objectContaining({ data: expect.objectContaining({ Payment: expect.objectContaining({ Type: 'token', Details: expect.objectContaining({ Token: 'paypal-payment-token-123', }), }), Amount: 12300, Currency: 'EUR', type: 'paypal', }), method: 'post', url: buyCreditUrl, }) ); }); await waitFor(() => { expect(mockEventManager.call).toHaveBeenCalled(); }); await waitFor(() => { expect(onClose).toHaveBeenCalled(); }); }); it('should disable paypal button while the amount is debouncing', async () => { const onClose = jest.fn(); const { container, queryByTestId } = render(<ContextCreditsModal open={true} onClose={onClose} />); await waitFor(() => { selectMethod(container, 'PayPal'); }); const otherAmountInput = queryByTestId('other-amount') as HTMLInputElement; await userEvent.type(otherAmountInput, '123'); expect(queryByTestId('paypal-button')).toBeDisabled(); expect(queryByTestId('paypal-credit-button')).toBeDisabled(); await wait(1000); expect(queryByTestId('paypal-button')).not.toBeDisabled(); expect(queryByTestId('paypal-credit-button')).not.toBeDisabled(); }); it('should disable paypal button if the amount is too high', async () => { const onClose = jest.fn(); const { container, queryByTestId } = render(<ContextCreditsModal open={true} onClose={onClose} />); await waitFor(() => { selectMethod(container, 'PayPal'); }); const otherAmountInput = queryByTestId('other-amount') as HTMLInputElement; await userEvent.type(otherAmountInput, '40001'); await wait(1000); expect(queryByTestId('paypal-button')).toBeDisabled(); expect(queryByTestId('paypal-credit-button')).toBeDisabled(); await userEvent.clear(otherAmountInput); await userEvent.type(otherAmountInput, '40000'); await wait(1000); expect(queryByTestId('paypal-button')).not.toBeDisabled(); expect(queryByTestId('paypal-credit-button')).not.toBeDisabled(); }); it('should create payment token for paypal-credit and then buy credits with it', async () => { const onClose = jest.fn(); const { container, queryByTestId } = render(<ContextCreditsModal open={true} onClose={onClose} />); await waitFor(() => { selectMethod(container, 'PayPal'); }); const paypalCreditButton = queryByTestId('paypal-credit-button') as HTMLButtonElement; fireEvent.click(paypalCreditButton); await waitFor(() => { expect(buyCreditMock).toHaveBeenCalled(); }); await waitFor(() => { expect(buyCreditMock).toHaveBeenCalledWith( expect.objectContaining({ data: expect.objectContaining({ Payment: expect.objectContaining({ Type: 'token', Details: expect.objectContaining({ Token: 'paypal-credit-payment-token-123', }), }), Amount: 5000, Currency: 'EUR', type: 'paypal-credit', }), method: 'post', url: buyCreditUrl, }) ); }); await waitFor(() => { expect(mockEventManager.call).toHaveBeenCalled(); }); await waitFor(() => { expect(onClose).toHaveBeenCalled(); }); }); const paypalPayerId = 'AAAAAAAAAAAAA'; const paypalShort = `PayPal - ${paypalPayerId}`; it('should display the saved credit cards', async () => { mockPaymentMethods().noSaved().withCard({ Last4: '4242', Brand: 'Visa', ExpMonth: '01', ExpYear: '2025', Name: 'John Smith', Country: 'US', ZIP: '11111', }); const { container, queryByTestId } = render(<ContextCreditsModal open={true} />); await waitFor(() => { expect(container.querySelector('#select-method')).toBeTruthy(); }); await waitFor(() => { expect(queryByTestId('existing-credit-card')).toBeTruthy(); }); expect(container).toHaveTextContent('Visa ending in 4242'); expect(container).toHaveTextContent('•••• •••• •••• 4242'); expect(container).toHaveTextContent('John Smith'); expect(container).toHaveTextContent('01/2025'); }); it('should display the saved paypal account', async () => { mockPaymentMethods().noSaved().withPaypal({ BillingAgreementID: 'B-22222222222222222', PayerID: paypalPayerId, Payer: '', }); const { container, queryByTestId } = render(<ContextCreditsModal open={true} />); await waitFor(() => { expect(container.querySelector('#select-method')).toBeTruthy(); selectMethod(container, paypalShort); }); expect(queryByTestId('existing-paypal')).toBeTruthy(); expect(container).toHaveTextContent('PayPal - AAAAAAAAAAAAA'); }); it('should create payment token for saved card and then buy credits with it', async () => { mockPaymentMethods().noSaved().withCard({ Last4: '4242', Brand: 'Visa', ExpMonth: '01', ExpYear: '2025', Name: 'John Smith', Country: 'US', ZIP: '11111', }); const onClose = jest.fn(); const { container, findByTestId } = render(<ContextCreditsModal open={true} onClose={onClose} />); await waitFor(() => { selectMethod(container, 'Visa ending in 4242'); }); const topUpButton = await findByTestId('top-up-button'); fireEvent.click(topUpButton); await waitFor(() => { expect(buyCreditMock).toHaveBeenCalled(); }); await waitFor(() => { expect(buyCreditMock).toHaveBeenCalledWith( expect.objectContaining({ data: expect.objectContaining({ Payment: expect.objectContaining({ Type: 'token', Details: expect.objectContaining({ Token: 'payment-token-123', }), }), Amount: 5000, Currency: 'EUR', }), method: 'post', url: buyCreditUrl, }) ); }); await waitFor(() => { expect(mockEventManager.call).toHaveBeenCalled(); }); await waitFor(() => { expect(onClose).toHaveBeenCalled(); }); }); it('should create payment token for saved paypal and then buy credits with it', async () => { mockPaymentMethods().noSaved().withPaypal({ BillingAgreementID: 'B-22222222222222222', PayerID: paypalPayerId, Payer: '', }); const onClose = jest.fn(); const { container, findByTestId } = render(<ContextCreditsModal open={true} onClose={onClose} />); await waitFor(() => { selectMethod(container, paypalShort); }); const topUpButton = await findByTestId('top-up-button'); fireEvent.click(topUpButton); await waitFor(() => { expect(buyCreditMock).toHaveBeenCalled(); }); await waitFor(() => { expect(buyCreditMock).toHaveBeenCalledWith( expect.objectContaining({ data: expect.objectContaining({ Payment: expect.objectContaining({ Type: 'token', Details: expect.objectContaining({ // The saved paypal method isn't handled by paypal hook. // It's handled by the same hook as the saved credit card. // That's why the mocked token isn't taken from the paypal mock this time. Token: 'payment-token-123', }), }), Amount: 5000, Currency: 'EUR', }), method: 'post', url: buyCreditUrl, }) ); }); await waitFor(() => { expect(mockEventManager.call).toHaveBeenCalled(); }); await waitFor(() => { expect(onClose).toHaveBeenCalled(); }); });
6,700
0
petrpan-code/ProtonMail/WebClients/packages/components/containers
petrpan-code/ProtonMail/WebClients/packages/components/containers/payments/CreditsSection.test.tsx
import { render } from '@testing-library/react'; import { mockSubscriptionCache, mockUserCache, userDefaultResponse } from '@proton/components/hooks/helpers/test'; import { PLANS } from '@proton/shared/lib/constants'; import { External, Subscription, SubscriptionModel } from '@proton/shared/lib/interfaces'; import { formatUser } from '@proton/shared/lib/models/userModel'; import { applyHOCs, withApi, withCache } from '@proton/testing/index'; import CreditsSection from './CreditsSection'; let subscription: SubscriptionModel; let upcoming: Subscription | null = null; let user: any; jest.mock('@proton/components/components/portal/Portal'); const ContextCreditsSection = applyHOCs(withApi(), withCache())(CreditsSection); beforeEach(() => { subscription = { ID: '123', InvoiceID: '1234', Cycle: 1, PeriodStart: 1696561158, PeriodEnd: 1699239558, CreateTime: 1696561161, CouponCode: null, Currency: 'CHF', Amount: 1299, Discount: 0, RenewAmount: 1299, Plans: [ { ID: '1', Type: 1, Name: PLANS.BUNDLE, Title: 'Proton Unlimited', MaxDomains: 3, MaxAddresses: 15, MaxCalendars: 25, MaxSpace: 536870912000, MaxMembers: 1, MaxVPN: 10, MaxTier: 2, Services: 15, Features: 1, State: 1, Cycle: 1, Currency: 'CHF', Amount: 1299, Offers: [], Quantity: 1, Pricing: { 1: 1299, 12: 11988, 24: 19176, }, }, ], Renew: 1, External: 0, UpcomingSubscription: null, isManagedByMozilla: false, }; upcoming = { ID: '124', InvoiceID: null as any, Cycle: 12, PeriodStart: 1699239558, PeriodEnd: 1730861958, CreateTime: 1696561195, CouponCode: null, Currency: 'CHF', Amount: 11988, Discount: 0, RenewAmount: 11988, Plans: [ { ID: '1', Type: 1, Name: PLANS.BUNDLE, Title: 'Proton Unlimited', MaxDomains: 3, MaxAddresses: 15, MaxCalendars: 25, MaxSpace: 536870912000, MaxMembers: 1, MaxVPN: 10, MaxTier: 2, Services: 15, Features: 1, State: 1, Cycle: 12, Currency: 'CHF', Amount: 11988, Quantity: 1, Offers: [], Pricing: { 1: 1299, 12: 11988, 24: 19176, }, }, ], Renew: 1, External: 0, }; jest.clearAllMocks(); user = { ...userDefaultResponse, }; user.User.Credit = 11988; // credit to buy the upcoming subscription mockUserCache(formatUser(user.User)); mockSubscriptionCache(subscription); }); it('should render', () => { const { container } = render(<ContextCreditsSection />); expect(container).not.toBeEmptyDOMElement(); }); it('should display the number of available credits', () => { const { getByTestId } = render(<ContextCreditsSection />); expect(getByTestId('avalaible-credits')).toHaveTextContent('119.88'); }); it('should render 0 credits if the amount of credits is the same as upcoming subscription price', () => { subscription.UpcomingSubscription = upcoming; const { getByTestId } = render(<ContextCreditsSection />); expect(getByTestId('avalaible-credits')).toHaveTextContent('0'); }); it('should render positive amount of credits if there are more credits than upcoming subscription price', () => { user.User.Credit = 12988; mockUserCache(formatUser(user.User)); subscription.UpcomingSubscription = upcoming; const { getByTestId } = render(<ContextCreditsSection />); expect(getByTestId('avalaible-credits')).toHaveTextContent('10'); }); it('should render 0 if the number of available credits is less than price of upcoming subscription', () => { user.User.Credit = 10000; mockUserCache(formatUser(user.User)); subscription.UpcomingSubscription = upcoming; const { getByTestId } = render(<ContextCreditsSection />); expect(getByTestId('avalaible-credits')).toHaveTextContent('0'); }); it('should render credits as-is if subscription is managed by Chargebee', () => { subscription.External = External.Chargebee; subscription.UpcomingSubscription = upcoming; subscription.UpcomingSubscription!.External = External.Chargebee; user.User.Credit = 12988; mockUserCache(formatUser(user.User)); const { getByTestId } = render(<ContextCreditsSection />); expect(getByTestId('avalaible-credits')).toHaveTextContent('129.88'); }); it('should display loader if subscription is not available', () => { mockSubscriptionCache(null as any); const { getByTestId } = render(<ContextCreditsSection />); expect(getByTestId('circle-loader')).toBeInTheDocument(); }); it('should take into account discount', () => { subscription.UpcomingSubscription = upcoming; subscription.UpcomingSubscription!.Discount = 1988; const { getByTestId } = render(<ContextCreditsSection />); expect(getByTestId('avalaible-credits')).toHaveTextContent('19.88'); });
6,705
0
petrpan-code/ProtonMail/WebClients/packages/components/containers
petrpan-code/ProtonMail/WebClients/packages/components/containers/payments/EditCardModal.test.tsx
import { fireEvent, render, waitFor } from '@testing-library/react'; import { Autopay, CardModel } from '@proton/components/payments/core'; import { updatePaymentMethod } from '@proton/shared/lib/api/payments'; import { apiMock, applyHOCs, withApi, withCache, withDeprecatedModals, withEventManager, withNotifications, } from '@proton/testing'; import EditCardModal from './EditCardModal'; jest.mock('@proton/components/components/portal/Portal'); jest.mock('@proton/components/components/toggle/Toggle'); const defaultCard: CardModel = { number: '', month: '', year: '', cvc: '', zip: '', country: 'US', }; beforeEach(() => { jest.clearAllMocks(); }); const ContextEditCardModal = applyHOCs( withNotifications(), withEventManager(), withApi(), withCache(), withDeprecatedModals() )(EditCardModal); it('should render', () => { const { container } = render(<ContextEditCardModal open={true} />); expect(container).not.toBeEmptyDOMElement(); }); it('should update Autopay and close modal if user edits the existing payment method', async () => { const paymentMethodId = 'paymentMethodId123'; const onClose = jest.fn(); const { getByTestId } = render( <ContextEditCardModal card={defaultCard} renewState={Autopay.DISABLE} paymentMethodId={paymentMethodId} open={true} onClose={onClose} /> ); fireEvent.click(getByTestId('toggle-subscription-renew')); await waitFor(() => { expect(apiMock).toHaveBeenCalledWith(updatePaymentMethod(paymentMethodId, { Autopay: Autopay.ENABLE })); }); await waitFor(() => { expect(onClose).toHaveBeenCalled(); }); }); it('should update Autopay and close modal if user edits the existing payment method (toggle off)', async () => { const paymentMethodId = 'paymentMethodId123'; const onClose = jest.fn(); const { getByTestId } = render( <ContextEditCardModal card={defaultCard} renewState={Autopay.ENABLE} paymentMethodId={paymentMethodId} open={true} onClose={onClose} /> ); fireEvent.click(getByTestId('toggle-subscription-renew')); fireEvent.click(getByTestId('action-disable-autopay')); await waitFor(() => { expect(apiMock).toHaveBeenCalledWith(updatePaymentMethod(paymentMethodId, { Autopay: Autopay.DISABLE })); }); await waitFor(() => { expect(onClose).toHaveBeenCalled(); }); }); it('should not update autopay if this is Add Credit card mode', async () => { const onClose = jest.fn(); const { getByTestId } = render(<ContextEditCardModal open={true} onClose={onClose} />); fireEvent.click(getByTestId('toggle-subscription-renew')); fireEvent.click(getByTestId('action-disable-autopay')); await waitFor(() => {}); expect(apiMock).not.toHaveBeenCalled(); expect(onClose).not.toHaveBeenCalled(); }); it('should toggle back if API returned error', async () => { apiMock.mockRejectedValue(new Error()); const paymentMethodId = 'paymentMethodId123'; const onClose = jest.fn(); const { getByTestId } = render( <ContextEditCardModal card={defaultCard} renewState={Autopay.DISABLE} paymentMethodId={paymentMethodId} open={true} onClose={onClose} /> ); fireEvent.click(getByTestId('toggle-subscription-renew')); await waitFor(() => { expect(apiMock).toHaveBeenCalledWith(updatePaymentMethod(paymentMethodId, { Autopay: Autopay.ENABLE })); }); await waitFor(() => { expect(onClose).not.toHaveBeenCalled(); }); await waitFor(() => { expect(getByTestId('toggle-subscription-renew')).not.toHaveTextContent('CHECKED'); }); }); it('should disable Save button while updating the toggle status', async () => { let resolve!: () => void; const manualPromise = new Promise<void>((innerResolve) => (resolve = innerResolve)); apiMock.mockReturnValue(manualPromise); const paymentMethodId = 'paymentMethodId123'; const onClose = jest.fn(); const { getByTestId } = render( <ContextEditCardModal card={defaultCard} renewState={Autopay.DISABLE} paymentMethodId={paymentMethodId} open={true} onClose={onClose} /> ); fireEvent.click(getByTestId('toggle-subscription-renew')); await waitFor(() => { expect(getByTestId('edit-card-action-save')).toHaveAttribute('disabled'); }); resolve(); await waitFor(() => { expect(getByTestId('edit-card-action-save')).not.toHaveAttribute('disabled'); }); });
6,713
0
petrpan-code/ProtonMail/WebClients/packages/components/containers
petrpan-code/ProtonMail/WebClients/packages/components/containers/payments/PayPalView.test.tsx
import { render } from '@testing-library/react'; import { renderHook } from '@testing-library/react-hooks'; import { usePaypal } from '@proton/components/payments/react-extensions/usePaypal'; import { Currency } from '@proton/shared/lib/interfaces'; import { apiMock, mockVerifyPayment } from '@proton/testing'; import PayPalView from './PayPalView'; const onChargeable = jest.fn(); const onClick = jest.fn(); beforeEach(() => { jest.clearAllMocks(); }); let amountAndCurrency = { Amount: 1000, Currency: 'EUR' as Currency, }; function paypalHook({ isCredit, Amount, Currency, mockVerificationResult, }: { isCredit: boolean; mockVerificationResult?: boolean; Amount: number; Currency: Currency; }) { const verifyPayment = mockVerifyPayment(); if (mockVerificationResult) { verifyPayment.mockVerification(); } return renderHook( ({ amountAndCurrency }) => usePaypal( { amountAndCurrency, onChargeable, isCredit, }, { api: apiMock, verifyPayment: mockVerifyPayment(), } ), { initialProps: { amountAndCurrency: { Amount, Currency, }, }, } ); } it('should render', () => { const { result: paypal } = paypalHook({ isCredit: false, ...amountAndCurrency }); const { result: paypalCredit } = paypalHook({ isCredit: true, ...amountAndCurrency }); const { container } = render( <PayPalView type="credit" paypal={paypal.current} paypalCredit={paypalCredit.current} onClick={onClick} amount={amountAndCurrency.Amount} currency={amountAndCurrency.Currency} /> ); expect(container).not.toBeEmptyDOMElement(); }); it('should render the message of paypal credit and "click here" button', () => { const { result: paypal } = paypalHook({ isCredit: false, ...amountAndCurrency }); const { result: paypalCredit } = paypalHook({ isCredit: true, ...amountAndCurrency }); const { getByText, getByTestId } = render( <PayPalView type="credit" paypal={paypal.current} paypalCredit={paypalCredit.current} onClick={onClick} amount={amountAndCurrency.Amount} currency={amountAndCurrency.Currency} /> ); const message = `You must have a credit card or bank account linked with your PayPal account. If your PayPal account doesn't have that, please click on the button below.`; expect(getByText(message)).toBeInTheDocument(); expect(getByTestId('paypal-credit-button')).toBeInTheDocument(); }); it('should disable the "click here" button when triggers are disabled', () => { const { result: paypal } = paypalHook({ isCredit: false, ...amountAndCurrency }); const { result: paypalCredit } = paypalHook({ isCredit: true, ...amountAndCurrency }); const { getByTestId } = render( <PayPalView type="credit" paypal={paypal.current} paypalCredit={paypalCredit.current} onClick={onClick} amount={amountAndCurrency.Amount} currency={amountAndCurrency.Currency} triggersDisabled={true} /> ); expect(getByTestId('paypal-credit-button')).toBeDisabled(); }); it('should disable the "click here" button when paypal credit is in initial state', () => { const { result: paypal } = paypalHook({ isCredit: false, ...amountAndCurrency }); const { result: paypalCredit } = paypalHook({ isCredit: true, ...amountAndCurrency }); const { getByTestId } = render( <PayPalView type="credit" paypal={paypal.current} paypalCredit={paypalCredit.current} onClick={onClick} amount={amountAndCurrency.Amount} currency={amountAndCurrency.Currency} /> ); expect(getByTestId('paypal-credit-button')).toBeDisabled(); });
6,725
0
petrpan-code/ProtonMail/WebClients/packages/components/containers
petrpan-code/ProtonMail/WebClients/packages/components/containers/payments/RenewToggle.test.tsx
import { fireEvent, render, waitFor } from '@testing-library/react'; import { renderHook } from '@testing-library/react-hooks'; import { mockSubscriptionCache } from '@proton/components/hooks/helpers/test'; import { Autopay } from '@proton/components/payments/core'; import { applyHOCs, hookWrapper, withCache } from '@proton/testing'; import RenewToggle, { useRenewToggle } from './RenewToggle'; jest.mock('@proton/components/components/portal/Portal'); jest.mock('@proton/components/components/toggle/Toggle'); beforeEach(() => { jest.clearAllMocks(); mockSubscriptionCache(); }); const providers = [withCache()]; const ContextRenewToggle = applyHOCs(...providers)(RenewToggle); const wrapper = hookWrapper(...providers); it('should render', () => { const { result } = renderHook(() => useRenewToggle({}), { wrapper }); const { container } = render(<ContextRenewToggle {...result.current} />); expect(container).not.toBeEmptyDOMElement(); }); it('should be checked when RenewState is Active', () => { const { result } = renderHook(() => useRenewToggle({}), { wrapper }); const { getByTestId } = render(<ContextRenewToggle {...result.current} />); expect(getByTestId('toggle-subscription-renew')).toHaveTextContent('CHECKED'); }); it('should be unchecked when RenewState is Disabled', () => { const { result } = renderHook(() => useRenewToggle({ initialRenewState: Autopay.DISABLE }), { wrapper }); const { getByTestId } = render(<ContextRenewToggle {...result.current} />); expect(getByTestId('toggle-subscription-renew')).not.toHaveTextContent('CHECKED'); }); it('should show modal when user disables auto renew', () => { const { result } = renderHook(() => useRenewToggle({}), { wrapper }); const { container, getByTestId, rerender } = render(<ContextRenewToggle {...result.current} />); fireEvent.click(getByTestId('toggle-subscription-renew')); rerender(<ContextRenewToggle {...result.current} />); expect(container).toHaveTextContent('Our system will no longer auto-charge you using this payment method'); }); it('should not toggle off if user clicked Keep auto-pay/Cancel', async () => { const { result, rerender: rerenderHook } = renderHook(() => useRenewToggle({}), { wrapper }); const { getByTestId, rerender, container } = render(<ContextRenewToggle {...result.current} />); fireEvent.click(getByTestId('toggle-subscription-renew')); rerenderHook(); rerender(<ContextRenewToggle {...result.current} />); expect(container).toHaveTextContent('Are you sure?'); fireEvent.click(getByTestId('action-keep-autopay')); await waitFor(() => {}); rerenderHook(); rerender(<ContextRenewToggle {...result.current} />); expect(getByTestId('toggle-subscription-renew')).toHaveTextContent('CHECKED'); }); it('should toggle off if user clicked Disable', async () => { const { result, rerender: rerenderHook } = renderHook(() => useRenewToggle({}), { wrapper }); const { getByTestId, rerender, container } = render(<ContextRenewToggle {...result.current} />); fireEvent.click(getByTestId('toggle-subscription-renew')); rerenderHook(); rerender(<ContextRenewToggle {...result.current} />); expect(container).toHaveTextContent('Are you sure?'); fireEvent.click(getByTestId('action-disable-autopay')); await waitFor(() => {}); rerenderHook(); rerender(<ContextRenewToggle {...result.current} />); await waitFor(() => { expect(getByTestId('toggle-subscription-renew')).not.toHaveTextContent('CHECKED'); }); }); it('should toggle on without modal', async () => { const { result, rerender: rerenderHook } = renderHook( () => useRenewToggle({ initialRenewState: Autopay.DISABLE }), { wrapper } ); const { getByTestId, container, rerender } = render(<ContextRenewToggle {...result.current} />); fireEvent.click(getByTestId('toggle-subscription-renew')); await waitFor(() => {}); rerenderHook(); rerender(<ContextRenewToggle {...result.current} />); expect(container).not.toHaveTextContent('Our system will no longer auto-charge you using this payment method'); expect(getByTestId('toggle-subscription-renew')).toHaveTextContent('CHECKED'); }); describe('useRenewToggle', () => { it('onChange should return ENABLE if toggled on', async () => { const { result } = renderHook(() => useRenewToggle({ initialRenewState: Autopay.DISABLE }), { wrapper }); expect(await result.current.onChange()).toEqual(Autopay.ENABLE); }); it('onChange should return DISABLE if toggled off', async () => { const { result } = renderHook(() => useRenewToggle({ initialRenewState: Autopay.ENABLE }), { wrapper }); const { getByTestId, rerender } = render(<ContextRenewToggle {...result.current} />); const onChangePromise = result.current.onChange(); rerender(<ContextRenewToggle {...result.current} />); fireEvent.click(getByTestId('action-disable-autopay')); expect(await onChangePromise).toEqual(Autopay.DISABLE); }); it('onChange should return null if the checkbox was not toggled off', async () => { const { result } = renderHook(() => useRenewToggle({ initialRenewState: Autopay.ENABLE }), { wrapper }); const { getByTestId, rerender } = render(<ContextRenewToggle {...result.current} />); const onChangePromise = result.current.onChange(); rerender(<ContextRenewToggle {...result.current} />); fireEvent.click(getByTestId('action-keep-autopay')); expect(await onChangePromise).toEqual(null); }); });
6,727
0
petrpan-code/ProtonMail/WebClients/packages/components/containers
petrpan-code/ProtonMail/WebClients/packages/components/containers/payments/RenewalNotice.test.tsx
import { render } from '@testing-library/react'; import { getRenewalNoticeText } from './RenewalNotice'; const RenewalNotice = (...props: Parameters<typeof getRenewalNoticeText>) => { return <div>{getRenewalNoticeText(...props)}</div>; }; describe('<RenewalNotice />', () => { beforeEach(() => { jest.clearAllMocks(); jest.useFakeTimers(); }); afterEach(() => { jest.useRealTimers(); }); it('should render', () => { const { container } = render( <RenewalNotice renewCycle={12} isCustomBilling={false} isScheduledSubscription={false} subscription={undefined} /> ); expect(container).not.toBeEmptyDOMElement(); }); it('should display the correct renewal date', () => { const mockedDate = new Date(2023, 10, 1); jest.setSystemTime(mockedDate); const renewCycle = 12; const expectedDateString = '11/01/2024'; // because months are 0-indexed ¯\_(ツ)_/¯ const { container } = render( <RenewalNotice renewCycle={renewCycle} isCustomBilling={false} isScheduledSubscription={false} subscription={undefined} /> ); expect(container).toHaveTextContent( `Subscription auto-renews every 12 months. Your next billing date is ${expectedDateString}.` ); }); it('should use period end date if custom billing is enabled', () => { const mockedDate = new Date(2023, 10, 1); jest.setSystemTime(mockedDate); const renewCycle = 12; const expectedDateString = '08/11/2025'; // because months are 0-indexed ¯\_(ツ)_/¯ const { container } = render( <RenewalNotice renewCycle={renewCycle} isCustomBilling={true} isScheduledSubscription={false} subscription={ { // the backend returns seconds, not milliseconds PeriodEnd: +new Date(2025, 7, 11) / 1000, } as any } /> ); expect(container).toHaveTextContent( `Subscription auto-renews every 12 months. Your next billing date is ${expectedDateString}.` ); }); it('should use the end of upcoming subscription period if scheduled subscription is enabled', () => { const mockedDate = new Date(2023, 10, 1); jest.setSystemTime(mockedDate); const renewCycle = 24; // the upcoming subscription takes another 24 months const { container } = render( <RenewalNotice renewCycle={renewCycle} isCustomBilling={false} isScheduledSubscription={true} subscription={ { // the backend returns seconds, not milliseconds PeriodEnd: +new Date(2024, 1, 3) / 1000, // the current subscription period ends on 02/03/2024 (3rd of February 2024) } as any } /> ); const expectedDateString = '02/03/2026'; // and finally the renewal date is 02/03/2026 (3rd of February 2026) expect(container).toHaveTextContent( `Subscription auto-renews every 24 months. Your next billing date is ${expectedDateString}.` ); }); });
6,732
0
petrpan-code/ProtonMail/WebClients/packages/components/containers
petrpan-code/ProtonMail/WebClients/packages/components/containers/payments/SubscriptionsSection.test.tsx
import { render } from '@testing-library/react'; import { mockPlansCache, mockSubscriptionCache, mockUserCache } from '@proton/components/hooks/helpers/test'; import { changeRenewState } from '@proton/shared/lib/api/payments'; import { PLANS } from '@proton/shared/lib/constants'; import { Renew, Subscription, SubscriptionModel } from '@proton/shared/lib/interfaces'; import { apiMock, applyHOCs, withApi, withCache, withEventManager } from '@proton/testing/index'; import SubscriptionsSection from './SubscriptionsSection'; const ContextSubscriptionSection = applyHOCs(withEventManager(), withApi(), withCache())(SubscriptionsSection); describe('SubscriptionsSection', () => { let subscription: SubscriptionModel; let upcoming: Subscription | null = null; beforeEach(() => { subscription = { ID: '123', InvoiceID: '1234', Cycle: 1, PeriodStart: 1696561158, PeriodEnd: 1699239558, CreateTime: 1696561161, CouponCode: null, Currency: 'CHF', Amount: 1299, Discount: 0, RenewAmount: 1299, Plans: [ { ID: '1', Type: 1, Name: PLANS.BUNDLE, Title: 'Proton Unlimited', MaxDomains: 3, MaxAddresses: 15, MaxCalendars: 25, MaxSpace: 536870912000, MaxMembers: 1, MaxVPN: 10, MaxTier: 2, Services: 15, Features: 1, State: 1, Cycle: 1, Currency: 'CHF', Amount: 1299, Offers: [], Quantity: 1, Pricing: { 1: 1299, 12: 11988, 24: 19176, }, }, ], Renew: 1, External: 0, UpcomingSubscription: null, isManagedByMozilla: false, }; upcoming = { ID: '124', InvoiceID: null as any, Cycle: 12, PeriodStart: 1699239558, PeriodEnd: 1730861958, CreateTime: 1696561195, CouponCode: null, Currency: 'CHF', Amount: 11988, Discount: 0, RenewAmount: 11988, Plans: [ { ID: '1', Type: 1, Name: PLANS.BUNDLE, Title: 'Proton Unlimited', MaxDomains: 3, MaxAddresses: 15, MaxCalendars: 25, MaxSpace: 536870912000, MaxMembers: 1, MaxVPN: 10, MaxTier: 2, Services: 15, Features: 1, State: 1, Cycle: 12, Currency: 'CHF', Amount: 11988, Quantity: 1, Offers: [], Pricing: { 1: 1299, 12: 11988, 24: 19176, }, }, ], Renew: 1, External: 0, }; jest.clearAllMocks(); mockUserCache(); mockPlansCache(); mockSubscriptionCache(subscription); }); it('should return MozillaInfoPanel if isManagedByMozilla is true', () => { subscription.isManagedByMozilla = true; const { container } = render(<ContextSubscriptionSection />); expect(container).toHaveTextContent('Your subscription is managed by Mozilla'); }); it('should render current subscription', () => { const { getByTestId } = render(<ContextSubscriptionSection />); expect(getByTestId('planNameId')).toHaveTextContent('Proton Unlimited'); expect(getByTestId('subscriptionStatusId')).toHaveTextContent('Active'); expect(getByTestId('planEndTimeId')).toHaveTextContent('Nov 6, 2023'); }); it('should display Expiring badge if renew is disabled', () => { subscription.Renew = Renew.Disabled; const { getByTestId } = render(<ContextSubscriptionSection />); expect(getByTestId('planNameId')).toHaveTextContent('Proton Unlimited'); expect(getByTestId('subscriptionStatusId')).toHaveTextContent('Expiring'); expect(getByTestId('planEndTimeId')).toHaveTextContent('Nov 6, 2023'); }); it('should render end date of upcoming subscription', () => { subscription.UpcomingSubscription = upcoming; const { getByTestId } = render(<ContextSubscriptionSection />); expect(getByTestId('planNameId')).toHaveTextContent('Proton Unlimited'); expect(getByTestId('subscriptionStatusId')).toHaveTextContent('Active'); expect(getByTestId('planEndTimeId')).toHaveTextContent('Nov 6, 2024'); }); it('should show renewal notice if there is no upcoming subscription', () => { const { getByTestId } = render(<ContextSubscriptionSection />); expect(getByTestId('renewalNotice')).toHaveTextContent('Renews automatically at CHF 12.99, for 1 month'); }); it('should show renewal notice if there is upcoming subscription', () => { subscription.UpcomingSubscription = upcoming; const { getByTestId } = render(<ContextSubscriptionSection />); expect(getByTestId('renewalNotice')).toHaveTextContent('Renews automatically at CHF 119.88, for 12 months'); }); it('should now show renewal notice if subscription is expiring', () => { subscription.Renew = Renew.Disabled; const { container } = render(<ContextSubscriptionSection />); expect(container).not.toHaveTextContent('Renews automatically'); }); it('should display Reactivate button when Renew is disabled', () => { subscription.Renew = Renew.Disabled; const { getByText } = render(<ContextSubscriptionSection />); expect(getByText('Reactivate')).toBeInTheDocument(); }); it('should display warning icon when renewal is disabled', () => { subscription.Renew = Renew.Disabled; const { queryByTestId } = render(<ContextSubscriptionSection />); expect(queryByTestId('periodEndWarning')).toBeInTheDocument(); }); it('should not display date of upcoming subscription if renew is disabled', () => { subscription.Renew = Renew.Disabled; subscription.UpcomingSubscription = upcoming; const { container } = render(<ContextSubscriptionSection />); expect(container).not.toHaveTextContent('Upcoming'); }); it('should call API when user presses reactivate button', () => { subscription.Renew = Renew.Disabled; const { getByText } = render(<ContextSubscriptionSection />); getByText('Reactivate').click(); expect(apiMock).toHaveBeenCalledWith( changeRenewState({ RenewalState: Renew.Enabled, }) ); }); });
6,736
0
petrpan-code/ProtonMail/WebClients/packages/components/containers
petrpan-code/ProtonMail/WebClients/packages/components/containers/payments/useBitcoin.test.tsx
import { renderHook } from '@testing-library/react-hooks'; import { AmountAndCurrency, PAYMENT_TOKEN_STATUS } from '@proton/components/payments/core'; import { createToken, getTokenStatus } from '@proton/shared/lib/api/payments'; import { MAX_BITCOIN_AMOUNT } from '@proton/shared/lib/constants'; import { addApiMock, addApiResolver, apiMock, flushPromises } from '@proton/testing/index'; import useBitcoin, { BITCOIN_POLLING_INTERVAL } from './useBitcoin'; const onTokenValidated = jest.fn(); const onAwaitingPayment = jest.fn(); beforeEach(() => { jest.clearAllMocks(); }); it('should render', () => { const amountAndCurrency: AmountAndCurrency = { Amount: 1000, Currency: 'EUR', }; const { result } = renderHook(() => useBitcoin({ api: apiMock, onTokenValidated, onAwaitingPayment, enablePolling: true, ...amountAndCurrency, }) ); expect(result.current).toBeDefined(); }); it('should request the token', async () => { const amountAndCurrency: AmountAndCurrency = { Amount: 1000, Currency: 'EUR', }; const { result } = renderHook(() => useBitcoin({ api: apiMock, onTokenValidated, onAwaitingPayment, enablePolling: true, ...amountAndCurrency, }) ); await result.current.request(); jest.runAllTicks(); expect(apiMock).toHaveBeenCalledTimes(1); }); it('should not request the token automatically', () => { const amountAndCurrency: AmountAndCurrency = { Amount: 1000, Currency: 'EUR', }; const { rerender } = renderHook( ({ amountAndCurrency }) => useBitcoin({ api: apiMock, onTokenValidated, onAwaitingPayment, enablePolling: true, ...amountAndCurrency, }), { initialProps: { amountAndCurrency, }, } ); expect(apiMock).toHaveBeenCalledTimes(0); rerender({ amountAndCurrency: { Amount: 2000, Currency: 'USD', }, }); expect(apiMock).toHaveBeenCalledTimes(0); }); it('should not request the token if the amount is too low', async () => { const amountAndCurrency: AmountAndCurrency = { Amount: 100, Currency: 'EUR', }; const { result } = renderHook(() => useBitcoin({ api: apiMock, onTokenValidated, onAwaitingPayment, enablePolling: true, ...amountAndCurrency, }) ); await result.current.request(); expect(apiMock).toHaveBeenCalledTimes(0); }); it('should not request the token if the amount is too high', async () => { const amountAndCurrency: AmountAndCurrency = { Amount: MAX_BITCOIN_AMOUNT + 1000, Currency: 'EUR', }; const { result } = renderHook(() => useBitcoin({ api: apiMock, onTokenValidated, onAwaitingPayment, enablePolling: true, ...amountAndCurrency, }) ); await result.current.request(); expect(apiMock).toHaveBeenCalledTimes(0); }); describe('', () => { beforeEach(() => { jest.clearAllMocks(); jest.useFakeTimers(); }); afterEach(() => { jest.useRealTimers(); }); it('should not request if the token exists and amount and currency are the same', async () => { const amountAndCurrency: AmountAndCurrency = { Amount: 1000, Currency: 'EUR', }; addApiMock(createToken({} as any).url, () => ({ Code: 1000, Token: 'Token-12345', Status: 0, Data: { CoinAddress: 'some-btc-address', CoinAmount: 0.000789, CoinType: 6, CoinAddressReused: false, }, })); const { result } = renderHook(() => useBitcoin({ api: apiMock, onTokenValidated, onAwaitingPayment, enablePolling: true, ...amountAndCurrency, }) ); await result.current.request(); jest.runAllTicks(); expect(apiMock).toHaveBeenCalledTimes(1); await result.current.request(); jest.runAllTicks(); expect(apiMock).toHaveBeenCalledTimes(1); }); it('should stop polling when enablePolling is set to false', async () => { const amountAndCurrency: AmountAndCurrency = { Amount: 1000, Currency: 'EUR', }; addApiMock(createToken({} as any).url, () => ({ Code: 1000, Token: 'Token-12345', Status: 0, Data: { CoinAddress: 'some-btc-address', CoinAmount: 0.000789, CoinType: 6, CoinAddressReused: false, }, })); addApiMock(getTokenStatus('Token-12345').url, () => ({ Code: 1000, Status: PAYMENT_TOKEN_STATUS.STATUS_PENDING, })); const { result, rerender } = renderHook( ({ enablePolling }) => useBitcoin({ api: apiMock, onTokenValidated, onAwaitingPayment, enablePolling, ...amountAndCurrency, }), { initialProps: { enablePolling: true, }, } ); await result.current.request(); expect(apiMock).toHaveBeenCalledTimes(1); // getting the token jest.advanceTimersByTime(BITCOIN_POLLING_INTERVAL); await flushPromises(); expect(apiMock).toHaveBeenCalledTimes(2); // checking the token for the first time rerender({ enablePolling: false, }); jest.advanceTimersByTime(BITCOIN_POLLING_INTERVAL); await flushPromises(); expect(apiMock).toHaveBeenCalledTimes(2); // checking the token for the second time must not happen after polling was disabled jest.advanceTimersByTime(BITCOIN_POLLING_INTERVAL); await flushPromises(); expect(apiMock).toHaveBeenCalledTimes(2); // checking the token for the second time must not happen after polling was disabled }); it('should stop polling when the token is invalid', async () => { const amountAndCurrency: AmountAndCurrency = { Amount: 1000, Currency: 'EUR', }; addApiMock(createToken({} as any).url, () => ({ Code: 1000, Token: 'Token-12345', Status: 0, Data: { CoinAddress: 'some-btc-address', CoinAmount: 0.000789, CoinType: 6, CoinAddressReused: false, }, })); let resolvers: ReturnType<typeof addApiResolver>; const updateResolvers = () => { resolvers = addApiResolver(getTokenStatus('Token-12345').url); }; updateResolvers(); const resolveToken = () => resolvers.resolve({ Code: 1000, Status: PAYMENT_TOKEN_STATUS.STATUS_PENDING, }); const rejectToken = () => resolvers.reject({ status: 400, }); const { result } = renderHook( ({ enablePolling }) => useBitcoin({ api: apiMock, onTokenValidated, onAwaitingPayment, enablePolling, ...amountAndCurrency, }), { initialProps: { enablePolling: true, }, } ); await result.current.request(); expect(apiMock).toHaveBeenCalledTimes(1); // getting the token updateResolvers(); await jest.advanceTimersByTimeAsync(BITCOIN_POLLING_INTERVAL); resolveToken(); expect(apiMock).toHaveBeenCalledTimes(2); // checking the token for the first time updateResolvers(); await jest.advanceTimersByTimeAsync(BITCOIN_POLLING_INTERVAL); rejectToken(); expect(apiMock).toHaveBeenCalledTimes(3); // checking the token for the second time updateResolvers(); await jest.advanceTimersByTimeAsync(BITCOIN_POLLING_INTERVAL); resolveToken(); // because of the rejection last time, the next call should never happen, the script must exit from the loop expect(apiMock).toHaveBeenCalledTimes(3); }); });
6,754
0
petrpan-code/ProtonMail/WebClients/packages/components/containers/payments
petrpan-code/ProtonMail/WebClients/packages/components/containers/payments/subscription/InAppPurchaseModal.test.tsx
import { act, fireEvent, render } from '@testing-library/react'; import { External } from '@proton/shared/lib/interfaces'; import InAppPurchaseModal from './InAppPurchaseModal'; jest.mock('@proton/components/components/portal/Portal'); it('should render', () => { const { container } = render( <InAppPurchaseModal open={true} subscription={{ External: External.Android } as any} onClose={() => {}} /> ); expect(container).not.toBeEmptyDOMElement(); }); it('should trigger onClose when user presses the button', async () => { const onClose = jest.fn(); const { getByTestId } = render( <InAppPurchaseModal onClose={onClose} open={true} subscription={{ External: External.Android } as any} /> ); await act(async () => { fireEvent.click(getByTestId('InAppPurchaseModal/onClose')); }); expect(onClose).toHaveBeenCalled(); }); it('should render iOS text if subscription is managed by Apple', async () => { const { container } = render( <InAppPurchaseModal onClose={() => {}} open={true} subscription={{ External: External.iOS } as any} /> ); expect(container).toHaveTextContent('Apple App Store'); expect(container).not.toHaveTextContent('Google'); expect(container).not.toHaveTextContent('Google Play'); }); it('should immediately close if subscription is not managed externally', () => { const onClose = jest.fn(); const { container } = render( <InAppPurchaseModal onClose={onClose} open={true} subscription={{ External: External.Default } as any} /> ); expect(onClose).toHaveBeenCalled(); expect(container).toBeEmptyDOMElement(); });
6,763
0
petrpan-code/ProtonMail/WebClients/packages/components/containers/payments
petrpan-code/ProtonMail/WebClients/packages/components/containers/payments/subscription/PlanSelection.test.tsx
import { ADDON_NAMES, CYCLE, PLANS } from '@proton/shared/lib/constants'; import { Plan } from '@proton/shared/lib/interfaces'; import { PLANS_MAP } from '@proton/testing/data'; import { getPrice } from './PlanSelection'; describe('getPrice', () => { it('should return null if the current plan does not have pricing for the celected cycle', () => { const plan = PLANS_MAP[PLANS.VPN_PRO] as Plan; expect(getPrice(plan, CYCLE.THIRTY, PLANS_MAP)).toBeNull(); }); it('should return cycle price for the current plan', () => { const plan = PLANS_MAP[PLANS.FAMILY] as Plan; expect(getPrice(plan, CYCLE.TWO_YEARS, PLANS_MAP)).toBe(plan.Pricing[CYCLE.TWO_YEARS]); }); it.each([ [PLANS.VPN_PRO, ADDON_NAMES.MEMBER_VPN_PRO], [PLANS.VPN_BUSINESS, ADDON_NAMES.MEMBER_VPN_BUSINESS], ])('should return member addon cycle price for the selected plans: %s', (planName, addonName) => { const plan = PLANS_MAP[planName] as Plan; const addon = PLANS_MAP[addonName] as Plan; expect(getPrice(plan, CYCLE.TWO_YEARS, PLANS_MAP)).toBe(addon.Pricing[CYCLE.TWO_YEARS]); }); it('should return the plan pricing if the addon is not available', () => { const plan = PLANS_MAP[PLANS.VPN_PRO] as Plan; const plansMap = { ...PLANS_MAP, [ADDON_NAMES.MEMBER_VPN_PRO]: undefined, }; expect(getPrice(plan, CYCLE.TWO_YEARS, plansMap)).toBe(plan.Pricing[CYCLE.TWO_YEARS]); }); });
6,768
0
petrpan-code/ProtonMail/WebClients/packages/components/containers/payments
petrpan-code/ProtonMail/WebClients/packages/components/containers/payments/subscription/SubscriptionContainer.test.tsx
import { fireEvent, render, waitFor } from '@testing-library/react'; import { defaultSubscriptionCache, mockOrganizationApi, mockPlansCache, mockSubscriptionCache, mockUserCache, mockUserVPNServersCountApi, organizationDefaultResponse, plansDefaultResponse, } from '@proton/components/hooks/helpers/test'; import { createToken, subscribe } from '@proton/shared/lib/api/payments'; import { ADDON_NAMES, PLANS } from '@proton/shared/lib/constants'; import { Audience, Organization, Plan } from '@proton/shared/lib/interfaces'; import { apiMock, applyHOCs, withApi, withAuthentication, withCache, withConfig, withDeprecatedModals, withEventManager, withFeatures, withNotifications, } from '@proton/testing/index'; import SubscriptionContainer, { SubscriptionContainerProps } from './SubscriptionContainer'; import { SUBSCRIPTION_STEPS } from './constants'; jest.mock('@proton/components/components/portal/Portal'); const ContextSubscriptionContainer = applyHOCs( withConfig(), withNotifications(), withEventManager(), withApi(), withCache(), withDeprecatedModals(), withFeatures(), withAuthentication() )(SubscriptionContainer); describe('SubscriptionContainer', () => { let props: SubscriptionContainerProps; beforeEach(() => { jest.clearAllMocks(); mockUserCache(); mockPlansCache(); mockSubscriptionCache(); mockUserVPNServersCountApi(); mockOrganizationApi(); }); beforeEach(() => { props = { app: 'proton-mail', defaultSelectedProductPlans: { [Audience.B2C]: PLANS.MAIL, [Audience.B2B]: PLANS.MAIL_PRO, [Audience.FAMILY]: PLANS.FAMILY, }, metrics: { source: 'dashboard', }, render: ({ onSubmit, title, content, footer }) => { return ( <form onSubmit={onSubmit}> <div>{title}</div> <div>{content}</div> <div>{footer}</div> </form> ); }, subscription: defaultSubscriptionCache, organization: organizationDefaultResponse.Organization as any as Organization, plans: plansDefaultResponse.Plans as any as Plan[], }; }); it('should render', () => { const { container } = render(<ContextSubscriptionContainer {...props} />); expect(container).not.toBeEmptyDOMElement(); }); it('should redirect user without supported addons directly to checkout step', async () => { props.step = SUBSCRIPTION_STEPS.CUSTOMIZATION; const { container } = render(<ContextSubscriptionContainer {...props} />); await waitFor(() => { expect(container).toHaveTextContent('Review subscription and pay'); }); // that's text from one of the branches of <Payment> component // depending on the specific test setup, you might need to change this text in the test. // The key idea is to ensure that the Payment component was rendered, and no matter what's exactly inside. // I could mock the Payment component, but I wanted to test the whole flow. await waitFor(() => { expect(container).toHaveTextContent('The minimum payment we accept is'); }); }); it('should render customization step', async () => { props.step = SUBSCRIPTION_STEPS.CUSTOMIZATION; props.planIDs = { [PLANS.MAIL_PRO]: 1, }; const { container } = render(<ContextSubscriptionContainer {...props} />); await waitFor(() => { expect(container).toHaveTextContent('Customize your plan'); }); }); it('should not proceed to the checkout step after customization if there was a check error', async () => { props.step = SUBSCRIPTION_STEPS.CUSTOMIZATION; props.planIDs = { [PLANS.MAIL_PRO]: 1, [ADDON_NAMES.MEMBER]: 329 }; // user with 330 users in the organization const { findByTestId, container } = render(<ContextSubscriptionContainer {...props} />); const continueButton = await findByTestId('continue-to-review'); apiMock.mockClear(); apiMock.mockRejectedValueOnce(new Error()); fireEvent.click(continueButton); await waitFor(() => {}); expect(apiMock).toHaveBeenCalledTimes(1); expect(container).toHaveTextContent('Customize your plan'); }); it.skip('should not create payment token if the amount is 0', async () => { props.step = SUBSCRIPTION_STEPS.CHECKOUT; props.planIDs = { mail2022: 1 }; const { container } = render(<ContextSubscriptionContainer {...props} />); let form: HTMLFormElement | null = null; await waitFor(() => { form = container.querySelector('form'); expect(form).not.toBeEmptyDOMElement(); }); if (!form) { throw new Error('Form not found'); } fireEvent.submit(form); const createTokenUrl = createToken({} as any).url; const subscribeUrl = subscribe({} as any, '' as any).url; await waitFor(() => {}); expect(apiMock).not.toHaveBeenCalledWith(expect.objectContaining({ url: createTokenUrl })); await waitFor(() => { expect(apiMock).toHaveBeenCalledWith( expect.objectContaining({ url: subscribeUrl, data: expect.objectContaining({ Amount: 0, }), }) ); }); }); });
6,770
0
petrpan-code/ProtonMail/WebClients/packages/components/containers/payments
petrpan-code/ProtonMail/WebClients/packages/components/containers/payments/subscription/SubscriptionCycleSelector.test.tsx
import { render } from '@testing-library/react'; import { CYCLE, PLANS } from '@proton/shared/lib/constants'; import SubscriptionCycleSelector, { Props } from './SubscriptionCycleSelector'; let props: Props; beforeEach(() => { props = { onChangeCycle: jest.fn(), mode: 'buttons', currency: 'CHF', cycle: CYCLE.TWO_YEARS, minimumCycle: CYCLE.MONTHLY, planIDs: { mail2022: 1, }, plansMap: { mail2022: { ID: 'l8vWAXHBQmv0u7OVtPbcqMa4iwQaBqowINSQjPrxAr-Da8fVPKUkUcqAq30_BCxj1X0nW70HQRmAa-rIvzmKUA==', Type: 1, Name: PLANS.PLUS, Title: 'Mail Plus', MaxDomains: 1, MaxAddresses: 10, MaxCalendars: 25, MaxSpace: 16106127360, MaxMembers: 1, MaxVPN: 0, MaxTier: 0, Services: 1, Features: 1, State: 1, Pricing: { '1': 499, '12': 4788, '24': 8376, }, DefaultPricing: { '1': 499, '12': 4788, '24': 8376, }, Currency: 'CHF', Quantity: 1, Offers: [], Cycle: 1, Amount: 499, }, }, }; }); it('should render', () => { const { container } = render(<SubscriptionCycleSelector {...props} />); expect(container).not.toBeEmptyDOMElement(); }); it('should correctly display price per month', () => { const { queryByTestId } = render(<SubscriptionCycleSelector {...props} />); expect(queryByTestId('price-per-user-per-month-1')).toHaveTextContent('CHF 4.99/month'); expect(queryByTestId('price-per-user-per-month-12')).toHaveTextContent('CHF 3.99/month'); expect(queryByTestId('price-per-user-per-month-24')).toHaveTextContent('CHF 3.49/month'); }); it('should correctly display price per user per month', () => { const planIDs = { mailpro2022: 1, '1member-mailpro2022': 3, }; const plansMap = { mailpro2022: { ID: 'BKiAUbkGnUPiy2c3b0sBCK557OBnWD7ACqqX3VPoZqOOyeMdupoWcjrPDBHy3ANfFKHnJs6qdQrdvHj7zjon_g==', Type: 1, Name: 'mailpro2022', Title: 'Mail Essentials', MaxDomains: 3, MaxAddresses: 10, MaxCalendars: 25, MaxSpace: 16106127360, MaxMembers: 1, MaxVPN: 0, MaxTier: 0, Services: 1, Features: 1, State: 1, Pricing: { '1': 799, '12': 8388, '24': 15576, }, DefaultPricing: { '1': 799, '12': 8388, '24': 15576, }, PeriodEnd: { '1': 1693576305, '12': 1722520305, '24': 1754056305, }, Currency: 'CHF', Quantity: 1, Offers: [], Cycle: 1, Amount: 799, }, '1member-mailpro2022': { ID: 'FK4MKKIVJqOC9Pg_sAxCjNWf8PM9yGzrXO3eXq8sk5RJB6HtaRBNUEcnvJBrQVPAtrDSoTNq4Du3FpqIxyMhHQ==', Type: 0, Name: '1member-mailpro2022', Title: '+1 User', MaxDomains: 0, MaxAddresses: 10, MaxCalendars: 25, MaxSpace: 16106127360, MaxMembers: 1, MaxVPN: 0, MaxTier: 0, Services: 1, Features: 0, State: 1, Pricing: { '1': 799, '12': 8388, '24': 15576, }, DefaultPricing: { '1': 799, '12': 8388, '24': 15576, }, PeriodEnd: { '1': 1693576305, '12': 1722520305, '24': 1754056305, }, Currency: 'CHF', Quantity: 1, Offers: [], Cycle: 1, Amount: 799, }, }; const { queryByTestId } = render( <SubscriptionCycleSelector {...props} plansMap={plansMap as any} planIDs={planIDs} /> ); expect(queryByTestId('price-per-user-per-month-1')).toHaveTextContent('CHF 7.99/user per month'); expect(queryByTestId('price-per-user-per-month-12')).toHaveTextContent('CHF 6.99/user per month'); expect(queryByTestId('price-per-user-per-month-24')).toHaveTextContent('CHF 6.49/user per month'); }); it('should correctly display price per user per month when there are non-user addons', () => { const planIDs = { bundlepro2022: 1, '1domain-bundlepro2022': 12, '1member-bundlepro2022': 8, }; const plansMap = { bundlepro2022: { ID: 'q6fRrEIn0nyJBE_-YSIiVf80M2VZhOuUHW5In4heCyOdV_nGibV38tK76fPKm7lTHQLcDiZtEblk0t55wbuw4w==', Type: 1, Name: 'bundlepro2022', Title: 'Business', MaxDomains: 10, MaxAddresses: 15, MaxCalendars: 25, MaxSpace: 536870912000, MaxMembers: 1, MaxVPN: 10, MaxTier: 2, Services: 15, Features: 1, State: 1, Pricing: { '1': 1299, '12': 13188, '24': 23976, }, DefaultPricing: { '1': 1299, '12': 13188, '24': 23976, }, PeriodEnd: { '1': 1693576305, '12': 1722520305, '24': 1754056305, }, Currency: 'CHF', Quantity: 1, Offers: [], Cycle: 1, Amount: 1299, }, '1domain-bundlepro2022': { ID: '39hry1jlHiPzhXRXrWjfS6t3fqA14QbYfrbF30l2PYYWOhVpyJ33nhujM4z4SHtfuQqTx6e7oSQokrqhLMD8LQ==', Type: 0, Name: '1domain-bundlepro2022', Title: '+1 Domain for Business', MaxDomains: 1, MaxAddresses: 0, MaxCalendars: 0, MaxSpace: 0, MaxMembers: 0, MaxVPN: 0, MaxTier: 0, Services: 15, Features: 0, State: 1, Pricing: { '1': 150, '12': 1680, '24': 3120, }, DefaultPricing: { '1': 150, '12': 1680, '24': 3120, }, PeriodEnd: { '1': 1693576305, '12': 1722520305, '24': 1754056305, }, Currency: 'CHF', Quantity: 1, Offers: [], Cycle: 1, Amount: 150, }, '1member-bundlepro2022': { ID: '0WjWEbOmKh7F2a1Snx2FJKA7a3Fm05p-nIZ0TqiHjDDUa6oHnsyWeeVXgSuzumCmFE8_asJsom9ZzGbx-eDecw==', Type: 0, Name: '1member-bundlepro2022', Title: '+1 User for Business', MaxDomains: 0, MaxAddresses: 15, MaxCalendars: 25, MaxSpace: 536870912000, MaxMembers: 1, MaxVPN: 10, MaxTier: 0, Services: 15, Features: 0, State: 1, Pricing: { '1': 1299, '12': 13188, '24': 23976, }, DefaultPricing: { '1': 1299, '12': 13188, '24': 23976, }, PeriodEnd: { '1': 1693576305, '12': 1722520305, '24': 1754056305, }, Currency: 'CHF', Quantity: 1, Offers: [], Cycle: 1, Amount: 1299, }, }; props = { ...props, planIDs, plansMap: plansMap as any, }; const { queryByTestId } = render(<SubscriptionCycleSelector {...props} />); expect(queryByTestId('price-per-user-per-month-1')).toHaveTextContent('CHF 12.99/user per month'); expect(queryByTestId('price-per-user-per-month-12')).toHaveTextContent('CHF 10.99/user per month'); expect(queryByTestId('price-per-user-per-month-24')).toHaveTextContent('CHF 9.99/user per month'); }); it('should display the prices correctly for VPN Plus', () => { const planIDs = { vpn2022: 1, }; const plansMap = { vpn2022: { ID: 'pIJGEYyNFsPEb61otAc47_X8eoSeAfMSokny6dmg3jg2JrcdohiRuWSN2i1rgnkEnZmolVx4Np96IcwxJh1WNw==', ParentMetaPlanID: 'hUcV0_EeNwUmXA6EoyNrtO-ZTD8H8F6LvNaSjMaPxB5ecFkA7y-5kc3q38cGumJENGHjtSoUndkYFUx0_xlJeg==', Type: 1, Name: 'vpn2022', Title: 'VPN Plus', MaxDomains: 0, MaxAddresses: 0, MaxCalendars: 0, MaxSpace: 0, MaxMembers: 0, MaxVPN: 10, MaxTier: 2, Services: 4, Features: 0, State: 1, Pricing: { '1': 1149, '12': 7188, '15': 14985, '24': 11976, '30': 29970, }, DefaultPricing: { '1': 1149, '12': 7188, '15': 14985, '24': 11976, '30': 29970, }, PeriodEnd: { '1': 1693583725, '12': 1722527725, '15': 1730476525, '24': 1754063725, '30': 1769961325, }, Currency: 'CHF', Quantity: 1, Offers: [], Cycle: 1, Amount: 1149, Vendors: { Google: { Plans: { '12': 'giapaccount_vpn2022_12_renewing', }, CustomerID: 'cus_google_CpVjQymENRYZmBtWQMDw', }, Apple: { Plans: { '12': 'iosaccount_vpn2022_12_usd_non_renewing', }, CustomerID: '', }, }, }, }; props = { ...props, planIDs, plansMap: plansMap as any, }; const { queryByTestId } = render(<SubscriptionCycleSelector {...props} />); expect(queryByTestId('price-per-user-per-month-1')).toHaveTextContent('CHF 11.49/month'); expect(queryByTestId('price-per-user-per-month-12')).toHaveTextContent('CHF 5.99/month'); expect(queryByTestId('price-per-user-per-month-24')).toHaveTextContent('CHF 4.99/month'); });
6,773
0
petrpan-code/ProtonMail/WebClients/packages/components/containers/payments
petrpan-code/ProtonMail/WebClients/packages/components/containers/payments/subscription/SubscriptionModalProvider.test.tsx
import { render, waitFor } from '@testing-library/react'; import cloneDeep from 'lodash/cloneDeep'; import { mockOrganizationApi, mockPlansApi, mockSubscriptionApi, mockUserCache, subscriptionDefaultResponse, } from '@proton/components/hooks/helpers/test'; import { PLANS } from '@proton/shared/lib/constants'; import { Audience, External } from '@proton/shared/lib/interfaces'; import { apiMock, mockCache } from '@proton/testing'; import ApiContext from '../../api/apiContext'; import { CacheProvider } from '../../cache'; import EventManagerContext from '../../eventManager/context'; import SubscriptionContainer from './SubscriptionContainer'; import SubscriptionModalProvider, { OpenSubscriptionModalCallback, useSubscriptionModal, } from './SubscriptionModalProvider'; jest.mock('@proton/components/hooks/useModals'); jest.mock('@proton/components/components/portal/Portal'); jest.mock('@proton/components/containers/payments/subscription/SubscriptionContainer'); jest.mock('@proton/components/hooks/useFeature', () => () => ({})); beforeEach(() => { mockUserCache(); mockSubscriptionApi(); mockOrganizationApi(); mockPlansApi(); }); const defaultEventManager = { call: jest.fn() }; const Providers = ({ children, eventManager = defaultEventManager, api = apiMock, cache = mockCache }: any) => { return ( <EventManagerContext.Provider value={eventManager}> <ApiContext.Provider value={api}> <CacheProvider cache={cache}>{children}</CacheProvider> </ApiContext.Provider> </EventManagerContext.Provider> ); }; it('should render', async () => { const { container } = render( <Providers> <SubscriptionModalProvider app="proton-account">My content</SubscriptionModalProvider> </Providers> ); await waitFor(() => { expect(container).toHaveTextContent('My content'); }); }); it('should render <SubscriptionModalDisabled> if there are legacy plans', async () => { const subscription = cloneDeep(subscriptionDefaultResponse); subscription.Subscription.Plans = [ { Name: PLANS.VPNBASIC, // that's a legacy plan } as any, ]; mockSubscriptionApi(subscription); let openSubscriptionModal!: OpenSubscriptionModalCallback; const ContextReaderComponent = () => { const modal = useSubscriptionModal(); openSubscriptionModal = modal[0]; return null; }; const { container } = render( <Providers> <SubscriptionModalProvider app="proton-account"> <ContextReaderComponent /> </SubscriptionModalProvider> </Providers> ); await waitFor(() => { expect(openSubscriptionModal).toBeDefined(); }); openSubscriptionModal({} as any); expect(container).toHaveTextContent('We’re upgrading your current plan to an improved plan'); }); it('should render <SubscriptionContainer> if there is no legacy plans', async () => { let openSubscriptionModal!: OpenSubscriptionModalCallback; const ContextReaderComponent = () => { const modal = useSubscriptionModal(); openSubscriptionModal = modal[0]; return null; }; const { container } = render( <Providers> <SubscriptionModalProvider app="proton-account"> <ContextReaderComponent /> </SubscriptionModalProvider> </Providers> ); await waitFor(() => { expect(openSubscriptionModal).toBeDefined(); }); openSubscriptionModal({} as any); expect(container).toHaveTextContent('SubscriptionContainer'); }); it('should render <SubscriptionContainer> with B2B default audience if it was selected in the callback', async () => { let openSubscriptionModal!: OpenSubscriptionModalCallback; const ContextReaderComponent = () => { const modal = useSubscriptionModal(); openSubscriptionModal = modal[0]; return null; }; const { container } = render( <Providers> <SubscriptionModalProvider app="proton-account"> <ContextReaderComponent /> </SubscriptionModalProvider> </Providers> ); await waitFor(() => { expect(openSubscriptionModal).toBeDefined(); }); openSubscriptionModal({ defaultAudience: Audience.B2B } as any); expect(SubscriptionContainer).toHaveBeenCalledWith( expect.objectContaining({ defaultAudience: Audience.B2B, }), {} ); expect(container).toHaveTextContent('SubscriptionContainer'); }); it('should render <SubscriptionContainer> with B2B default audience if plan is a B2B plan', async () => { let openSubscriptionModal!: OpenSubscriptionModalCallback; const ContextReaderComponent = () => { const modal = useSubscriptionModal(); openSubscriptionModal = modal[0]; return null; }; const { container } = render( <Providers> <SubscriptionModalProvider app="proton-account"> <ContextReaderComponent /> </SubscriptionModalProvider> </Providers> ); await waitFor(() => { expect(openSubscriptionModal).toBeDefined(); }); openSubscriptionModal({ plan: PLANS.BUNDLE_PRO } as any); expect(SubscriptionContainer).toHaveBeenCalledWith( expect.objectContaining({ defaultAudience: Audience.B2B, }), {} ); expect(container).toHaveTextContent('SubscriptionContainer'); }); it('should render <SubscriptionContainer> with B2B default audience if subscription has a B2B plan', async () => { const subscription = cloneDeep(subscriptionDefaultResponse); subscription.Subscription.Plans = [ { Name: PLANS.BUNDLE_PRO, } as any, ]; mockSubscriptionApi(subscription); let openSubscriptionModal!: OpenSubscriptionModalCallback; const ContextReaderComponent = () => { const modal = useSubscriptionModal(); openSubscriptionModal = modal[0]; return null; }; const { container } = render( <Providers> <SubscriptionModalProvider app="proton-account"> <ContextReaderComponent /> </SubscriptionModalProvider> </Providers> ); await waitFor(() => { expect(openSubscriptionModal).toBeDefined(); }); openSubscriptionModal({} as any); expect(SubscriptionContainer).toHaveBeenCalledWith( expect.objectContaining({ defaultAudience: Audience.B2B, }), {} ); expect(container).toHaveTextContent('SubscriptionContainer'); }); it('should render <SubscriptionContainer> with FAMILY default audience if it is selected', async () => { let openSubscriptionModal!: OpenSubscriptionModalCallback; const ContextReaderComponent = () => { const modal = useSubscriptionModal(); openSubscriptionModal = modal[0]; return null; }; const { container } = render( <Providers> <SubscriptionModalProvider app="proton-account"> <ContextReaderComponent /> </SubscriptionModalProvider> </Providers> ); await waitFor(() => { expect(openSubscriptionModal).toBeDefined(); }); openSubscriptionModal({ defaultAudience: Audience.FAMILY } as any); expect(SubscriptionContainer).toHaveBeenCalledWith( expect.objectContaining({ defaultAudience: Audience.FAMILY, }), {} ); expect(container).toHaveTextContent('SubscriptionContainer'); }); it('should render <InAppPurchaseModal> if subscription is managed externally', async () => { const subscription = cloneDeep(subscriptionDefaultResponse); subscription.Subscription.External = External.Android; mockSubscriptionApi(subscription); let openSubscriptionModal!: OpenSubscriptionModalCallback; const ContextReaderComponent = () => { const modal = useSubscriptionModal(); openSubscriptionModal = modal[0]; return null; }; const { getByTestId } = render( <Providers> <SubscriptionModalProvider app="proton-account"> <ContextReaderComponent /> </SubscriptionModalProvider> </Providers> ); await waitFor(() => { expect(openSubscriptionModal).toBeDefined(); }); openSubscriptionModal({} as any); expect(getByTestId('InAppPurchaseModal/text')).not.toBeEmptyDOMElement(); });
6,777
0
petrpan-code/ProtonMail/WebClients/packages/components/containers/payments
petrpan-code/ProtonMail/WebClients/packages/components/containers/payments/subscription/UnsubscribeButton.test.tsx
import { act, fireEvent, render, waitFor } from '@testing-library/react'; import cloneDeep from 'lodash/cloneDeep'; import { useModals } from '@proton/components/hooks'; import { mockOrganizationApi, mockPlansApi, mockSubscriptionApi, mockUserCache, mockUserVPNServersCountApi, subscriptionDefaultResponse, } from '@proton/components/hooks/helpers/test'; import { External } from '@proton/shared/lib/interfaces'; import { apiMock, mockCache } from '@proton/testing'; import ApiContext from '../../api/apiContext'; import { CacheProvider } from '../../cache'; import EventManagerContext from '../../eventManager/context'; import { NotificationsProvider } from '../../notifications'; import InAppPurchaseModal from './InAppPurchaseModal'; import UnsubscribeButton from './UnsubscribeButton'; jest.mock('@proton/components/hooks/useModals'); beforeEach(() => { mockUserVPNServersCountApi(); mockUserCache(); mockSubscriptionApi(); mockOrganizationApi(); mockPlansApi(); }); const defaultEventManager = { call: jest.fn() }; const Providers = ({ children, eventManager = defaultEventManager, api = apiMock, cache = mockCache }: any) => { return ( <EventManagerContext.Provider value={eventManager}> <ApiContext.Provider value={api}> <NotificationsProvider> <CacheProvider cache={cache}>{children}</CacheProvider> </NotificationsProvider> </ApiContext.Provider> </EventManagerContext.Provider> ); }; it('should render', async () => { const { container } = render( <Providers> <UnsubscribeButton>Unsubscribe</UnsubscribeButton> </Providers> ); await waitFor(() => {}); expect(container).toHaveTextContent('Unsubscribe'); }); it('should open <InAppPurchaseModal> modal if subscription is managed by Google', async () => { const subscription = cloneDeep(subscriptionDefaultResponse); subscription.Subscription.External = External.Android; mockSubscriptionApi(subscription); const { getByTestId } = render( <Providers> <UnsubscribeButton>Unsubscribe</UnsubscribeButton> </Providers> ); await waitFor(() => {}); await act(async () => { fireEvent.click(getByTestId('UnsubscribeButton')); }); const { createModal } = useModals(); const mockCreateModal: jest.Mock = createModal as any; expect(createModal).toHaveBeenCalled(); expect(mockCreateModal.mock.lastCall[0].type).toEqual(InAppPurchaseModal); });
6,782
0
petrpan-code/ProtonMail/WebClients/packages/components/containers/payments
petrpan-code/ProtonMail/WebClients/packages/components/containers/payments/subscription/YourPlanSection.test.tsx
import { fireEvent, render, waitFor, within } from '@testing-library/react'; import { useAddresses, useCache, useCalendars, useConfig, useFeature, useOrganization, usePlans, useSubscription, useUser, useVPNServersCount, } from '@proton/components/hooks'; import usePendingUserInvitations from '@proton/components/hooks/usePendingUserInvitations'; import { APPS, PLANS } from '@proton/shared/lib/constants'; import YourPlanSection from './YourPlanSection'; import { addresses, calendars, organization, pendingInvite, plans, subscriptionB, subscriptionBusiness, user, vpnServersCount, } from './__mocks__/data'; import { SUBSCRIPTION_STEPS } from './constants'; jest.mock('@proton/components/hooks/useConfig'); const mockUseConfig = useConfig as jest.MockedFunction<any>; mockUseConfig.mockReturnValue({ APP_NAME: APPS.PROTONMAIL }); jest.mock('@proton/components/hooks/useUser'); const mockUseUser = useUser as jest.MockedFunction<any>; mockUseUser.mockReturnValue([user, false]); jest.mock('@proton/components/hooks/usePlans'); const mockUsePlans = usePlans as jest.MockedFunction<any>; mockUsePlans.mockReturnValue([plans, false]); jest.mock('@proton/components/hooks/useAddresses'); const mockUseAddresses = useAddresses as jest.MockedFunction<any>; mockUseAddresses.mockReturnValue([addresses, false]); jest.mock('@proton/components/hooks/useCalendars'); const mockUseCalendars = useCalendars as jest.MockedFunction<any>; mockUseCalendars.mockReturnValue([calendars, false]); jest.mock('@proton/components/hooks/useSubscription'); const mockUseSubscription = useSubscription as jest.MockedFunction<any>; mockUseSubscription.mockReturnValue([subscriptionB, false]); jest.mock('@proton/components/hooks/useOrganization'); const mockUseOrganization = useOrganization as jest.MockedFunction<any>; mockUseOrganization.mockReturnValue([[], false]); jest.mock('@proton/components/hooks/useVPNServersCount'); const mockUseVPNServersCount = useVPNServersCount as jest.MockedFunction<any>; mockUseVPNServersCount.mockReturnValue([vpnServersCount, false]); jest.mock('@proton/components/hooks/usePendingUserInvitations'); const mockUsePendingUserInvitations = usePendingUserInvitations as jest.MockedFunction<any>; mockUsePendingUserInvitations.mockReturnValue([[], false]); jest.mock('@proton/components/hooks/useLoad'); const mockOpenSubscriptionModal = jest.fn(); jest.mock('./SubscriptionModalProvider', () => ({ __esModule: true, useSubscriptionModal: () => [mockOpenSubscriptionModal], })); jest.mock('@proton/components/hooks/useFeature'); const mockUseFeature = useFeature as jest.MockedFunction<any>; mockUseFeature.mockReturnValue({ feature: { Value: true } }); jest.mock('@proton/components/hooks/useCache'); const mockUseCache = useCache as jest.MockedFunction<any>; mockUseCache.mockReturnValue({ get: jest.fn(), delete: jest.fn() }); describe('YourPlanSection', () => { beforeEach(() => { mockUseSubscription.mockReturnValue([subscriptionB, false]); mockUsePendingUserInvitations.mockReturnValue([[], false]); mockUseOrganization.mockReturnValue([{}, false]); }); afterEach(() => { mockUsePendingUserInvitations.mockRestore(); mockUseOrganization.mockRestore(); mockUseSubscription.mockRestore(); }); describe('when user has no pending invite', () => { it('should only render subscription panel and upsell panels', async () => { const { getByTestId } = render(<YourPlanSection app={APPS.PROTONMAIL} />); const dashboardPanelsContainer = getByTestId('dashboard-panels-container'); expect(dashboardPanelsContainer.childNodes).toHaveLength(2); const [subscriptionPanel, upsellPanel] = dashboardPanelsContainer.childNodes; // Subscription Panel expect(subscriptionPanel).toBeTruthy(); within(subscriptionPanel as HTMLElement).getByText('Proton Unlimited'); within(subscriptionPanel as HTMLElement).getByText('Edit billing details'); within(subscriptionPanel as HTMLElement).getByText('Explore other Proton plans'); // Upsell Panel expect(upsellPanel).toBeTruthy(); within(upsellPanel as HTMLElement).getByText('Proton Family'); const upsellButton = within(upsellPanel as HTMLElement).getByTestId('upsell-cta'); fireEvent.click(upsellButton); await waitFor(() => expect(mockOpenSubscriptionModal).toHaveBeenCalledTimes(1)); expect(mockOpenSubscriptionModal).toHaveBeenCalledWith({ cycle: 24, plan: PLANS.FAMILY, step: SUBSCRIPTION_STEPS.CHECKOUT, disablePlanSelection: true, metrics: { source: 'upsells', }, }); }); }); describe('when user has pending invites', () => { it('should render subscription panel and pending invites, without upsells', async () => { mockUsePendingUserInvitations.mockReturnValueOnce([[pendingInvite], false]); const { getByTestId } = render(<YourPlanSection app={APPS.PROTONMAIL} />); const dashboardPanelsContainer = getByTestId('dashboard-panels-container'); expect(dashboardPanelsContainer.childNodes).toHaveLength(2); const [subscriptionPanel, invitePanel] = dashboardPanelsContainer.childNodes; // Subscription Panel expect(subscriptionPanel).toBeTruthy(); within(subscriptionPanel as HTMLElement).getByText('Proton Unlimited'); within(subscriptionPanel as HTMLElement).getByText('Edit billing details'); within(subscriptionPanel as HTMLElement).getByText('Explore other Proton plans'); // Upsell Panel expect(invitePanel).toBeTruthy(); within(invitePanel as HTMLElement).getByText('Pending invitation'); within(invitePanel as HTMLElement).getByText('Invitation from Test Org'); within(invitePanel as HTMLElement).getByText('View invitation'); }); }); describe('[business] when there is more than one user in organization', () => { it('should render subscription, usage and upsells', () => { mockUseOrganization.mockReturnValue([organization]); mockUseSubscription.mockReturnValue([subscriptionBusiness]); const { getByTestId } = render(<YourPlanSection app={APPS.PROTONMAIL} />); const dashboardPanelsContainer = getByTestId('dashboard-panels-container'); expect(dashboardPanelsContainer.childNodes).toHaveLength(3); const [subscriptionPanel, usagePanel, upsellPanel] = dashboardPanelsContainer.childNodes; // Subscription Panel expect(subscriptionPanel).toBeTruthy(); within(subscriptionPanel as HTMLElement).getByText('Proton Pro'); // Upsell Panel expect(upsellPanel).toBeTruthy(); within(upsellPanel as HTMLElement).getByText('Business'); // Usage Panel expect(usagePanel).toBeTruthy(); within(usagePanel as HTMLElement).getByText("Your account's usage"); }); }); });
6,787
0
petrpan-code/ProtonMail/WebClients/packages/components/containers/payments
petrpan-code/ProtonMail/WebClients/packages/components/containers/payments/subscription/useCheckoutModifiers.test.tsx
import { renderHook } from '@testing-library/react-hooks'; import { COUPON_CODES, CYCLE, PLANS } from '@proton/shared/lib/constants'; import { PlansMap, Renew, SubscriptionCheckResponse, SubscriptionModel } from '@proton/shared/lib/interfaces'; import { Model } from './SubscriptionContainer'; import { SUBSCRIPTION_STEPS } from './constants'; import { useCheckoutModifiers } from './useCheckoutModifiers'; describe('useCheckoutModifiers', () => { let model: Model; let subscriptionModel: SubscriptionModel; let checkResult: SubscriptionCheckResponse; const plansMap: PlansMap = { mail2022: { ID: 'Wb4NAqmiuqoA7kCHE28y92bBFfN8jaYQCLxHRAB96yGj-bh9SxguXC48_WSU-fRUjdAr-lx95c6rFLplgXyXYA==', Type: 1, Name: PLANS.MAIL, Title: 'Mail Plus', MaxDomains: 1, MaxAddresses: 10, MaxCalendars: 25, MaxSpace: 16106127360, MaxMembers: 1, MaxVPN: 0, MaxTier: 0, Services: 1, Features: 1, State: 1, Pricing: { '1': 499, '12': 4788, '24': 8376, }, Currency: 'CHF', Quantity: 1, Cycle: 1, Amount: 499, Offers: [], }, mailpro2022: { ID: 'rIJcBetavQi7h5qqN9nxrRnlojgl6HF6bAVG989deNJVVVx1nn2Ic3eyCVV2Adq11ddseZuWba9H5tmvLC727Q==', Type: 1, Name: PLANS.MAIL_PRO, Title: 'Mail Essentials', MaxDomains: 3, MaxAddresses: 10, MaxCalendars: 25, MaxSpace: 16106127360, MaxMembers: 1, MaxVPN: 0, MaxTier: 0, Services: 1, Features: 1, State: 1, Pricing: { '1': 799, '12': 8388, '24': 15576, }, Currency: 'CHF', Quantity: 1, Cycle: 1, Amount: 799, Offers: [], }, bundle2022: { ID: 'vl-JevUsz3GJc18CC1VOs-qDKqoIWlLiUePdrzFc72-BtxBPHBDZM7ayn8CNQ59Sk4XjDbwwBVpdYrPIFtOvIw==', Type: 1, Name: PLANS.BUNDLE, Title: 'Proton Unlimited', MaxDomains: 3, MaxAddresses: 15, MaxCalendars: 25, MaxSpace: 536870912000, MaxMembers: 1, MaxVPN: 10, MaxTier: 2, Services: 7, Features: 1, State: 1, Pricing: { '1': 1199, '12': 11988, '24': 19176, }, Currency: 'CHF', Quantity: 1, Cycle: 1, Amount: 1199, Offers: [], }, }; beforeEach(() => { model = { step: SUBSCRIPTION_STEPS.CHECKOUT, planIDs: { [PLANS.MAIL]: 1, }, currency: 'CHF', cycle: CYCLE.MONTHLY, initialCheckComplete: false, }; subscriptionModel = { ID: 'id123', InvoiceID: 'id456', Cycle: CYCLE.MONTHLY, PeriodStart: Math.floor(Date.now() / 1000) - 1, PeriodEnd: Math.floor(Date.now() / 1000 + 30 * 24 * 60 * 60), CreateTime: Math.floor(Date.now() / 1000) - 1, CouponCode: null, Currency: 'CHF', Amount: 499, RenewAmount: 499, Discount: 0, isManagedByMozilla: false, External: 0, Renew: Renew.Enabled, Plans: [ { Amount: 499, Currency: 'CHF', Cycle: 1, Features: 1, ID: 'Wb4NAqmiuqoA7kCHE28y92bBFfN8jaYQCLxHRAB96yGj-bh9SxguXC48_WSU-fRUjdAr-lx95c6rFLplgXyXYA==', MaxAddresses: 10, MaxCalendars: 25, MaxDomains: 1, MaxMembers: 1, MaxSpace: 16106127360, MaxTier: 0, MaxVPN: 0, Name: PLANS.MAIL, Quantity: 1, Services: 1, State: 1, Title: 'Mail Plus', Type: 1, Pricing: null as any, Offers: [], }, ], }; checkResult = { Amount: 499, AmountDue: 499, Coupon: null, Currency: 'CHF', Cycle: CYCLE.MONTHLY, Additions: null, PeriodEnd: Math.floor(Date.now() / 1000 + 30 * 24 * 60 * 60), }; }); it('should return isProration === true when checkResult is undefined', () => { const { result } = renderHook(() => useCheckoutModifiers(model, subscriptionModel, plansMap)); expect(result.current.isProration).toEqual(true); }); it('should return isProration === true when user buys different plan', () => { model.planIDs = { [PLANS.MAIL_PRO]: 1, }; subscriptionModel.Plans[0].Name = PLANS.MAIL; const { result } = renderHook(() => useCheckoutModifiers(model, subscriptionModel, plansMap, checkResult)); expect(result.current.isProration).toEqual(true); }); it('should return isProration === true if user buys the same plan but proration is undefined', () => { checkResult.Proration = undefined; const { result } = renderHook(() => useCheckoutModifiers(model, subscriptionModel, plansMap, checkResult)); expect(result.current.isProration).toEqual(true); }); it('should return isProration === true if Proration exists and proration !== 0', () => { checkResult.Proration = -450; const { result } = renderHook(() => useCheckoutModifiers(model, subscriptionModel, plansMap, checkResult)); expect(result.current.isProration).toEqual(true); }); it('should return isProration === false if Proration exists and proration === 0', () => { checkResult.Proration = 0; const { result } = renderHook(() => useCheckoutModifiers(model, subscriptionModel, plansMap, checkResult)); expect(result.current.isProration).toEqual(false); }); it('should return isScheduledSubscription === false if checkResult is undefined', () => { const { result } = renderHook(() => useCheckoutModifiers(model, subscriptionModel, plansMap)); expect(result.current.isScheduledSubscription).toEqual(false); }); it('should return isProration true when user has trial', () => { subscriptionModel.CouponCode = COUPON_CODES.REFERRAL; checkResult.Proration = 0; const { result } = renderHook(() => useCheckoutModifiers(model, subscriptionModel, plansMap, checkResult)); expect(result.current.isProration).toEqual(true); }); describe('custom billings', () => { it('should return isScheduledSubscription === false if UnusedCredit !== 0', () => { checkResult.Proration = 0; checkResult.UnusedCredit = -20; const { result } = renderHook(() => useCheckoutModifiers(model, subscriptionModel, plansMap, checkResult)); expect(result.current.isScheduledSubscription).toEqual(false); }); it('should return isProration === false if UnusedCredit !== 0', () => { checkResult.Proration = 0; checkResult.UnusedCredit = -20; const { result } = renderHook(() => useCheckoutModifiers(model, subscriptionModel, plansMap, checkResult)); expect(result.current.isProration).toEqual(false); }); it('should return isCustomBilling === true if UnusedCredit !== 0', () => { checkResult.Proration = 0; checkResult.UnusedCredit = -20; const { result } = renderHook(() => useCheckoutModifiers(model, subscriptionModel, plansMap, checkResult)); expect(result.current.isCustomBilling).toEqual(true); }); it('should return isCustomBilling === false if UnusedCredit === 0', () => { checkResult.Proration = 150; checkResult.UnusedCredit = 0; const { result } = renderHook(() => useCheckoutModifiers(model, subscriptionModel, plansMap, checkResult)); expect(result.current.isCustomBilling).toEqual(false); }); it('should return isCustomBilling === false if UnusedCredit === 0 if Proration is 0 too', () => { checkResult.Proration = 0; checkResult.UnusedCredit = 0; const { result } = renderHook(() => useCheckoutModifiers(model, subscriptionModel, plansMap, checkResult)); expect(result.current.isCustomBilling).toEqual(false); }); it('should return isCustomBilling === false if checkResult is undefined', () => { const { result } = renderHook(() => useCheckoutModifiers(model, subscriptionModel, plansMap)); expect(result.current.isCustomBilling).toEqual(false); }); }); });
6,793
0
petrpan-code/ProtonMail/WebClients/packages/components/containers/payments/subscription
petrpan-code/ProtonMail/WebClients/packages/components/containers/payments/subscription/cancelSubscription/CancelSubscriptionModal.test.tsx
import { render } from '@testing-library/react'; import { subscriptionMock, upcomingSubscriptionMock } from '@proton/testing/data'; import { CancelSubscriptionModal } from './CancelSubscriptionModal'; jest.mock('@proton/components/components/portal/Portal'); const onResolve = jest.fn(); const onReject = jest.fn(); it('should render', () => { const { container } = render( <CancelSubscriptionModal subscription={subscriptionMock} onResolve={onResolve} onReject={onReject} open /> ); expect(container).not.toBeEmptyDOMElement(); }); it('should return status kept when clicking on keep subscription', () => { const { getByTestId } = render( <CancelSubscriptionModal subscription={subscriptionMock} onResolve={onResolve} onReject={onReject} open /> ); getByTestId('keepSubscription').click(); expect(onResolve).toHaveBeenCalledWith({ status: 'kept' }); }); it('should return status cancelled when clicking on cancel subscription', () => { const { getByTestId } = render( <CancelSubscriptionModal subscription={subscriptionMock} onResolve={onResolve} onReject={onReject} open /> ); getByTestId('cancelSubscription').click(); expect(onResolve).toHaveBeenCalledWith({ status: 'cancelled' }); }); it('should display end date of the current subscription', () => { const { container } = render( <CancelSubscriptionModal subscription={subscriptionMock} onResolve={onResolve} onReject={onReject} open /> ); expect(container).toHaveTextContent('expires on Jun 5, 2024'); }); it('should display the end date of the upcoming subscription if it exists', () => { const { container } = render( <CancelSubscriptionModal subscription={{ ...subscriptionMock, UpcomingSubscription: upcomingSubscriptionMock }} onResolve={onResolve} onReject={onReject} open /> ); expect(container).toHaveTextContent('expires on Jun 5, 2026'); });
6,795
0
petrpan-code/ProtonMail/WebClients/packages/components/containers/payments/subscription
petrpan-code/ProtonMail/WebClients/packages/components/containers/payments/subscription/cancelSubscription/CancelSubscriptionSection.test.tsx
import { render } from '@testing-library/react'; import { mockSubscriptionCache, mockUserCache } from '@proton/components/hooks/helpers/test'; import { applyHOCs, withApi, withCache, withEventManager, withNotifications } from '@proton/testing/index'; import { CancelSubscriptionSection } from './CancelSubscriptionSection'; const CancelSubscriptionSectionContext = applyHOCs( withApi(), withEventManager(), withCache(), withNotifications() )(CancelSubscriptionSection); beforeEach(() => { jest.clearAllMocks(); mockSubscriptionCache(); mockUserCache(); }); it('should render', () => { const { container } = render(<CancelSubscriptionSectionContext />); expect(container).not.toBeEmptyDOMElement(); }); it('should return empty DOM element if no subscription', () => { mockSubscriptionCache(null as any); const { container } = render(<CancelSubscriptionSectionContext />); expect(container).toBeEmptyDOMElement(); });
6,799
0
petrpan-code/ProtonMail/WebClients/packages/components/containers/payments/subscription
petrpan-code/ProtonMail/WebClients/packages/components/containers/payments/subscription/cancelSubscription/useCancelSubscriptionFlow.test.tsx
import { render } from '@testing-library/react'; import { renderHook } from '@testing-library/react-hooks'; import userEvent from '@testing-library/user-event'; import { changeRenewState } from '@proton/shared/lib/api/payments'; import { wait } from '@proton/shared/lib/helpers/promise'; import { Renew, SubscriptionModel, UserModel } from '@proton/shared/lib/interfaces'; import { componentWrapper as _componentWrapper, apiMock, hookWrapper, withApi, withConfig, withEventManager, withNotifications, } from '@proton/testing'; import { subscriptionMock } from '@proton/testing/data'; import { useCancelSubscriptionFlow } from './useCancelSubscriptionFlow'; jest.mock('@proton/components/components/portal/Portal'); const user: UserModel = { ID: 'user-123', } as UserModel; const providers = [withConfig(), withApi(), withEventManager(), withNotifications()]; const wrapper = hookWrapper(...providers); const componentWrapper = _componentWrapper(...providers); it('should return modals and cancelSubscription', () => { const { result } = renderHook( () => useCancelSubscriptionFlow({ subscription: subscriptionMock as SubscriptionModel, user }), { wrapper } ); expect(result.current.cancelSubscription).toBeDefined(); expect(result.current.cancelSubscriptionModals).toBeDefined(); }); it('should return subscription kept if no subscription', async () => { const { result } = renderHook(() => useCancelSubscriptionFlow({ subscription: undefined as any, user }), { wrapper, }); await expect(result.current.cancelSubscription()).resolves.toEqual({ status: 'kept', }); }); it('should return subscription kept if no user', async () => { const { result } = renderHook( () => useCancelSubscriptionFlow({ subscription: subscriptionMock as SubscriptionModel, user: undefined as any }), { wrapper } ); await expect(result.current.cancelSubscription()).resolves.toEqual({ status: 'kept', }); }); it('should return subscription kept if user closes the modal', async () => { const { result } = renderHook( () => useCancelSubscriptionFlow({ subscription: subscriptionMock as SubscriptionModel, user }), { wrapper } ); const cancelSubscriptionPromise = result.current.cancelSubscription(); const { getByTestId } = render(result.current.cancelSubscriptionModals); getByTestId('keepSubscription').click(); await expect(cancelSubscriptionPromise).resolves.toEqual({ status: 'kept', }); }); it('should return subscription kept if user closes the feedback modal', async () => { const { result } = renderHook( () => useCancelSubscriptionFlow({ subscription: subscriptionMock as SubscriptionModel, user }), { wrapper } ); const cancelSubscriptionPromise = result.current.cancelSubscription(); // Render the modal components returned by the hook const { getByTestId, rerender } = render(result.current.cancelSubscriptionModals, { wrapper: componentWrapper, }); getByTestId('cancelSubscription').click(); await wait(0); rerender(result.current.cancelSubscriptionModals); // Simulate user clicking the element to close the feedback modal getByTestId('cancelFeedback').click(); await expect(cancelSubscriptionPromise).resolves.toEqual({ status: 'kept', }); }); it('should send the API request for subscription cancellation and return the result', async () => { const { result } = renderHook( () => useCancelSubscriptionFlow({ subscription: subscriptionMock as SubscriptionModel, user }), { wrapper } ); const cancelSubscriptionPromise = result.current.cancelSubscription(); const { getByTestId, rerender, container, getByText } = render(result.current.cancelSubscriptionModals, { wrapper: componentWrapper, }); getByTestId('cancelSubscription').click(); await wait(0); rerender(result.current.cancelSubscriptionModals); await userEvent.click(container.querySelector('#reason') as HTMLButtonElement); await userEvent.click(getByText('I use a different Proton account')); getByTestId('submitFeedback').click(); await wait(0); rerender(result.current.cancelSubscriptionModals); expect(apiMock).toHaveBeenCalledWith( changeRenewState({ RenewalState: Renew.Disabled, CancellationFeedback: { Reason: 'DIFFERENT_ACCOUNT', Feedback: '', ReasonDetails: '', Context: 'mail', }, }) ); await expect(cancelSubscriptionPromise).resolves.toEqual({ status: 'cancelled', }); });
6,802
0
petrpan-code/ProtonMail/WebClients/packages/components/containers/payments/subscription
petrpan-code/ProtonMail/WebClients/packages/components/containers/payments/subscription/helpers/dashboard-upsells.test.ts
import { APPS, COUPON_CODES, CYCLE, PLANS, PLAN_TYPES } from '@proton/shared/lib/constants'; import { Subscription } from '@proton/shared/lib/interfaces'; import { businessUpsell, drivePlusUpsell, familyUpsell, mailPlusUpsell, passPlusUpsell, plans, subscription, trialMailPlusUpsell, unlimitedUpsell, vpnBusinessUpsell, vpnEnterpriseUpsell, } from '../__mocks__/data'; import { SUBSCRIPTION_STEPS } from '../constants'; import { resolveUpsellsToDisplay } from './dashboard-upsells'; describe('resolveUpsellsToDisplay', () => { let mockedOpenSubscriptionModal: jest.Mock; let base: Parameters<typeof resolveUpsellsToDisplay>[0]; beforeEach(() => { mockedOpenSubscriptionModal = jest.fn(); base = { app: APPS.PROTONMAIL, currency: 'EUR', subscription, plans, serversCount: { paid: { servers: 100, countries: 10, }, free: { servers: 10, countries: 1, }, }, canPay: true, isFree: true, hasPaidMail: false, openSubscriptionModal: mockedOpenSubscriptionModal, }; }); describe('Free Mail', () => { it('should return MailPlus + Unlimited (recommended) upsells', () => { const upsells = resolveUpsellsToDisplay(base); expect(upsells).toMatchObject([mailPlusUpsell, { ...unlimitedUpsell, isRecommended: true }]); upsells[0].onUpgrade(); expect(mockedOpenSubscriptionModal).toHaveBeenCalledTimes(1); expect(mockedOpenSubscriptionModal).toHaveBeenCalledWith({ disablePlanSelection: true, plan: PLANS.MAIL, step: SUBSCRIPTION_STEPS.CHECKOUT, metrics: { source: 'upsells', }, }); upsells[1].onUpgrade(); expect(mockedOpenSubscriptionModal).toHaveBeenCalledTimes(2); expect(mockedOpenSubscriptionModal).toHaveBeenLastCalledWith({ cycle: CYCLE.TWO_YEARS, disablePlanSelection: true, plan: PLANS.BUNDLE, step: SUBSCRIPTION_STEPS.CHECKOUT, metrics: { source: 'upsells', }, }); }); }); describe('Free Trial', () => { it('should return MailPlus + Unlimited (recommended) upsells', () => { const upsells = resolveUpsellsToDisplay({ ...base, subscription: { ...base.subscription, CouponCode: COUPON_CODES.REFERRAL, PeriodEnd: 1718870501, } as Subscription, }); // .toMatchObject can't match functions, so we need to remove them const trialMailPlusUpsellWithoutAction = { ...trialMailPlusUpsell, otherCtas: trialMailPlusUpsell.otherCtas.map(({ action, ...rest }) => rest), }; expect(upsells).toMatchObject([ trialMailPlusUpsellWithoutAction, { ...unlimitedUpsell, isRecommended: true }, ]); upsells[0].onUpgrade(); expect(mockedOpenSubscriptionModal).toHaveBeenCalledTimes(1); expect(mockedOpenSubscriptionModal).toHaveBeenCalledWith({ disablePlanSelection: true, plan: PLANS.MAIL, step: SUBSCRIPTION_STEPS.CHECKOUT, metrics: { source: 'upsells', }, }); upsells[1].onUpgrade(); expect(mockedOpenSubscriptionModal).toHaveBeenCalledTimes(2); expect(mockedOpenSubscriptionModal).toHaveBeenLastCalledWith({ cycle: CYCLE.TWO_YEARS, disablePlanSelection: true, plan: PLANS.BUNDLE, step: SUBSCRIPTION_STEPS.CHECKOUT, metrics: { source: 'upsells', }, }); }); }); describe('Mail Plus', () => { it('should return Unlimited (recommended) + Family upsells', () => { const upsells = resolveUpsellsToDisplay({ ...base, isFree: false, hasPaidMail: true, }); expect(upsells).toMatchObject([ { ...unlimitedUpsell, isRecommended: true, features: unlimitedUpsell.features.filter(({ text }) => text !== '25 calendars'), }, familyUpsell, ]); upsells[0].onUpgrade(); expect(mockedOpenSubscriptionModal).toHaveBeenCalledTimes(1); expect(mockedOpenSubscriptionModal).toHaveBeenCalledWith({ cycle: CYCLE.TWO_YEARS, disablePlanSelection: true, plan: PLANS.BUNDLE, step: SUBSCRIPTION_STEPS.CHECKOUT, metrics: { source: 'upsells', }, }); upsells[1].onUpgrade(); expect(mockedOpenSubscriptionModal).toHaveBeenCalledTimes(2); expect(mockedOpenSubscriptionModal).toHaveBeenLastCalledWith({ cycle: CYCLE.TWO_YEARS, disablePlanSelection: true, plan: PLANS.FAMILY, step: SUBSCRIPTION_STEPS.CHECKOUT, metrics: { source: 'upsells', }, }); }); }); describe('Unlimited', () => { it('should return Family upsell', () => { const [upsell] = resolveUpsellsToDisplay({ ...base, isFree: false, hasPaidMail: true, subscription: { Plans: [ { Name: PLANS.BUNDLE, Type: PLAN_TYPES.PLAN, }, ], } as Subscription, }); expect(upsell).toMatchObject(familyUpsell); upsell.onUpgrade(); expect(mockedOpenSubscriptionModal).toHaveBeenCalledTimes(1); expect(mockedOpenSubscriptionModal).toHaveBeenCalledWith({ cycle: CYCLE.TWO_YEARS, disablePlanSelection: true, plan: PLANS.FAMILY, step: SUBSCRIPTION_STEPS.CHECKOUT, metrics: { source: 'upsells', }, }); }); }); describe('Essentials', () => { it('should return Business upsell', () => { const [upsell] = resolveUpsellsToDisplay({ ...base, isFree: false, hasPaidMail: true, subscription: { Plans: [ { Name: PLANS.MAIL_PRO, Type: PLAN_TYPES.PLAN, }, ], } as Subscription, }); expect(upsell).toMatchObject(businessUpsell); upsell.onUpgrade(); expect(mockedOpenSubscriptionModal).toHaveBeenCalledTimes(1); expect(mockedOpenSubscriptionModal).toHaveBeenCalledWith({ cycle: CYCLE.TWO_YEARS, disablePlanSelection: true, plan: PLANS.BUNDLE_PRO, step: SUBSCRIPTION_STEPS.CHECKOUT, metrics: { source: 'upsells', }, }); }); }); describe('Free Drive', () => { it('should return Drive upsell', () => { const [upsell] = resolveUpsellsToDisplay({ ...base, app: APPS.PROTONDRIVE, isFree: true, }); expect(upsell).toMatchObject(drivePlusUpsell); upsell.onUpgrade(); expect(mockedOpenSubscriptionModal).toHaveBeenCalledTimes(1); expect(mockedOpenSubscriptionModal).toHaveBeenCalledWith({ cycle: CYCLE.TWO_YEARS, disablePlanSelection: true, plan: PLANS.DRIVE, step: SUBSCRIPTION_STEPS.CHECKOUT, metrics: { source: 'upsells', }, }); }); }); describe('Free Pass', () => { it('should return Pass upsell', () => { const [upsell] = resolveUpsellsToDisplay({ ...base, app: APPS.PROTONPASS, isFree: true, }); expect(upsell).toMatchObject(passPlusUpsell); upsell.onUpgrade(); expect(mockedOpenSubscriptionModal).toHaveBeenCalledTimes(1); expect(mockedOpenSubscriptionModal).toHaveBeenCalledWith({ cycle: CYCLE.TWO_YEARS, disablePlanSelection: true, plan: PLANS.PASS_PLUS, step: SUBSCRIPTION_STEPS.CHECKOUT, metrics: { source: 'upsells', }, }); }); }); describe('VPN Essentials', () => { it('should return VPN Business and VPN Enterprise upselss', () => { const upsells = resolveUpsellsToDisplay({ ...base, subscription: { Plans: [ { Name: PLANS.VPN_PRO, Type: PLAN_TYPES.PLAN, }, ], } as Subscription, app: APPS.PROTONACCOUNT, isFree: false, }); const [upsell1, upsell2] = upsells; expect(upsell1).toMatchObject(vpnBusinessUpsell); upsell1.onUpgrade(); expect(mockedOpenSubscriptionModal).toHaveBeenCalledTimes(1); expect(mockedOpenSubscriptionModal).toHaveBeenCalledWith({ cycle: CYCLE.TWO_YEARS, disablePlanSelection: true, plan: PLANS.VPN_BUSINESS, step: SUBSCRIPTION_STEPS.CHECKOUT_WITH_CUSTOMIZATION, metrics: { source: 'upsells', }, }); expect(upsell2).toMatchObject(vpnEnterpriseUpsell); expect(upsell2.ignoreDefaultCta).toEqual(true); expect(upsell2.otherCtas).toHaveLength(1); upsell2.onUpgrade(); // that's right, the VPN Enterprise upsell should not call the modal. It must have noop because it has // custom CTA. The 1 comes from the previous call expect(mockedOpenSubscriptionModal).toHaveBeenCalledTimes(1); }); }); describe('VPN Business', () => { it('should return VPN Enterprise upsell', () => { const [upsell] = resolveUpsellsToDisplay({ ...base, subscription: { Plans: [ { Name: PLANS.VPN_BUSINESS, Type: PLAN_TYPES.PLAN, }, ], } as Subscription, app: APPS.PROTONACCOUNT, isFree: false, }); expect(upsell).toMatchObject(vpnEnterpriseUpsell); expect(upsell.ignoreDefaultCta).toEqual(true); expect(upsell.otherCtas).toHaveLength(1); upsell.onUpgrade(); expect(mockedOpenSubscriptionModal).not.toHaveBeenCalled(); }); }); });
6,805
0
petrpan-code/ProtonMail/WebClients/packages/components/containers/payments/subscription
petrpan-code/ProtonMail/WebClients/packages/components/containers/payments/subscription/helpers/payment.test.ts
import { FREE_SUBSCRIPTION } from '@proton/shared/lib/constants'; import { Renew } from '@proton/shared/lib/interfaces'; import { subscriptionMock, upcomingSubscriptionMock } from '@proton/testing/data'; import { subscriptionExpires } from './payment'; describe('subscriptionExpires()', () => { it('should handle the case when subscription is not loaded yet', () => { expect(subscriptionExpires()).toEqual({ subscriptionExpiresSoon: false, renewDisabled: false, renewEnabled: true, expirationDate: null, }); }); it('should handle the case when subscription is free', () => { expect(subscriptionExpires(FREE_SUBSCRIPTION as any)).toEqual({ subscriptionExpiresSoon: false, renewDisabled: false, renewEnabled: true, expirationDate: null, }); }); it('should handle non-expiring subscription', () => { expect(subscriptionExpires(subscriptionMock)).toEqual({ subscriptionExpiresSoon: false, planName: 'Proton Unlimited', renewDisabled: false, renewEnabled: true, expirationDate: null, }); }); it('should handle expiring subscription', () => { expect( subscriptionExpires({ ...subscriptionMock, Renew: Renew.Disabled, }) ).toEqual({ subscriptionExpiresSoon: true, planName: 'Proton Unlimited', renewDisabled: true, renewEnabled: false, expirationDate: subscriptionMock.PeriodEnd, }); }); it('should handle the case when the upcoming subscription expires', () => { expect( subscriptionExpires({ ...subscriptionMock, UpcomingSubscription: { ...upcomingSubscriptionMock, Renew: Renew.Disabled, }, }) ).toEqual({ subscriptionExpiresSoon: true, planName: 'Proton Unlimited', renewDisabled: true, renewEnabled: false, expirationDate: upcomingSubscriptionMock.PeriodEnd, }); }); it('should handle the case when the upcoming subscription does not expire', () => { expect( subscriptionExpires({ ...subscriptionMock, UpcomingSubscription: { ...upcomingSubscriptionMock, Renew: Renew.Enabled, }, }) ).toEqual({ subscriptionExpiresSoon: false, planName: 'Proton Unlimited', renewDisabled: false, renewEnabled: true, expirationDate: null, }); }); });
6,808
0
petrpan-code/ProtonMail/WebClients/packages/components/containers/payments/subscription
petrpan-code/ProtonMail/WebClients/packages/components/containers/payments/subscription/modal-components/CheckoutRow.test.tsx
import { render } from '@testing-library/react'; import CheckoutRow, { Props } from './CheckoutRow'; let props: Props; beforeEach(() => { props = { title: 'My Checkout Title', amount: 999, }; }); it('should render', () => { const { container } = render(<CheckoutRow {...props} />); expect(container).not.toBeEmptyDOMElement(); }); it('should render free if amount is 0 and there is no currency', () => { props.amount = 0; props.currency = undefined; const { container } = render(<CheckoutRow {...props} />); expect(container).toHaveTextContent(props.title as string); expect(container).toHaveTextContent('Free'); }); it('should render loading state', () => { props.loading = true; const { container } = render(<CheckoutRow {...props} />); expect(container).toHaveTextContent(props.title as string); expect(container).toHaveTextContent('Loading'); }); it('should render price with suffix', () => { props.suffix = '/year'; props.currency = 'CHF'; const { container } = render(<CheckoutRow {...props} />); expect(container).toHaveTextContent(`My Checkout TitleCHF 9.99/year`); }); it('should render price with suffix on next line', () => { props.suffix = '/year'; props.currency = 'CHF'; props.suffixNextLine = true; const { getByTestId } = render(<CheckoutRow {...props} />); expect(getByTestId('next-line-suffix')).toHaveTextContent('/year'); });
6,813
0
petrpan-code/ProtonMail/WebClients/packages/components/containers/payments/subscription
petrpan-code/ProtonMail/WebClients/packages/components/containers/payments/subscription/panels/Panel.test.tsx
import { render, screen } from '@testing-library/react'; import Panel from './Panel'; describe('Panel', () => { it('should display panel title + its content', () => { render( <Panel title="test title"> <>Test content</> </Panel> ); expect(screen.getByRole('heading', { level: 2, name: /test title/ })); expect(screen.getByText('Test content')); }); });
6,818
0
petrpan-code/ProtonMail/WebClients/packages/components/containers/payments/subscription
petrpan-code/ProtonMail/WebClients/packages/components/containers/payments/subscription/panels/UpsellPanel.test.tsx
import { fireEvent, render, screen, waitFor } from '@testing-library/react'; import { useActiveBreakpoint } from '@proton/components/hooks'; import { omit } from '@proton/shared/lib/helpers/object'; import UpsellPanel, { UpsellPanelProps } from './UpsellPanel'; jest.mock('@proton/components/hooks/useActiveBreakpoint'); const mockUseActiveBreakpoint = useActiveBreakpoint as jest.MockedFn<typeof useActiveBreakpoint>; describe('UpsellBox', () => { beforeEach(() => { mockUseActiveBreakpoint.mockReturnValue({ isNarrow: false } as any); }); const handleUpgrade = jest.fn(); const upsellBoxBaseProps: UpsellPanelProps = { title: 'Upgrade to Plus', features: [ { icon: 'storage', text: `10GB total storage`, }, { icon: 'envelope', text: `10 email addresses/aliases`, }, { icon: 'tag', text: `Unlimited folders, labels, and filters`, }, ], ctas: [ { label: 'From 3.99€', action: handleUpgrade, shape: 'outline', }, ], }; it('should correctly render a basic upsell box', () => { const { container } = render( <UpsellPanel {...upsellBoxBaseProps}>Upgrade to Plus pack to access to more services</UpsellPanel> ); // should have basic style expect(container.firstChild).toHaveClass('border-strong'); // should not have `recommended` label const recommendedLabel = screen.queryByText('Recommended'); expect(recommendedLabel).toBeNull(); // header expect(screen.getByText('Upgrade to Plus')); expect(screen.getByText('Upgrade to Plus pack to access to more services')); // features expect(screen.getByText('10GB total storage')); expect(screen.getByText('10 email addresses/aliases')); expect(screen.getByText('Unlimited folders, labels, and filters')); // actions const button = screen.getByText('From 3.99€'); expect(button).toHaveClass('button-outline-weak'); }); it('should correctly handle upsell click action', async () => { render(<UpsellPanel {...upsellBoxBaseProps} />); const button = screen.getByText('From 3.99€'); fireEvent.click(button); await waitFor(() => expect(handleUpgrade).toHaveBeenCalledTimes(1)); }); describe('isRecommended is true', () => { it('should render with primary border', () => { const { container } = render(<UpsellPanel {...upsellBoxBaseProps} isRecommended />); // should have basic style expect(container.firstChild).toHaveClass('border-primary'); expect(container.firstChild).toHaveClass('border-recommended'); // should have label rendered expect(screen.getByText('Recommended')); }); describe('when action button is outline', () => { it('should render with primary border and buttons', () => { render( <UpsellPanel {...omit(upsellBoxBaseProps, ['ctas'])} ctas={[ { label: 'From 3.99€', action: handleUpgrade, shape: 'outline', }, ]} isRecommended /> ); // actions const button = screen.getByText('From 3.99€'); expect(button).toHaveClass('button-solid-norm'); }); }); describe('when action button is other than outline/solid', () => { it('should not change color and shape of the button', () => { render( <UpsellPanel {...omit(upsellBoxBaseProps, ['ctas'])} ctas={[ { label: 'From 3.99€', action: handleUpgrade, shape: 'ghost', color: 'norm', }, ]} isRecommended /> ); // actions const button = screen.getByText('From 3.99€'); expect(button).toHaveClass('button-ghost-norm'); }); }); }); describe('when one item as a tooltip', () => { it('should render a tooltip in the DOM', () => { render( <UpsellPanel {...omit(upsellBoxBaseProps, ['features'])} features={[ { icon: 'envelope', text: `10 email addresses/aliases`, tooltip: 'You can use those aliases on different website to protect your main email', }, ]} /> ); expect(screen.getByText('10 email addresses/aliases')); expect( screen.getByText('More info: You can use those aliases on different website to protect your main email') ); }); }); describe('when a children is provided', () => { it('should render the children', () => { render( <UpsellPanel {...upsellBoxBaseProps}> <div>Hello world, here is a testing child</div> </UpsellPanel> ); screen.getAllByText('Hello world, here is a testing child'); }); }); describe('when screenview is narrow', () => { it('should not display the feature but a button to toggle their display', async () => { mockUseActiveBreakpoint.mockReturnValue({ isNarrow: true } as any); render(<UpsellPanel {...upsellBoxBaseProps} />); // features should be hidden at first expect(screen.queryByText('10GB total storage')).toBeNull(); expect(screen.queryByText('10 email addresses/aliases')).toBeNull(); expect(screen.queryByText('Unlimited folders, labels, and filters')).toBeNull(); const showBtn = screen.getByText('See plan features'); fireEvent.click(showBtn); // features should be displayed expect(screen.getByText('10GB total storage')); expect(screen.getByText('10 email addresses/aliases')); expect(screen.getByText('Unlimited folders, labels, and filters')); const hideBtn = screen.getByText('Hide plan features'); fireEvent.click(hideBtn); // features should be hidden again expect(screen.queryByText('10GB total storage')).toBeNull(); expect(screen.queryByText('10 email addresses/aliases')).toBeNull(); expect(screen.queryByText('Unlimited folders, labels, and filters')).toBeNull(); }); }); });
6,820
0
petrpan-code/ProtonMail/WebClients/packages/components/containers/payments/subscription
petrpan-code/ProtonMail/WebClients/packages/components/containers/payments/subscription/panels/UpsellPanels.test.tsx
import { render, screen, within } from '@testing-library/react'; import { COUPON_CODES } from '@proton/shared/lib/constants'; import { Subscription } from '@proton/shared/lib/interfaces'; import { familyUpsell, subscription, trialMailPlusUpsell, unlimitedUpsell } from '../__mocks__/data'; import { Upsell } from '../helpers'; import UpsellPanels from './UpsellPanels'; describe('UpsellPanel', () => { it('should display panels with correct details', async () => { const { container } = render( <UpsellPanels subscription={subscription} upsells={[ { ...unlimitedUpsell, onUpgrade: jest.fn(), isRecommended: true } as Upsell, { ...familyUpsell, onUpgrade: jest.fn() } as Upsell, ]} /> ); expect(container.childNodes).toHaveLength(2); const unlimitedUpsellPanel = container.childNodes[0] as HTMLElement; const familyUpsellPanel = container.childNodes[1] as HTMLElement; expect(within(unlimitedUpsellPanel).getByText('Recommended')); // 1rst upsell - title expect(within(unlimitedUpsellPanel).getByText('Proton Unlimited')); // description expect( within(unlimitedUpsellPanel).getByText( 'Comprehensive privacy and security with all Proton services combined.' ) ); // features within(unlimitedUpsellPanel).getByText('500 GB storage'); expect(within(unlimitedUpsellPanel).getByText('15 email addresses/aliases')); expect(within(unlimitedUpsellPanel).getByText('3 custom email domains')); expect(within(unlimitedUpsellPanel).getByText('Unlimited folders, labels, and filters')); expect(within(unlimitedUpsellPanel).getByText('25 calendars')); expect(within(unlimitedUpsellPanel).getByText('10 high-speed VPN connections')); expect(within(unlimitedUpsellPanel).getByText('Proton Pass with unlimited hide-my-email aliases')); expect(within(familyUpsellPanel).queryByText('Recommended')).toBeNull(); // 2nd upsell - title expect(within(familyUpsellPanel).getByText('Proton Family')); // description expect(within(familyUpsellPanel).getByText('Protect your family’s privacy with all Proton services combined.')); // features expect(within(familyUpsellPanel).getByText('3 TB storage')); expect(within(familyUpsellPanel).getByText('Up to 6 users')); expect(within(familyUpsellPanel).getByText('90 email addresses/aliases')); expect(within(familyUpsellPanel).getByText('Unlimited folders, labels, and filters')); expect(within(familyUpsellPanel).getByText('10 high-speed VPN connections')); expect(within(familyUpsellPanel).getByText('Proton Pass with unlimited hide-my-email aliases')); }); it('should display warning for trial period end', () => { render( <UpsellPanels subscription={ { ...subscription, CouponCode: COUPON_CODES.REFERRAL, PeriodEnd: 1718870501, } as Subscription } upsells={[{ ...trialMailPlusUpsell, onUpgrade: jest.fn() } as unknown as Upsell]} /> ); screen.getByText('Your trial ends June 20, 2024'); }); });
6,828
0
petrpan-code/ProtonMail/WebClients/packages/components/containers
petrpan-code/ProtonMail/WebClients/packages/components/containers/recovery/DailyEmailNotificationToggle.test.tsx
import { fireEvent, render, waitFor } from '@testing-library/react'; import DailyEmailNotificationToggle from './DailyEmailNotificationToggle'; describe('DailyEmailNotificationToggle', () => { describe('when annot enable', () => { it('should have disabled attribute', () => { const { container } = render( <DailyEmailNotificationToggle canEnable={false} isEnabled={false} onChange={jest.fn()} id="test-toggle" /> ); const input = container.querySelector('#test-toggle'); expect(input).toHaveAttribute('disabled', ''); }); }); describe('when can enable', () => { it('should check checkbox if enabled', () => { const { container } = render( <DailyEmailNotificationToggle canEnable={true} isEnabled={true} onChange={jest.fn()} id="test-toggle" /> ); const input = container.querySelector('#test-toggle'); expect(input).not.toHaveAttribute('disabled'); expect(input).toHaveAttribute('checked', ''); }); it('should emit onChange on click', async () => { const mockOnChange = jest.fn(); const { container } = render( <DailyEmailNotificationToggle canEnable={true} isEnabled={true} onChange={mockOnChange} id="test-toggle" /> ); const input = container.querySelector('#test-toggle'); fireEvent.click(input as HTMLElement); await waitFor(() => expect(mockOnChange).toHaveBeenCalledTimes(1)); }); }); });
6,856
0
petrpan-code/ProtonMail/WebClients/packages/components/containers/referral
petrpan-code/ProtonMail/WebClients/packages/components/containers/referral/helpers/fetchAllReferralsByOffset.test.ts
import { Api } from '@proton/shared/lib/interfaces'; import fetchAllReferralsByOffset from './fetchAllReferralsByOffset'; interface ApiResults { Referrals: number[]; Total: number; } describe('fetchAllReferralsByOffset', () => { it('Should make 1 call if total is inferior to limit', async () => { const apiSpy = jest.fn<Promise<ApiResults>, [Api]>(() => Promise.resolve({ Total: 10, Referrals: new Array(10), }) ); const { Referrals } = await fetchAllReferralsByOffset(apiSpy as Api); expect(apiSpy).toHaveBeenCalledTimes(1); expect(Referrals?.length).toBe(10); }); it('Should make 2 call if total is superior to limit', async () => { const LIMIT = 5; const TOTAL = 10; const CALLS_NUMBER = 2; const apiSpy = jest.fn<Promise<ApiResults>, [Api]>(() => Promise.resolve({ Total: 10, Referrals: new Array(LIMIT), }) ); const { Referrals } = await fetchAllReferralsByOffset(apiSpy as Api, { Limit: LIMIT, Offset: 0 }); expect(Referrals?.length).toBe(TOTAL); expect(apiSpy).toHaveBeenCalledTimes(CALLS_NUMBER); }); it('Should make 5 calls (4 of 100 and 1 of 60)', async () => { const TOTAL = 460; const CALLS_NUMBER = 5; let calls = 0; const apiSpy = jest.fn<Promise<ApiResults>, [Api]>(() => { calls += 1; return Promise.resolve({ Total: TOTAL, Referrals: calls < CALLS_NUMBER ? new Array(100) : new Array(60), }); }); const { Referrals } = await fetchAllReferralsByOffset(apiSpy as Api); expect(Referrals?.length).toBe(TOTAL); expect(apiSpy).toHaveBeenCalledTimes(CALLS_NUMBER); }); });
6,866
0
petrpan-code/ProtonMail/WebClients/packages/components/containers/referral
petrpan-code/ProtonMail/WebClients/packages/components/containers/referral/invite/helpers.test.ts
import { isValidEmailAdressToRefer } from './helpers'; describe('Referral helpers', () => { const addresses: [string, boolean][] = [ ['[email protected]', false], ['[email protected]', false], ['[email protected]', false], ['[email protected]', true], ['à[email protected]', false], ]; describe('isValidEmailAddress', () => { it.each(addresses)('%s should be %p', (address, expectedResult) => { expect(isValidEmailAdressToRefer(address)).toBe(expectedResult); }); }); });
6,967
0
petrpan-code/ProtonMail/WebClients/packages/components/containers/vpn
petrpan-code/ProtonMail/WebClients/packages/components/containers/vpn/WireGuardConfigurationSection/WireGuardConfigurationSection.test.ts
const fs = require('fs'); const path = require('path'); /** * This is a test to ensure the bigint polyfill patch is applied. It is intended to catch a scenario where the * ed25519 library may get updated and we won't get notified through the yarn install. */ describe('ed25519 library', () => { it('should polyfill bigint', () => { const file = fs.readFileSync(path.resolve(`${require.resolve('@noble/ed25519')}/../esm/index.js`)).toString(); expect( file.includes(`const BigInt = typeof window.BigInt !== 'undefined' ? window.BigInt : (() => 0);`) ).toBeTruthy(); }); });
7,012
0
petrpan-code/ProtonMail/WebClients/packages/components
petrpan-code/ProtonMail/WebClients/packages/components/helpers/url.test.ts
import { getHostname, isExternal, isMailTo, isSubDomain, isURLProtonInternal, punycodeUrl, } from '@proton/components/helpers/url'; import { mockWindowLocation, resetWindowLocation } from '@proton/components/helpers/url.test.helpers'; const windowHostname = 'mail.proton.me'; describe('isSubDomain', function () { it('should detect that same hostname is a subDomain', () => { const hostname = 'mail.proton.me'; expect(isSubDomain(hostname, hostname)).toBeTruthy(); }); it('should detect that domain is a subDomain', () => { const hostname = 'mail.proton.me'; const domain = 'proton.me'; expect(isSubDomain(hostname, domain)).toBeTruthy(); }); it('should detect that domain is not a subDomain', () => { const hostname = 'mail.proton.me'; const domain = 'whatever.com'; expect(isSubDomain(hostname, domain)).toBeFalsy(); }); }); describe('getHostname', function () { it('should give the correct hostname', () => { const hostname = 'mail.proton.me'; const url = `https://${hostname}/u/0/inbox`; expect(getHostname(url)).toEqual(hostname); }); }); describe('isMailTo', function () { it('should detect that the url is a mailto link', () => { const url = 'mailto:[email protected]'; expect(isMailTo(url)).toBeTruthy(); }); it('should detect that the url is not a mailto link', () => { const url = 'https://proton.me'; expect(isMailTo(url)).toBeFalsy(); }); }); describe('isExternal', function () { beforeEach(() => { mockWindowLocation(undefined, windowHostname); }); afterEach(() => { resetWindowLocation(); }); it('should detect that the url is not external', () => { const url1 = 'https://mail.proton.me'; expect(window.location.hostname).toEqual(windowHostname); expect(isExternal(url1)).toBeFalsy(); }); it('should detect that the url is external', () => { const url = 'https://url.whatever.com'; expect(window.location.hostname).toEqual(windowHostname); expect(isExternal(url)).toBeTruthy(); }); it('should detect that the mailto link is not external', () => { const url = 'mailto:[email protected]'; expect(window.location.hostname).toEqual(windowHostname); expect(isExternal(url)).toBeFalsy(); }); }); describe('isProtonInternal', function () { beforeEach(() => { mockWindowLocation(undefined, windowHostname); }); afterEach(() => { resetWindowLocation(); }); it('should detect that the url is proton internal', () => { const url1 = 'https://mail.proton.me'; const url2 = 'https://calendar.proton.me'; expect(isURLProtonInternal(url1)).toBeTruthy(); expect(isURLProtonInternal(url2)).toBeTruthy(); }); it('should detect that the url is not proton internal', () => { const url = 'https://url.whatever.com'; expect(isURLProtonInternal(url)).toBeFalsy(); }); }); describe('punycodeUrl', () => { it('should encode the url with punycode', () => { // reference: https://www.xudongz.com/blog/2017/idn-phishing/ const url = 'https://www.аррӏе.com'; const encodedUrl = punycodeUrl(url); expect(encodedUrl).toEqual('https://www.xn--80ak6aa92e.com'); }); it('should encode url with punycode and keep pathname, query parameters and fragment', () => { const url = 'https://www.äöü.com/ümläüts?ä=ö&ü=ä#ümläüts'; const encodedUrl = punycodeUrl(url); expect(encodedUrl).toEqual( 'https://www.xn--4ca0bs.com/%C3%BCml%C3%A4%C3%BCts?%C3%A4=%C3%B6&%C3%BC=%C3%A4#%C3%BCml%C3%A4%C3%BCts' ); }); it('should not encode url already punycode', () => { const url = 'https://www.xn--4ca0bs.com'; const encodedUrl = punycodeUrl(url); expect(encodedUrl).toEqual(url); }); it('should not encode url with no punycode', () => { const url = 'https://www.protonmail.com'; const encodedUrl = punycodeUrl(url); expect(encodedUrl).toEqual(url); }); it('should keep the trailing slash', () => { const url = 'https://www.äöü.com/EDEQWE/'; const encodedUrl = punycodeUrl(url); expect(encodedUrl).toEqual('https://www.xn--4ca0bs.com/EDEQWE/'); }); it('should keep the port', () => { const url = 'https://www.äöü.com:8080'; const encodedUrl = punycodeUrl(url); expect(encodedUrl).toEqual('https://www.xn--4ca0bs.com:8080'); }); it('should keep the trailing slash if hash or search after', () => { const sUrl = 'https://www.dude.com/r/?dude=buddy'; const encodedSUrl = punycodeUrl(sUrl); expect(encodedSUrl).toEqual('https://www.dude.com/r/?dude=buddy'); const hUrl = 'https://www.dude.com/r/#dude'; const encodedHUrl = punycodeUrl(hUrl); expect(encodedHUrl).toEqual('https://www.dude.com/r/#dude'); }); });
7,072
0
petrpan-code/ProtonMail/WebClients/packages/components
petrpan-code/ProtonMail/WebClients/packages/components/hooks/useFolderColor.test.ts
import { Folder } from '@proton/shared/lib/interfaces/Folder'; import { FOLDER_COLOR, INHERIT_PARENT_FOLDER_COLOR } from '@proton/shared/lib/mail/mailSettings'; import useFolderColor from './useFolderColor'; import { useMailSettings } from './useMailSettings'; const mockFolderSetting = FOLDER_COLOR.ENABLED; const mockinheritSetting = INHERIT_PARENT_FOLDER_COLOR.ENABLED; jest.mock('./useMailSettings', () => ({ useMailSettings: jest.fn(() => [ { EnableFolderColor: mockFolderSetting, InheritParentFolderColor: mockinheritSetting }, false, ]), })); jest.mock('./useCategories', () => ({ useFolders: () => [ [ { ID: 'A', Color: 'red' }, { ID: 'B', Color: 'blue', ParentID: 'A' }, { ID: 'C', Color: 'green', ParentID: 'B' }, ], false, ], })); describe('useFolderColor hook', () => { it('should not return color if EnableFolderColor is disabled', () => { (useMailSettings as jest.Mock).mockReturnValueOnce([ { EnableFolderColor: FOLDER_COLOR.DISABLED, InheritParentFolderColor: INHERIT_PARENT_FOLDER_COLOR.ENABLED }, false, ]); const folder = { ID: 'C', Color: 'green' } as Folder; const color = useFolderColor(folder); expect(color).toBe(undefined); }); it('should return current color if InheritParentFolderColor is disabled', () => { (useMailSettings as jest.Mock).mockReturnValueOnce([ { EnableFolderColor: FOLDER_COLOR.ENABLED, InheritParentFolderColor: INHERIT_PARENT_FOLDER_COLOR.DISABLED }, false, ]); const folder = { ID: 'C', Color: 'green', ParentID: 'B' } as Folder; const color = useFolderColor(folder); expect(color).toBe('green'); }); it('should return current folder color since it is a root', () => { const folder = { ID: 'C', Color: 'green' } as Folder; const color = useFolderColor(folder); expect(color).toBe('green'); }); it('should search for root folder color', () => { const folder = { ID: 'C', Color: 'green', ParentID: 'B' } as Folder; const color = useFolderColor(folder); expect(color).toBe('red'); }); });
7,119
0
petrpan-code/ProtonMail/WebClients/packages/components
petrpan-code/ProtonMail/WebClients/packages/components/hooks/useMyCountry.test.ts
import { getCountryFromLanguage } from './useMyCountry'; describe('getCountryFromLanguage()', () => { beforeEach(() => { jest.clearAllMocks(); }); it('should prioritize languages as given by the browser', () => { const mockNavigator = jest.spyOn(window, 'navigator', 'get'); mockNavigator.mockReturnValue({ ...window.navigator, languages: ['de-DE', 'en-EN'], }); expect(getCountryFromLanguage()).toEqual('de'); }); it('should prioritize languages with country code', () => { const mockNavigator = jest.spyOn(window, 'navigator', 'get'); mockNavigator.mockReturnValue({ ...window.navigator, languages: ['fr', 'en_CA'], }); expect(getCountryFromLanguage()).toEqual('ca'); }); it('should return undefined when the browser language tags do not have country code', () => { const mockNavigator = jest.spyOn(window, 'navigator', 'get'); mockNavigator.mockReturnValue({ ...window.navigator, languages: ['fr', 'en'], }); expect(getCountryFromLanguage()).toBeUndefined(); }); });
7,145
0
petrpan-code/ProtonMail/WebClients/packages/components
petrpan-code/ProtonMail/WebClients/packages/components/hooks/useSortedList.test.ts
import { act, renderHook } from '@testing-library/react-hooks'; import { SORT_DIRECTION } from '@proton/shared/lib/constants'; import useSortedList from './useSortedList'; describe('useSortedList hook', () => { it('should return sorted list initially if config is provided', () => { const list = [{ t: 2 }, { t: 3 }, { t: 1 }]; const { result } = renderHook(() => useSortedList(list, { key: 't', direction: SORT_DIRECTION.DESC })); expect(result.current.sortedList).toEqual([{ t: 3 }, { t: 2 }, { t: 1 }]); expect(result.current.sortConfig).toEqual({ key: 't', direction: SORT_DIRECTION.DESC }); }); it('should not sort initially if no config is provided', () => { const list = [{ t: 2 }, { t: 3 }, { t: 1 }]; const { result } = renderHook(() => useSortedList(list)); expect(result.current.sortedList).toEqual(list); expect(result.current.sortConfig).toBeUndefined(); }); it('should set initialize sorting config on sort when none was provided', () => { const list = [{ t: 2 }, { t: 3 }, { t: 1 }]; const { result } = renderHook(() => useSortedList(list)); act(() => result.current.toggleSort('t')); expect(result.current.sortedList).toEqual([{ t: 1 }, { t: 2 }, { t: 3 }]); expect(result.current.sortConfig).toEqual({ key: 't', direction: SORT_DIRECTION.ASC }); }); it('should toggle sort direction for the same key', () => { const list = [{ t: 2 }, { t: 3 }, { t: 1 }]; const { result } = renderHook(() => useSortedList(list, { key: 't', direction: SORT_DIRECTION.ASC })); expect(result.current.sortedList).toEqual([{ t: 1 }, { t: 2 }, { t: 3 }]); expect(result.current.sortConfig).toEqual({ key: 't', direction: SORT_DIRECTION.ASC }); act(() => result.current.toggleSort('t')); expect(result.current.sortedList).toEqual([{ t: 3 }, { t: 2 }, { t: 1 }]); expect(result.current.sortConfig).toEqual({ key: 't', direction: SORT_DIRECTION.DESC }); }); it('should change sort key and set direction to ascending for another key', () => { const list = [ { t: 2, k: 'c' }, { t: 3, k: 'b' }, { t: 1, k: 'a' }, ]; const { result } = renderHook(() => useSortedList(list, { key: 't', direction: SORT_DIRECTION.ASC })); expect(result.current.sortedList).toEqual([ { t: 1, k: 'a' }, { t: 2, k: 'c' }, { t: 3, k: 'b' }, ]); expect(result.current.sortConfig).toEqual({ key: 't', direction: SORT_DIRECTION.ASC }); act(() => result.current.toggleSort('k')); expect(result.current.sortedList).toEqual([ { t: 1, k: 'a' }, { t: 3, k: 'b' }, { t: 2, k: 'c' }, ]); expect(result.current.sortConfig).toEqual({ key: 'k', direction: SORT_DIRECTION.ASC }); }); });
7,188
0
petrpan-code/ProtonMail/WebClients/packages/components/payments/client-extensions
petrpan-code/ProtonMail/WebClients/packages/components/payments/client-extensions/validators/PaymentVerificationModal.test.tsx
import { render, screen, waitFor } from '@testing-library/react'; import { wait } from '@proton/shared/lib/helpers/promise'; import { applyHOCs, withNotifications } from '@proton/testing/index'; import PaymentVerificationModal, { PromiseWithController, Props } from './PaymentVerificationModal'; jest.mock('@proton/components/components/portal/Portal'); let props: Props; let promiseWithController: PromiseWithController; let promiseResolve: () => void; let promiseReject: (error: any) => void; beforeEach(() => { jest.clearAllMocks(); promiseWithController = { promise: new Promise((resolve, reject) => { promiseResolve = resolve; promiseReject = reject; }), abort: { abort: jest.fn(), } as any, }; props = { onSubmit: jest.fn(), onClose: jest.fn(), token: 'token123', onProcess: jest.fn().mockReturnValue(promiseWithController), }; }); const ContextPaymentVerificationModal = applyHOCs(withNotifications())(PaymentVerificationModal); it('should render', () => { const { container } = render(<ContextPaymentVerificationModal {...props} />); expect(container).not.toBeEmptyDOMElement(); }); it('should render redirect step by default', () => { render(<ContextPaymentVerificationModal {...props} />); expect(screen.getByTestId('redirect-message')).toBeInTheDocument(); expect(screen.getByText('Verify')).toBeInTheDocument(); }); it('should set redirecting step once user clicks on verify', () => { render(<ContextPaymentVerificationModal {...props} />); screen.getByText('Verify').click(); expect(screen.getByTestId('redirecting-message')).toBeInTheDocument(); }); it('should set redirected after processingDelay passes', async () => { const processingDelay = 100; render(<ContextPaymentVerificationModal {...props} processingDelay={processingDelay} />); screen.getByText('Verify').click(); await wait(processingDelay); expect(screen.getByTestId('redirected-message')).toBeInTheDocument(); }); it('should set fail step if promise rejects', async () => { render(<ContextPaymentVerificationModal {...props} />); screen.getByText('Verify').click(); promiseReject(new Error()); await screen.findByTestId('fail-message'); }); it('should call onSubmit and the onClose callback if promise resolves', async () => { render(<ContextPaymentVerificationModal {...props} />); screen.getByText('Verify').click(); promiseResolve(); await waitFor(() => expect(props.onSubmit).toHaveBeenCalledTimes(1)); expect(props.onClose).toHaveBeenCalledTimes(1); }); it('should abort the promise and call onClose if user cancels', async () => { const processingDelay = 100; render(<ContextPaymentVerificationModal {...props} processingDelay={processingDelay} />); screen.getByText('Verify').click(); await wait(processingDelay); screen.getByText('Cancel').click(); await waitFor(() => expect(props.onClose).toHaveBeenCalledTimes(1)); expect(promiseWithController.abort.abort).toHaveBeenCalledTimes(1); });
7,191
0
petrpan-code/ProtonMail/WebClients/packages/components/payments
petrpan-code/ProtonMail/WebClients/packages/components/payments/core/cardDetails.test.ts
import { CardModel, toDetails } from './cardDetails'; describe('cardDetails', () => { it('should format card details correctly', () => { let card: CardModel = { number: '4111 1111 1111 1111', month: '10', year: '2020', cvc: '123', zip: '123 45', country: 'US', }; expect(toDetails(card)).toEqual({ Number: '4111111111111111', ExpMonth: '10', ExpYear: '2020', CVC: '123', ZIP: '123 45', Country: 'US', }); card = { number: '4111 1111 1111 1111', month: '10', year: '32', cvc: '123', zip: '123 45', country: 'US', }; expect(toDetails(card)).toEqual({ Number: '4111111111111111', ExpMonth: '10', ExpYear: '2032', CVC: '123', ZIP: '123 45', Country: 'US', }); }); });
7,196
0
petrpan-code/ProtonMail/WebClients/packages/components/payments
petrpan-code/ProtonMail/WebClients/packages/components/payments/core/ensureTokenChargeable.test.ts
import { PAYMENT_TOKEN_STATUS } from './constants'; import { EnsureTokenChargeableTranslations, ensureTokenChargeable } from './ensureTokenChargeable'; let tab: { closed: boolean; close: () => any }; const translations: EnsureTokenChargeableTranslations = { processAbortedError: 'Process aborted', paymentProcessCanceledError: 'Payment process canceled', paymentProcessFailedError: 'Payment process failed', paymentProcessConsumedError: 'Payment process consumed', paymentProcessNotSupportedError: 'Payment process not supported', unknownPaymentTokenStatusError: 'Unknown payment token status', tabClosedError: 'Tab closed', }; describe('process', () => { let ApprovalURL = 'https://example.proton.me'; let ReturnHost = 'https://return.proton.me'; let Token = 'some-payment-token-222'; let api: jest.Mock; let signal: AbortSignal; beforeEach(() => { jest.clearAllMocks(); tab = { closed: false, close: jest.fn() }; jest.spyOn(window, 'open').mockReturnValue(tab as any); jest.spyOn(window, 'removeEventListener'); jest.spyOn(window, 'addEventListener'); api = jest.fn(); signal = { aborted: false, reason: null, onabort: jest.fn(), throwIfAborted: jest.fn(), addEventListener: jest.fn(), removeEventListener: jest.fn(), dispatchEvent: jest.fn(), }; }); it('should open the ApprovalURL', () => { tab.closed = true; // prevents the test from hanging because of an unhandled promise ensureTokenChargeable({ api, ApprovalURL, ReturnHost, signal, Token }, translations).catch(() => {}); expect(window.open).toHaveBeenCalledWith(ApprovalURL); }); it('should add abort listener to the signal', async () => { const promise = ensureTokenChargeable({ api, ApprovalURL, ReturnHost, signal, Token }, translations); expect(signal.addEventListener).toHaveBeenCalledTimes(1); const signalAddEventListenerMock = signal.addEventListener as jest.Mock; expect(signalAddEventListenerMock.mock.lastCall[0]).toEqual('abort'); expect(typeof signalAddEventListenerMock.mock.lastCall[1]).toBe('function'); expect(window.addEventListener).toHaveBeenCalledTimes(1); const windowAddEventListenerMock = window.addEventListener as jest.Mock; expect(windowAddEventListenerMock.mock.lastCall[0]).toEqual('message'); expect(typeof windowAddEventListenerMock.mock.lastCall[1]).toEqual('function'); const onMessage = windowAddEventListenerMock.mock.lastCall[1]; const abort = signalAddEventListenerMock.mock.lastCall[1]; abort(); expect(window.removeEventListener).toHaveBeenCalledWith('message', onMessage, false); expect(signal.removeEventListener).toHaveBeenCalledWith('abort', abort); expect(tab.close).toHaveBeenCalled(); await expect(promise).rejects.toEqual(new Error('Process aborted')); }); it('should resolve if Status is STATUS_CHARGEABLE', async () => { tab.closed = true; api.mockResolvedValue({ Status: PAYMENT_TOKEN_STATUS.STATUS_CHARGEABLE, }); const promise = ensureTokenChargeable({ api, ApprovalURL, ReturnHost, signal, Token }, translations); await expect(promise).resolves.toEqual(undefined); }); it.each([ PAYMENT_TOKEN_STATUS.STATUS_PENDING, PAYMENT_TOKEN_STATUS.STATUS_FAILED, PAYMENT_TOKEN_STATUS.STATUS_CONSUMED, PAYMENT_TOKEN_STATUS.STATUS_NOT_SUPPORTED, ])('should reject if Status is %s', async (Status) => { tab.closed = true; api.mockResolvedValue({ Status, }); const promise = ensureTokenChargeable({ api, ApprovalURL, ReturnHost, signal, Token }, translations); await expect(promise).rejects.toEqual({ tryAgain: true }); }); it('should re-try to confirm until the tab is closed', async () => { api.mockResolvedValue({ Status: PAYMENT_TOKEN_STATUS.STATUS_CHARGEABLE, }); const delayListening = 10; const promise = ensureTokenChargeable( { api, ApprovalURL, ReturnHost, signal, Token }, translations, delayListening ); jest.runAllTimers(); tab.closed = true; await expect(promise).resolves.toEqual(undefined); }); });
7,200
0
petrpan-code/ProtonMail/WebClients/packages/components/payments
petrpan-code/ProtonMail/WebClients/packages/components/payments/core/methods.test.ts
import { queryPaymentMethodStatus, queryPaymentMethods } from '@proton/shared/lib/api/payments'; import { BLACK_FRIDAY } from '@proton/shared/lib/constants'; import { PAYMENT_METHOD_TYPES } from './constants'; import { Autopay, PaymentMethodFlows, PaymentMethodStatus, SavedPaymentMethod } from './interface'; import { PaymentMethods, initializePaymentMethods } from './methods'; let status: PaymentMethodStatus; beforeEach(() => { status = { Card: true, Paypal: true, Apple: true, Cash: true, Bitcoin: true, }; }); describe('getNewMethods()', () => { it('should include card when card is available', () => { const methods = new PaymentMethods(status, [], 500, '', 'subscription'); expect(methods.getNewMethods().some((method) => method.type === 'card')).toBe(true); }); it('should not include card when card is not available', () => { status.Card = false; const methods = new PaymentMethods(status, [], 500, '', 'subscription'); expect(methods.getNewMethods().some((method) => method.type === 'card')).toBe(false); }); // tests for PayPal it('should include PayPal when PayPal is available', () => { const methods = new PaymentMethods(status, [], 500, '', 'subscription'); expect(methods.getNewMethods().some((method) => method.type === 'paypal')).toBe(true); }); it('should not include PayPal when PayPal is not available due to amount less than minimum', () => { const methods = new PaymentMethods(status, [], 50, '', 'subscription'); expect(methods.getNewMethods().some((method) => method.type === 'paypal')).toBe(false); }); it('should not include PayPal when already used as payment method', () => { const methods = new PaymentMethods( status, [ { ID: '1', Type: PAYMENT_METHOD_TYPES.PAYPAL, Order: 500, Details: { BillingAgreementID: 'BA-123', PayerID: '123', Payer: '123', }, }, ], 500, '', 'subscription' ); expect(methods.getNewMethods().some((method) => method.type === 'paypal')).toBe(false); }); it('should include Bitcoin when Bitcoin is available', () => { const methods = new PaymentMethods(status, [], 500, '', 'subscription'); expect(methods.getNewMethods().some((method) => method.type === 'bitcoin')).toBe(true); }); it('should not include Bitcoin when Bitcoin is not available due to coupon', () => { const methods = new PaymentMethods(status, [], 500, BLACK_FRIDAY.COUPON_CODE, 'subscription'); expect(methods.getNewMethods().some((method) => method.type === 'bitcoin')).toBe(false); }); it.each(['signup', 'human-verification'] as PaymentMethodFlows[])( 'should not include Bitcoin when Bitcoin is not available due to flow %s', (flow) => { const methods = new PaymentMethods(status, [], 500, '', flow); expect(methods.getNewMethods().some((method) => method.type === 'bitcoin')).toBe(false); } ); it('should not include bitcoin due to amount less than minimum', () => { const methods = new PaymentMethods(status, [], 50, '', 'subscription'); expect(methods.getNewMethods().some((method) => method.type === 'bitcoin')).toBe(false); }); it('should include Cash when Cash is available', () => { const methods = new PaymentMethods(status, [], 500, '', 'subscription'); expect(methods.getNewMethods().some((method) => method.type === 'cash')).toBe(true); }); it('should not include Cash when Cash is not available due to coupon', () => { const methods = new PaymentMethods(status, [], 500, BLACK_FRIDAY.COUPON_CODE, 'subscription'); expect(methods.getNewMethods().some((method) => method.type === 'cash')).toBe(false); }); it.each(['signup', 'signup-pass', 'human-verification'] as PaymentMethodFlows[])( 'should not include Cash when Cash is not available due to flow %s', (flow) => { const methods = new PaymentMethods(status, [], 500, '', flow); expect(methods.getNewMethods().some((method) => method.type === 'cash')).toBe(false); } ); }); describe('getUsedMethods()', () => { it('should return used methods: paypal and cards', () => { const methods = new PaymentMethods( status, [ { ID: '1', Type: PAYMENT_METHOD_TYPES.PAYPAL, Order: 500, Details: { BillingAgreementID: 'BA-123', PayerID: '123', Payer: '123', }, }, { ID: '2', Type: PAYMENT_METHOD_TYPES.CARD, Order: 501, Autopay: Autopay.ENABLE, Details: { Name: 'Arthur Morgan', ExpMonth: '12', ExpYear: '2030', ZIP: '12345', Country: 'US', Last4: '1234', Brand: 'Visa', }, }, // one more card { ID: '3', Type: PAYMENT_METHOD_TYPES.CARD, Order: 502, Autopay: Autopay.ENABLE, Details: { Name: 'Arthur Morgan', ExpMonth: '11', ExpYear: '2031', ZIP: '12345', Country: 'US', Last4: '4242', Brand: 'Visa', }, }, ], 500, '', 'subscription' ); expect(methods.getUsedMethods().some((method) => method.type === 'paypal')).toBe(true); expect(methods.getUsedMethods().some((method) => method.value === '1')).toBe(true); expect(methods.getUsedMethods().filter((method) => method.type === 'card').length).toBe(2); expect(methods.getUsedMethods().some((method) => method.value === '2')).toBe(true); expect(methods.getUsedMethods().some((method) => method.value === '3')).toBe(true); }); }); describe('getAvailablePaymentMethods()', () => { it('should return combination of new and used methods', () => { const methods = new PaymentMethods( status, [ { ID: '1', Type: PAYMENT_METHOD_TYPES.PAYPAL, Order: 500, Details: { BillingAgreementID: 'BA-123', PayerID: '123', Payer: '123', }, }, { ID: '2', Type: PAYMENT_METHOD_TYPES.CARD, Order: 501, Autopay: Autopay.ENABLE, Details: { Name: 'Arthur Morgan', ExpMonth: '12', ExpYear: '2030', ZIP: '12345', Country: 'US', Last4: '1234', Brand: 'Visa', }, }, // one more card { ID: '3', Type: PAYMENT_METHOD_TYPES.CARD, Order: 502, Autopay: Autopay.ENABLE, Details: { Name: 'Arthur Morgan', ExpMonth: '11', ExpYear: '2031', ZIP: '12345', Country: 'US', Last4: '4242', Brand: 'Visa', }, }, ], 500, '', 'subscription' ); const availableMethods = methods.getAvailablePaymentMethods(); expect(availableMethods.usedMethods.some((method) => method.type === 'paypal')).toBe(true); expect(availableMethods.usedMethods.some((method) => method.value === '1')).toBe(true); expect(availableMethods.usedMethods.filter((method) => method.type === 'card').length).toBe(2); expect(availableMethods.usedMethods.some((method) => method.value === '2')).toBe(true); expect(availableMethods.usedMethods.some((method) => method.value === '3')).toBe(true); // if paypal already saved, it can't be a new method too expect(availableMethods.methods.some((method) => method.type === 'paypal')).toBe(false); expect(availableMethods.methods.some((method) => method.type === 'card')).toBe(true); }); }); describe('getLastUsedMethod()', () => { it('should return last used method', () => { const methods = new PaymentMethods( status, [ { ID: '1', Type: PAYMENT_METHOD_TYPES.PAYPAL, Order: 500, Details: { BillingAgreementID: 'BA-123', PayerID: '123', Payer: '123', }, }, { ID: '2', Type: PAYMENT_METHOD_TYPES.CARD, Order: 501, Autopay: Autopay.ENABLE, Details: { Name: 'Arthur Morgan', ExpMonth: '12', ExpYear: '2030', ZIP: '12345', Country: 'US', Last4: '1234', Brand: 'Visa', }, }, // one more card { ID: '3', Type: PAYMENT_METHOD_TYPES.CARD, Order: 502, Autopay: Autopay.ENABLE, Details: { Name: 'Arthur Morgan', ExpMonth: '11', ExpYear: '2031', ZIP: '12345', Country: 'US', Last4: '4242', Brand: 'Visa', }, }, ], 500, '', 'subscription' ); const lastUsedMethod = methods.getLastUsedMethod(); expect(lastUsedMethod).toEqual({ type: PAYMENT_METHOD_TYPES.PAYPAL, paymentMethodId: '1', value: '1', isSaved: true, isExpired: false, }); }); }); describe('getSavedMethodById()', () => { it('should return the correct saved method by id', () => { const methods = new PaymentMethods( status, [ { ID: '1', Type: PAYMENT_METHOD_TYPES.PAYPAL, Order: 500, Details: { BillingAgreementID: 'BA-123', PayerID: '123', Payer: '123', }, }, { ID: '2', Type: PAYMENT_METHOD_TYPES.CARD, Order: 501, Autopay: Autopay.ENABLE, Details: { Name: 'Arthur Morgan', ExpMonth: '12', ExpYear: '2030', ZIP: '12345', Country: 'US', Last4: '1234', Brand: 'Visa', }, }, // one more card { ID: '3', Type: PAYMENT_METHOD_TYPES.CARD, Order: 502, Autopay: Autopay.ENABLE, Details: { Name: 'Arthur Morgan', ExpMonth: '11', ExpYear: '2031', ZIP: '12345', Country: 'US', Last4: '4242', Brand: 'Visa', }, }, ], 500, '', 'subscription' ); const savedMethod = methods.getSavedMethodById('2'); expect(savedMethod).toEqual({ ID: '2', Type: PAYMENT_METHOD_TYPES.CARD, Order: 501, Autopay: Autopay.ENABLE, Details: { Name: 'Arthur Morgan', ExpMonth: '12', ExpYear: '2030', ZIP: '12345', Country: 'US', Last4: '1234', Brand: 'Visa', }, }); }); }); describe('initializePaymentMethods()', () => { it('should correctly initialize payment methods', async () => { const apiMock = jest.fn(); const paymentMethodStatus: PaymentMethodStatus = { Card: true, Paypal: true, Apple: true, Cash: true, Bitcoin: true, }; const paymentMethods: SavedPaymentMethod[] = [ { ID: '1', Type: PAYMENT_METHOD_TYPES.CARD, Order: 500, Autopay: Autopay.ENABLE, Details: { Name: 'Arthur Morgan', ExpMonth: '12', ExpYear: '2030', ZIP: '12345', Country: 'US', Last4: '1234', Brand: 'Visa', }, }, ]; apiMock.mockImplementation(({ url }) => { if (url === queryPaymentMethods().url) { return { PaymentMethods: paymentMethods, }; } if (url === queryPaymentMethodStatus().url) { return paymentMethodStatus; } }); const methods = await initializePaymentMethods( apiMock, undefined, undefined, true, 500, 'coupon', 'subscription' as PaymentMethodFlows ); expect(methods).toBeDefined(); expect(methods.flow).toEqual('subscription'); expect(methods.amount).toEqual(500); expect(methods.coupon).toEqual('coupon'); expect(methods.getAvailablePaymentMethods().methods.length).toBeGreaterThan(0); }); it('should correctly initialize payment methods when user is not authenticated', async () => { const apiMock = jest.fn(); const paymentMethodStatus: PaymentMethodStatus = { Card: true, Paypal: true, Apple: true, Cash: true, Bitcoin: true, }; apiMock.mockImplementation(({ url }) => { if (url === queryPaymentMethodStatus().url) { return paymentMethodStatus; } }); const methods = await initializePaymentMethods( apiMock, undefined, undefined, false, 500, 'coupon', 'subscription' as PaymentMethodFlows ); expect(methods).toBeDefined(); expect(methods.flow).toEqual('subscription'); expect(methods.amount).toEqual(500); expect(methods.coupon).toEqual('coupon'); expect(methods.getAvailablePaymentMethods().methods.length).toBeGreaterThan(0); }); });
7,203
0
petrpan-code/ProtonMail/WebClients/packages/components/payments/core
petrpan-code/ProtonMail/WebClients/packages/components/payments/core/payment-processors/cardPayment.test.ts
import { MOCK_TOKEN_RESPONSE, addTokensResolver, addTokensResponse, apiMock } from '@proton/testing'; import { CardModel, getDefaultCard } from '../cardDetails'; import { PAYMENT_METHOD_TYPES, PAYMENT_TOKEN_STATUS } from '../constants'; import { AmountAndCurrency, ChargeablePaymentToken, TokenPaymentMethod } from '../interface'; import { CardPaymentProcessor } from './cardPayment'; describe('CardPaymentProcessor', () => { let paymentProcessor: CardPaymentProcessor; const mockVerifyPayment = jest.fn(); const mockHandler = jest.fn(); const amountAndCurrency: AmountAndCurrency = { Amount: 1000, Currency: 'USD', }; const onTokenIsChargeable = jest.fn().mockResolvedValue(null); let mockCard: CardModel; beforeEach(() => { addTokensResponse(); paymentProcessor = new CardPaymentProcessor( mockVerifyPayment, apiMock, amountAndCurrency, false, onTokenIsChargeable ); mockCard = { number: '4111111111111111', month: '01', year: '32', cvc: '123', zip: '12345', country: 'US', }; paymentProcessor.updateState({ card: mockCard, }); }); afterEach(() => { jest.clearAllMocks(); }); it('should update state correctly', () => { const newState = { cardSubmitted: true }; paymentProcessor.updateState(newState); expect(paymentProcessor.cardSubmitted).toEqual(true); }); it('should call handler when state is updated', () => { paymentProcessor.onStateUpdated(mockHandler); const newState = { cardSubmitted: true }; paymentProcessor.updateState(newState); expect(mockHandler).toHaveBeenCalledWith({ cardSubmitted: true, }); }); it('should remove handler correctly by id', () => { const id = paymentProcessor.onStateUpdated(mockHandler); paymentProcessor.removeHandler(id); const newState = { cardSubmitted: true }; paymentProcessor.updateState(newState); expect(mockHandler).not.toHaveBeenCalled(); }); it('should remove handler correctly by handler', () => { paymentProcessor.onStateUpdated(mockHandler); paymentProcessor.removeHandler(mockHandler); const newState = { cardSubmitted: true }; paymentProcessor.updateState(newState); expect(mockHandler).not.toHaveBeenCalled(); }); it('should clear all handlers', () => { const otherHandler = jest.fn(); paymentProcessor.onStateUpdated(mockHandler); paymentProcessor.onStateUpdated(otherHandler); paymentProcessor.clearHandlers(); const newState = { cardSubmitted: true }; paymentProcessor.updateState(newState); expect(mockHandler).not.toHaveBeenCalled(); expect(otherHandler).not.toHaveBeenCalled(); }); it('should return ChargeablePaymentToken right away when amount is 0', async () => { paymentProcessor.amountAndCurrency = { Amount: 0, Currency: 'USD', }; await paymentProcessor.fetchPaymentToken(); const result = await paymentProcessor.verifyPaymentToken(); expect(result).toEqual({ type: PAYMENT_METHOD_TYPES.CARD, chargeable: true, ...paymentProcessor.amountAndCurrency, }); expect(onTokenIsChargeable).toHaveBeenCalledWith(result); }); it('should throw error when method is card but the data is not valid', async () => { paymentProcessor.updateState({ card: getDefaultCard() }); await expect(paymentProcessor.fetchPaymentToken()).rejects.toThrowError(); }); it('should call onTokenIsChargeable when amount is 0 upon returing the token', async () => { paymentProcessor.amountAndCurrency = { Amount: 0, Currency: 'USD', }; await paymentProcessor.fetchPaymentToken(); await paymentProcessor.verifyPaymentToken(); expect(onTokenIsChargeable).toHaveBeenCalled(); }); it('should call onTokenIsChargeable when amount is not 0 upon returing the token', async () => { const expectedResult: ChargeablePaymentToken = { type: PAYMENT_METHOD_TYPES.CARD, ...paymentProcessor.amountAndCurrency, chargeable: true, Payment: { Type: PAYMENT_METHOD_TYPES.TOKEN, Details: { Token: MOCK_TOKEN_RESPONSE.Token, }, }, }; await paymentProcessor.fetchPaymentToken(); const result = await paymentProcessor.verifyPaymentToken(); expect(result).toEqual(expectedResult); expect(onTokenIsChargeable).toHaveBeenCalledWith(result); }); it('should set processingPayment to false when preparePaymentToken throws error', async () => { const { reject } = addTokensResolver(); const promise = paymentProcessor.fetchPaymentToken(); const error = new Error('error'); reject(error); await expect(promise).rejects.toThrowError(error); }); it('should call mockVerifyPayment', async () => { addTokensResponse({ ...MOCK_TOKEN_RESPONSE, Status: PAYMENT_TOKEN_STATUS.STATUS_PENDING, ApprovalURL: 'https://verify.proton.me', ReturnHost: 'https://proton.me', } as any); const returnToken: TokenPaymentMethod = { Payment: { Type: PAYMENT_METHOD_TYPES.TOKEN, Details: { Token: 'token123', }, }, }; mockVerifyPayment.mockResolvedValue(returnToken); await paymentProcessor.fetchPaymentToken(); const result = await paymentProcessor.verifyPaymentToken(); expect(mockVerifyPayment).toHaveBeenCalledWith({ ApprovalURL: 'https://verify.proton.me', ReturnHost: 'https://proton.me', Token: 'token123', Payment: { Details: { CVC: '123', Country: 'US', ExpMonth: '01', ExpYear: '2032', Number: '4111111111111111', ZIP: '12345', }, Type: 'card', }, addCardMode: false, }); expect(result).toEqual( expect.objectContaining({ type: PAYMENT_METHOD_TYPES.CARD, chargeable: true, ...paymentProcessor.amountAndCurrency, Payment: { Details: { Token: 'token123', }, Type: 'token', }, }) ); expect(onTokenIsChargeable).toHaveBeenCalledWith(result); }); it('should throw when verifyPaymentToken is called before fetchPaymentToken', async () => { await expect(paymentProcessor.verifyPaymentToken()).rejects.toThrowError(); }); it('should throw when verification failed', async () => { addTokensResponse({ ...MOCK_TOKEN_RESPONSE, Status: PAYMENT_TOKEN_STATUS.STATUS_PENDING, ApprovalURL: 'https://verify.proton.me', ReturnHost: 'https://proton.me', } as any); const error = new Error('error'); mockVerifyPayment.mockRejectedValue(error); await paymentProcessor.fetchPaymentToken(); await expect(paymentProcessor.verifyPaymentToken()).rejects.toThrowError(error); }); it('should remove the payment token', async () => { await paymentProcessor.fetchPaymentToken(); expect(paymentProcessor.fetchedPaymentToken).toBeTruthy(); paymentProcessor.reset(); expect(paymentProcessor.fetchedPaymentToken).toEqual(null); }); });
7,205
0
petrpan-code/ProtonMail/WebClients/packages/components/payments/core
petrpan-code/ProtonMail/WebClients/packages/components/payments/core/payment-processors/paymentProcessor.test.ts
import { CardModel, getDefaultCard } from '../cardDetails'; import { AmountAndCurrency, ChargeablePaymentParameters, ChargeablePaymentToken, NonChargeablePaymentToken, } from '../interface'; import { PaymentProcessor } from './paymentProcessor'; class PaymentProcessorTest extends PaymentProcessor<{ card: CardModel }> { fetchPaymentToken(): Promise<ChargeablePaymentToken | NonChargeablePaymentToken> { throw new Error('Method not implemented.'); } verifyPaymentToken(): Promise<ChargeablePaymentParameters> { throw new Error('Method not implemented.'); } } describe('PaymentProcessor', () => { let paymentProcessor: PaymentProcessor<{ card: CardModel }>; const amountAndCurrency: AmountAndCurrency = { Amount: 1000, Currency: 'USD', }; const mockHandler = jest.fn(); beforeEach(() => { paymentProcessor = new PaymentProcessorTest({ card: getDefaultCard() }, amountAndCurrency); }); afterEach(() => { jest.clearAllMocks(); }); it('should call the handler when the state is updated', () => { paymentProcessor.onStateUpdated(mockHandler); const newState = { card: { ...getDefaultCard(), number: '4242424242424242' } }; paymentProcessor.updateState(newState); expect(mockHandler).toHaveBeenCalledWith(newState); }); it('should return an id when a new handler is added', () => { const id = paymentProcessor.onStateUpdated(mockHandler); expect(typeof id).toEqual('string'); }); it('should not call the handler when the state is updated after the processor was destroyed', () => { paymentProcessor.onStateUpdated(mockHandler); paymentProcessor.destroy(); const newState = { card: { ...getDefaultCard(), number: '4242424242424242' } }; paymentProcessor.updateState(newState); expect(mockHandler).not.toHaveBeenCalled(); }); it('should not call the handler when the state is updated after the handler was removed', () => { const id = paymentProcessor.onStateUpdated(mockHandler); paymentProcessor.removeHandler(id); const newState = { card: { ...getDefaultCard(), number: '4242424242424242' } }; paymentProcessor.updateState(newState); expect(mockHandler).not.toHaveBeenCalled(); }); it('should not call the handler when the state is updated after the handler was removed by handler instance', () => { paymentProcessor.onStateUpdated(mockHandler); paymentProcessor.removeHandler(mockHandler); const newState = { card: { ...getDefaultCard(), number: '4242424242424242' } }; paymentProcessor.updateState(newState); expect(mockHandler).not.toHaveBeenCalled(); }); });
7,207
0
petrpan-code/ProtonMail/WebClients/packages/components/payments/core
petrpan-code/ProtonMail/WebClients/packages/components/payments/core/payment-processors/paypalPayment.test.ts
import { MAX_CREDIT_AMOUNT, MIN_PAYPAL_AMOUNT } from '@proton/shared/lib/constants'; import { MOCK_TOKEN_RESPONSE, addTokensResolver, addTokensResponse, apiMock } from '@proton/testing'; import { PAYMENT_METHOD_TYPES, PAYMENT_TOKEN_STATUS } from '../constants'; import { AmountAndCurrency, ChargeablePaymentParameters, TokenPaymentMethod } from '../interface'; import { PaypalPaymentProcessor, PaypalWrongAmountError } from './paypalPayment'; describe('PaypalPaymentProcessor', () => { let paymentProcessor: PaypalPaymentProcessor; const mockVerifyPayment = jest.fn(); const mockHandler = jest.fn(); const amountAndCurrency: AmountAndCurrency = { Amount: 1000, Currency: 'USD', }; const onTokenIsChargeable = jest.fn().mockResolvedValue(null); const isCredit = false; function resetPaymentProcessor() { paymentProcessor = new PaypalPaymentProcessor( mockVerifyPayment, apiMock, amountAndCurrency, isCredit, onTokenIsChargeable ); } beforeEach(() => { addTokensResponse(); resetPaymentProcessor(); }); afterEach(() => { jest.clearAllMocks(); }); it('should call handler when token is fetched', async () => { paymentProcessor.onStateUpdated(mockHandler); const result = await paymentProcessor.fetchPaymentToken(); expect(mockHandler).toHaveBeenCalledWith({ fetchedPaymentToken: expect.objectContaining({ Amount: 1000, Currency: 'USD', chargeable: true, type: PAYMENT_METHOD_TYPES.PAYPAL, Payment: expect.objectContaining({ Details: { Token: MOCK_TOKEN_RESPONSE.Token, }, }), }), }); expect(result).toEqual( expect.objectContaining({ Amount: 1000, Currency: 'USD', chargeable: true, type: PAYMENT_METHOD_TYPES.PAYPAL, Payment: expect.objectContaining({ Details: { Token: MOCK_TOKEN_RESPONSE.Token, }, }), }) ); }); it('should return ChargeablePaymentToken right away when amount is 0', async () => { paymentProcessor.amountAndCurrency = { Amount: 0, Currency: 'USD', }; await paymentProcessor.fetchPaymentToken(); const result = await paymentProcessor.verifyPaymentToken(); expect(result).toEqual( expect.objectContaining({ type: PAYMENT_METHOD_TYPES.PAYPAL, chargeable: true, ...paymentProcessor.amountAndCurrency, }) ); expect(onTokenIsChargeable).toHaveBeenCalledWith(result); }); it('should call onTokenIsChargeable when amount is 0 upon returing the token', async () => { paymentProcessor.amountAndCurrency = { Amount: 0, Currency: 'USD', }; await paymentProcessor.fetchPaymentToken(); await paymentProcessor.verifyPaymentToken(); expect(onTokenIsChargeable).toHaveBeenCalled(); }); it('should call onTokenIsChargeable when amount is not 0 upon returing the token', async () => { const expectedResult: ChargeablePaymentParameters = { type: PAYMENT_METHOD_TYPES.PAYPAL, ...paymentProcessor.amountAndCurrency, chargeable: true, Payment: { Type: PAYMENT_METHOD_TYPES.TOKEN, Details: { Token: MOCK_TOKEN_RESPONSE.Token, }, }, }; await paymentProcessor.fetchPaymentToken(); const result = await paymentProcessor.verifyPaymentToken(); expect(result).toEqual(expectedResult); expect(onTokenIsChargeable).toHaveBeenCalledWith(result); }); it('should set processingPayment to false when preparePaymentToken throws error', async () => { const { reject } = addTokensResolver(); const promise = paymentProcessor.fetchPaymentToken(); const error = new Error('error'); reject(error); await expect(promise).rejects.toThrowError(error); }); it('should call mockVerifyPayment', async () => { addTokensResponse({ ...MOCK_TOKEN_RESPONSE, Status: PAYMENT_TOKEN_STATUS.STATUS_PENDING, ApprovalURL: 'https://verify.proton.me', ReturnHost: 'https://proton.me', } as any); const returnToken: TokenPaymentMethod = { Payment: { Type: PAYMENT_METHOD_TYPES.TOKEN, Details: { Token: 'token123', }, }, }; mockVerifyPayment.mockResolvedValue(returnToken); await paymentProcessor.fetchPaymentToken(); const result = await paymentProcessor.verifyPaymentToken(); expect(mockVerifyPayment).toHaveBeenCalledWith({ ApprovalURL: 'https://verify.proton.me', Payment: { Type: PAYMENT_METHOD_TYPES.PAYPAL, }, ReturnHost: 'https://proton.me', Token: 'token123', }); expect(result).toEqual( expect.objectContaining({ type: PAYMENT_METHOD_TYPES.PAYPAL, chargeable: true, ...paymentProcessor.amountAndCurrency, Payment: { Details: { Token: 'token123', }, Type: 'token', }, }) ); expect(onTokenIsChargeable).toHaveBeenCalledWith(result); }); it('should throw error when verifyPaymentToken is called without token', async () => { await expect(paymentProcessor.verifyPaymentToken()).rejects.toThrowError('Payment token is not fetched'); }); it('should save the error and re-trhrow it', async () => { addTokensResponse({ ...MOCK_TOKEN_RESPONSE, Status: PAYMENT_TOKEN_STATUS.STATUS_PENDING, ApprovalURL: 'https://verify.proton.me', ReturnHost: 'https://proton.me', } as any); mockVerifyPayment.mockRejectedValue(new Error('some error')); await paymentProcessor.fetchPaymentToken(); await expect(paymentProcessor.verifyPaymentToken()).rejects.toThrowError('some error'); expect(paymentProcessor.verificationError).toEqual(new Error('Paypal payment verification failed')); }); it('should update disabled state depending on the amount', () => { paymentProcessor.setAmountAndCurrency({ Amount: 0, Currency: 'USD', }); expect(paymentProcessor.disabled).toBe(false); paymentProcessor.setAmountAndCurrency({ Amount: MIN_PAYPAL_AMOUNT - 1, Currency: 'USD', }); expect(paymentProcessor.disabled).toBe(true); paymentProcessor.setAmountAndCurrency({ Amount: MIN_PAYPAL_AMOUNT, Currency: 'USD', }); expect(paymentProcessor.disabled).toBe(false); paymentProcessor.setAmountAndCurrency({ Amount: (MAX_CREDIT_AMOUNT + MIN_PAYPAL_AMOUNT) / 2, Currency: 'EUR', }); expect(paymentProcessor.disabled).toBe(false); paymentProcessor.setAmountAndCurrency({ Amount: MAX_CREDIT_AMOUNT, Currency: 'USD', }); expect(paymentProcessor.disabled).toBe(false); paymentProcessor.setAmountAndCurrency({ Amount: MAX_CREDIT_AMOUNT + 1, Currency: 'USD', }); expect(paymentProcessor.disabled).toBe(true); }); it('should throw when amount is not in range', async () => { paymentProcessor.setAmountAndCurrency({ Amount: MIN_PAYPAL_AMOUNT - 1, Currency: 'USD', }); await expect(() => paymentProcessor.fetchPaymentToken()).rejects.toThrowError(PaypalWrongAmountError); resetPaymentProcessor(); paymentProcessor.setAmountAndCurrency({ Amount: MAX_CREDIT_AMOUNT + 1, Currency: 'USD', }); await expect(() => paymentProcessor.fetchPaymentToken()).rejects.toThrowError(PaypalWrongAmountError); resetPaymentProcessor(); paymentProcessor.setAmountAndCurrency({ Amount: MIN_PAYPAL_AMOUNT, Currency: 'USD', }); const token = await paymentProcessor.fetchPaymentToken(); expect(token).toBeDefined(); }); it('should throw when amount is not in range (no resets)', async () => { paymentProcessor.setAmountAndCurrency({ Amount: MIN_PAYPAL_AMOUNT - 1, Currency: 'USD', }); await expect(() => paymentProcessor.fetchPaymentToken()).rejects.toThrowError(PaypalWrongAmountError); paymentProcessor.setAmountAndCurrency({ Amount: MAX_CREDIT_AMOUNT + 1, Currency: 'USD', }); await expect(() => paymentProcessor.fetchPaymentToken()).rejects.toThrowError(PaypalWrongAmountError); paymentProcessor.setAmountAndCurrency({ Amount: MIN_PAYPAL_AMOUNT, Currency: 'USD', }); const token = await paymentProcessor.fetchPaymentToken(); expect(token).toBeDefined(); }); // It's necessary to keep the error to support the retry mechanism properly. // Properly means: when there is an error, the user sees Retry button. When the user clicks on it, // the error is removed and the token is fetched again. Very important: the token is NOT verified until user // clicks on the button the second time. This is because Safari doesn't allow to open a new window without // a synchronous user action handling. So, we need to wait for the user to click on the button and then // open the window. it('should remove token and KEEP error on reset()', () => { const error = new Error('error'); paymentProcessor.updateState({ fetchedPaymentToken: 'token' as any, verificationError: error, }); paymentProcessor.reset(); expect(paymentProcessor.fetchedPaymentToken).toBeNull(); expect(paymentProcessor.verificationError).toBe(error); }); });
7,209
0
petrpan-code/ProtonMail/WebClients/packages/components/payments/core
petrpan-code/ProtonMail/WebClients/packages/components/payments/core/payment-processors/savedPayment.test.ts
import { MOCK_TOKEN_RESPONSE, addTokensResponse, apiMock } from '@proton/testing'; import { PAYMENT_METHOD_TYPES, PAYMENT_TOKEN_STATUS } from '../constants'; import { AmountAndCurrency, Autopay, SavedPaymentMethod, TokenPaymentMethod } from '../interface'; import { SavedPaymentProcessor } from './savedPayment'; describe('SavedPaymentProcessor', () => { let savedPaymentProcessor: SavedPaymentProcessor; const mockVerifyPayment = jest.fn(); const amountAndCurrency: AmountAndCurrency = { Amount: 1000, Currency: 'USD', }; const onTokenIsChargeable = jest.fn().mockResolvedValue(null); const savedMethod: SavedPaymentMethod = { ID: '123', Type: PAYMENT_METHOD_TYPES.CARD, Order: 500, Autopay: Autopay.ENABLE, Details: { Name: 'Arthur Morgan', ExpMonth: '12', ExpYear: '2032', ZIP: '12345', Country: 'US', Last4: '4242', Brand: 'Visa', }, }; beforeEach(() => { addTokensResponse(); savedPaymentProcessor = new SavedPaymentProcessor( mockVerifyPayment, apiMock, amountAndCurrency, savedMethod, onTokenIsChargeable ); }); afterEach(() => { jest.clearAllMocks(); }); it('should fetch payment token', async () => { const result = await savedPaymentProcessor.fetchPaymentToken(); expect(result).toEqual({ Amount: 1000, Currency: 'USD', Payment: { Details: { Token: 'token123' }, Type: 'token' }, chargeable: true, type: 'card', }); }); it('should throw error when verifyPaymentToken is called before fetchPaymentToken', async () => { await expect(savedPaymentProcessor.verifyPaymentToken()).rejects.toThrowError( 'Payment token was not fetched. Please call fetchPaymentToken() first.' ); }); it('should return ChargeablePaymentToken when amount is 0', async () => { savedPaymentProcessor.amountAndCurrency = { Amount: 0, Currency: 'USD', }; await savedPaymentProcessor.fetchPaymentToken(); const result = await savedPaymentProcessor.verifyPaymentToken(); expect(result).toEqual( expect.objectContaining({ type: PAYMENT_METHOD_TYPES.CARD, chargeable: true, ...savedPaymentProcessor.amountAndCurrency, }) ); expect(onTokenIsChargeable).toHaveBeenCalledWith(result); }); it('should return ChargeablePaymentToken when fetchedPaymentToken is chargeable', async () => { await savedPaymentProcessor.fetchPaymentToken(); const result = await savedPaymentProcessor.verifyPaymentToken(); expect(result).toEqual( expect.objectContaining({ type: PAYMENT_METHOD_TYPES.CARD, chargeable: true, ...savedPaymentProcessor.amountAndCurrency, Payment: { Details: { Token: 'token123', }, Type: 'token', }, }) ); expect(onTokenIsChargeable).toHaveBeenCalledWith(result); }); it('should call verifyPayment when fetchedPaymentToken is not chargeable', async () => { addTokensResponse({ ...MOCK_TOKEN_RESPONSE, Status: PAYMENT_TOKEN_STATUS.STATUS_PENDING, ApprovalURL: 'https://verify.proton.me', ReturnHost: 'https://proton.me', } as any); const returnToken: TokenPaymentMethod = { Payment: { Type: PAYMENT_METHOD_TYPES.TOKEN, Details: { Token: 'token123', }, }, }; mockVerifyPayment.mockResolvedValue(returnToken); await savedPaymentProcessor.fetchPaymentToken(); const result = await savedPaymentProcessor.verifyPaymentToken(); expect(mockVerifyPayment).toHaveBeenCalledWith({ ApprovalURL: 'https://verify.proton.me', ReturnHost: 'https://proton.me', Token: 'token123', }); expect(result).toEqual( expect.objectContaining({ type: PAYMENT_METHOD_TYPES.CARD, chargeable: true, ...savedPaymentProcessor.amountAndCurrency, Payment: { Details: { Token: 'token123', }, Type: 'token', }, }) ); expect(onTokenIsChargeable).toHaveBeenCalledWith(result); }); it('should throw when verifyPaymentToken throws', async () => { addTokensResponse({ ...MOCK_TOKEN_RESPONSE, Status: PAYMENT_TOKEN_STATUS.STATUS_PENDING, ApprovalURL: 'https://verify.proton.me', ReturnHost: 'https://proton.me', } as any); mockVerifyPayment.mockRejectedValue(new Error('error')); await savedPaymentProcessor.fetchPaymentToken(); await expect(savedPaymentProcessor.verifyPaymentToken()).rejects.toThrowError('error'); }); it('should reset payment token', async () => { await savedPaymentProcessor.fetchPaymentToken(); expect(savedPaymentProcessor.fetchedPaymentToken).toBeTruthy(); savedPaymentProcessor.reset(); expect(savedPaymentProcessor.fetchedPaymentToken).toEqual(null); }); });
7,213
0
petrpan-code/ProtonMail/WebClients/packages/components/payments
petrpan-code/ProtonMail/WebClients/packages/components/payments/react-extensions/useCard.test.ts
import { renderHook } from '@testing-library/react-hooks'; import { addTokensResponse, apiMock } from '@proton/testing'; import { InvalidCardDataError, PAYMENT_TOKEN_STATUS } from '../core'; import { Props, useCard } from './useCard'; const mockVerifyPayment = jest.fn(); const onChargeableMock = jest.fn(); beforeEach(() => { jest.clearAllMocks(); addTokensResponse(); }); it('should render', () => { const { result } = renderHook(() => useCard( { amountAndCurrency: { Amount: 100, Currency: 'USD' }, onChargeable: onChargeableMock }, { api: apiMock, verifyPayment: mockVerifyPayment } ) ); expect(result.current).toBeDefined(); expect(result.current.meta.type).toEqual('card'); }); it('should return empty card by default', () => { const { result } = renderHook(() => useCard( { amountAndCurrency: { Amount: 100, Currency: 'USD' }, onChargeable: onChargeableMock }, { api: apiMock, verifyPayment: mockVerifyPayment } ) ); expect(result.current.card).toEqual({ number: '', month: '', year: '', cvc: '', zip: '', country: 'US', }); expect(result.current.submitted).toEqual(false); expect(result.current.errors).toEqual({}); }); it('should have false loading statuses by default', () => { const { result } = renderHook(() => useCard( { amountAndCurrency: { Amount: 100, Currency: 'USD' }, onChargeable: onChargeableMock }, { api: apiMock, verifyPayment: mockVerifyPayment } ) ); expect(result.current.fetchingToken).toEqual(false); expect(result.current.verifyingToken).toEqual(false); expect(result.current.processingToken).toEqual(false); }); it('should update amount and currency', () => { const { result, rerender } = renderHook( (props: Props) => useCard(props, { api: apiMock, verifyPayment: mockVerifyPayment }), { initialProps: { amountAndCurrency: { Amount: 100, Currency: 'USD' }, onChargeable: onChargeableMock }, } ); expect(result.current.paymentProcessor.amountAndCurrency).toEqual({ Amount: 100, Currency: 'USD' }); rerender({ amountAndCurrency: { Amount: 200, Currency: 'EUR' }, onChargeable: onChargeableMock }); expect(result.current.paymentProcessor.amountAndCurrency).toEqual({ Amount: 200, Currency: 'EUR' }); }); it('should not update the processor between renders', () => { const { result, rerender } = renderHook( (props: Props) => useCard(props, { api: apiMock, verifyPayment: mockVerifyPayment }), { initialProps: { amountAndCurrency: { Amount: 100, Currency: 'USD' }, onChargeable: onChargeableMock }, } ); const processor = result.current.paymentProcessor; rerender({ amountAndCurrency: { Amount: 200, Currency: 'EUR' }, onChargeable: onChargeableMock }); expect(result.current.paymentProcessor).toEqual(processor); }); it('should destroy the processor on unmount', () => { const { result, unmount } = renderHook( (props: Props) => useCard(props, { api: apiMock, verifyPayment: mockVerifyPayment }), { initialProps: { amountAndCurrency: { Amount: 100, Currency: 'USD' }, onChargeable: onChargeableMock }, } ); const processor = result.current.paymentProcessor; processor.destroy = jest.fn(); unmount(); expect(processor.destroy).toHaveBeenCalled(); }); it('should throw an error if there are no card details and user wants to fetch token', async () => { const { result } = renderHook( (props: Props) => useCard(props, { api: apiMock, verifyPayment: mockVerifyPayment }), { initialProps: { amountAndCurrency: { Amount: 100, Currency: 'USD' }, onChargeable: onChargeableMock }, } ); await expect(result.current.fetchPaymentToken()).rejects.toThrowError(InvalidCardDataError); }); it('should fetch payment token when the card is provided initially', async () => { const { result } = renderHook( (props: Props) => useCard(props, { api: apiMock, verifyPayment: mockVerifyPayment }), { initialProps: { amountAndCurrency: { Amount: 100, Currency: 'USD' }, onChargeable: onChargeableMock, initialCard: { number: '4242424242424242', month: '12', year: '2032', cvc: '123', zip: '12345', country: 'US', }, }, } ); expect(result.current.fetchingToken).toEqual(false); expect(result.current.verifyingToken).toEqual(false); expect(result.current.processingToken).toEqual(false); const tokenPromise = result.current.fetchPaymentToken(); expect(result.current.fetchingToken).toEqual(true); expect(result.current.verifyingToken).toEqual(false); expect(result.current.processingToken).toEqual(true); const token = await tokenPromise; expect(result.current.fetchingToken).toEqual(false); expect(result.current.verifyingToken).toEqual(false); expect(result.current.processingToken).toEqual(false); expect(token).toEqual({ Amount: 100, Currency: 'USD', Payment: { Type: 'token', Details: { Token: 'token123', }, }, chargeable: true, type: 'card', }); }); it('should fetch payment token when the card is provided later', async () => { const { result } = renderHook( (props: Props) => useCard(props, { api: apiMock, verifyPayment: mockVerifyPayment }), { initialProps: { amountAndCurrency: { Amount: 100, Currency: 'USD' }, onChargeable: onChargeableMock, }, } ); expect(result.current.fetchingToken).toEqual(false); result.current.setCardProperty('number', '4242424242424242'); result.current.setCardProperty('month', '12'); result.current.setCardProperty('year', '2032'); result.current.setCardProperty('cvc', '123'); result.current.setCardProperty('zip', '12345'); result.current.setCardProperty('country', 'US'); expect(result.current.fetchingToken).toEqual(false); const tokenPromise = result.current.fetchPaymentToken(); expect(result.current.fetchingToken).toEqual(true); const token = await tokenPromise; expect(result.current.fetchingToken).toEqual(false); expect(token).toEqual({ Amount: 100, Currency: 'USD', Payment: { Type: 'token', Details: { Token: 'token123', }, }, chargeable: true, type: 'card', }); }); it('should reset payment token when currency or amount is changed', async () => { const { result, rerender } = renderHook( (props: Props) => useCard(props, { api: apiMock, verifyPayment: mockVerifyPayment }), { initialProps: { amountAndCurrency: { Amount: 100, Currency: 'USD' }, onChargeable: onChargeableMock, }, } ); result.current.setCardProperty('number', '4242424242424242'); result.current.setCardProperty('month', '12'); result.current.setCardProperty('year', '2032'); result.current.setCardProperty('cvc', '123'); result.current.setCardProperty('zip', '12345'); result.current.setCardProperty('country', 'US'); await result.current.fetchPaymentToken(); expect(result.current.paymentProcessor.fetchedPaymentToken).toEqual({ Amount: 100, Currency: 'USD', Payment: { Type: 'token', Details: { Token: 'token123', }, }, chargeable: true, type: 'card', }); rerender({ amountAndCurrency: { Amount: 200, Currency: 'EUR' }, onChargeable: onChargeableMock, }); expect(result.current.paymentProcessor.fetchedPaymentToken).toEqual(null); }); it('should verify the payment token', async () => { addTokensResponse().pending(); mockVerifyPayment.mockResolvedValue({ Payment: { Type: 'token', Details: { Token: 'token123', }, }, }); const { result } = renderHook( (props: Props) => useCard(props, { api: apiMock, verifyPayment: mockVerifyPayment }), { initialProps: { amountAndCurrency: { Amount: 100, Currency: 'USD' }, onChargeable: onChargeableMock, }, } ); result.current.setCardProperty('number', '4242424242424242'); result.current.setCardProperty('month', '12'); result.current.setCardProperty('year', '2032'); result.current.setCardProperty('cvc', '123'); result.current.setCardProperty('zip', '12345'); result.current.setCardProperty('country', 'US'); await result.current.fetchPaymentToken(); expect(result.current.paymentProcessor.fetchedPaymentToken).toEqual({ Amount: 100, Currency: 'USD', Payment: { Type: 'token', Details: { Token: 'token123', }, }, chargeable: false, type: 'card', status: PAYMENT_TOKEN_STATUS.STATUS_PENDING, approvalURL: 'https://verify.proton.me', returnHost: 'https://account.proton.me', }); const verifyPromise = result.current.verifyPaymentToken(); expect(result.current.fetchingToken).toEqual(false); expect(result.current.verifyingToken).toEqual(true); expect(result.current.processingToken).toEqual(true); const verifiedToken = await verifyPromise; expect(verifiedToken).toEqual({ Payment: { Type: 'token', Details: { Token: 'token123', }, }, Amount: 100, Currency: 'USD', chargeable: true, type: 'card', }); }); it('should throw an error during token processing if verification failed', async () => { addTokensResponse().pending(); mockVerifyPayment.mockRejectedValue(new Error('Verification failed')); const { result } = renderHook( (props: Props) => useCard(props, { api: apiMock, verifyPayment: mockVerifyPayment }), { initialProps: { amountAndCurrency: { Amount: 100, Currency: 'USD' }, onChargeable: onChargeableMock, }, } ); result.current.setCardProperty('number', '4242424242424242'); result.current.setCardProperty('month', '12'); result.current.setCardProperty('year', '2032'); result.current.setCardProperty('cvc', '123'); result.current.setCardProperty('zip', '12345'); result.current.setCardProperty('country', 'US'); await result.current.fetchPaymentToken(); expect(result.current.paymentProcessor.fetchedPaymentToken).toEqual({ Amount: 100, Currency: 'USD', Payment: { Type: 'token', Details: { Token: 'token123', }, }, chargeable: false, type: 'card', status: PAYMENT_TOKEN_STATUS.STATUS_PENDING, approvalURL: 'https://verify.proton.me', returnHost: 'https://account.proton.me', }); const processPromise = result.current.processPaymentToken(); expect(result.current.fetchingToken).toEqual(false); expect(result.current.verifyingToken).toEqual(true); expect(result.current.processingToken).toEqual(true); await expect(processPromise).rejects.toThrow('Verification failed'); expect(result.current.fetchingToken).toEqual(false); expect(result.current.verifyingToken).toEqual(false); expect(result.current.processingToken).toEqual(false); expect(result.current.paymentProcessor.fetchedPaymentToken).toEqual(null); });
7,215
0
petrpan-code/ProtonMail/WebClients/packages/components/payments
petrpan-code/ProtonMail/WebClients/packages/components/payments/react-extensions/useMethods.test.ts
import { renderHook } from '@testing-library/react-hooks'; import { queryPaymentMethodStatus, queryPaymentMethods } from '@proton/shared/lib/api/payments'; import { wait } from '@proton/shared/lib/helpers/promise'; import { addApiMock, apiMock } from '@proton/testing'; import { Autopay, PAYMENT_METHOD_TYPES, PaymentMethodStatus, SavedPaymentMethod } from '../core'; import { useMethods } from './useMethods'; let paymentMethodStatus: PaymentMethodStatus; let paymentMethods: SavedPaymentMethod[] = [ { ID: '1', Type: PAYMENT_METHOD_TYPES.CARD, Order: 500, Autopay: Autopay.ENABLE, Details: { Name: 'Arthur Morgan', ExpMonth: '12', ExpYear: '2030', ZIP: '12345', Country: 'US', Last4: '1234', Brand: 'Visa', }, }, ]; beforeEach(() => { jest.clearAllMocks(); paymentMethodStatus = { Card: true, Paypal: true, Apple: true, Cash: true, Bitcoin: true, }; addApiMock(queryPaymentMethods().url, () => ({ PaymentMethods: paymentMethods, })); addApiMock(queryPaymentMethodStatus().url, () => paymentMethodStatus); }); it('should render', () => { const { result } = renderHook(() => useMethods( { paymentMethodStatus, amount: 100, flow: 'credit', }, { api: apiMock, isAuthenticated: true, } ) ); expect(result.current).toBeDefined(); }); it('should initialize payment methods', async () => { const { result, waitForNextUpdate } = renderHook(() => useMethods( { paymentMethodStatus, amount: 1000, flow: 'credit', }, { api: apiMock, isAuthenticated: true, } ) ); expect(result.current.loading).toBe(true); await waitForNextUpdate(); expect(result.current.loading).toBe(false); expect(result.current.savedMethods).toEqual(paymentMethods); expect(result.current.selectedMethod).toEqual({ isExpired: false, isSaved: true, paymentMethodId: '1', type: PAYMENT_METHOD_TYPES.CARD, value: '1', }); expect(result.current.savedSelectedMethod).toEqual({ ID: '1', Type: PAYMENT_METHOD_TYPES.CARD, Order: 500, Autopay: Autopay.ENABLE, Details: { Name: 'Arthur Morgan', ExpMonth: '12', ExpYear: '2030', ZIP: '12345', Country: 'US', Last4: '1234', Brand: 'Visa', }, }); expect(result.current.status).toEqual(paymentMethodStatus); expect(result.current.isNewPaypal).toBe(false); expect(result.current.usedMethods).toEqual([ { isExpired: false, isSaved: true, paymentMethodId: '1', type: PAYMENT_METHOD_TYPES.CARD, value: '1', }, ]); expect(result.current.newMethods).toEqual([ { isSaved: false, type: PAYMENT_METHOD_TYPES.CARD, value: PAYMENT_METHOD_TYPES.CARD, }, { isSaved: false, type: PAYMENT_METHOD_TYPES.PAYPAL, value: PAYMENT_METHOD_TYPES.PAYPAL, }, { isSaved: false, type: PAYMENT_METHOD_TYPES.BITCOIN, value: PAYMENT_METHOD_TYPES.BITCOIN, }, { isSaved: false, type: PAYMENT_METHOD_TYPES.CASH, value: PAYMENT_METHOD_TYPES.CASH, }, ]); expect(result.current.lastUsedMethod).toEqual({ isExpired: false, isSaved: true, paymentMethodId: '1', type: PAYMENT_METHOD_TYPES.CARD, value: '1', }); }); it('should update methods when amount changes', async () => { const { result, waitForNextUpdate, rerender } = renderHook( ({ amount }) => useMethods( { paymentMethodStatus, amount, flow: 'credit', }, { api: apiMock, isAuthenticated: true, } ), { initialProps: { amount: 1000, }, } ); await waitForNextUpdate(); expect(result.current.loading).toBe(false); expect(result.current.savedMethods).toEqual(paymentMethods); rerender({ amount: 100, }); expect(result.current.newMethods).toEqual([ { isSaved: false, type: PAYMENT_METHOD_TYPES.CARD, value: PAYMENT_METHOD_TYPES.CARD, }, { isSaved: false, type: PAYMENT_METHOD_TYPES.CASH, value: PAYMENT_METHOD_TYPES.CASH, }, ]); }); it('should get saved method by its ID', async () => { const { result, waitForNextUpdate } = renderHook(() => useMethods( { paymentMethodStatus, amount: 1000, flow: 'credit', }, { api: apiMock, isAuthenticated: true, } ) ); await waitForNextUpdate(); expect(result.current.getSavedMethodByID('1')).toEqual({ ID: '1', Type: PAYMENT_METHOD_TYPES.CARD, Order: 500, Autopay: Autopay.ENABLE, Details: { Name: 'Arthur Morgan', ExpMonth: '12', ExpYear: '2030', ZIP: '12345', Country: 'US', Last4: '1234', Brand: 'Visa', }, }); }); it('should set selected method', async () => { const { result, waitForNextUpdate } = renderHook(() => useMethods( { paymentMethodStatus, amount: 1000, flow: 'credit', }, { api: apiMock, isAuthenticated: true, } ) ); await waitForNextUpdate(); expect(result.current.selectedMethod).toEqual({ isExpired: false, isSaved: true, paymentMethodId: '1', type: PAYMENT_METHOD_TYPES.CARD, value: '1', }); result.current.selectMethod('card'); expect(result.current.selectedMethod).toEqual({ isSaved: false, type: PAYMENT_METHOD_TYPES.CARD, value: PAYMENT_METHOD_TYPES.CARD, }); expect(result.current.savedSelectedMethod).toEqual(undefined); expect(result.current.isNewPaypal).toBe(false); result.current.selectMethod('paypal'); expect(result.current.selectedMethod).toEqual({ isSaved: false, type: PAYMENT_METHOD_TYPES.PAYPAL, value: PAYMENT_METHOD_TYPES.PAYPAL, }); expect(result.current.savedSelectedMethod).toEqual(undefined); expect(result.current.isNewPaypal).toBe(true); }); it('should update amount correctly even if the initialization is slow', async () => { addApiMock(queryPaymentMethodStatus().url, async () => { await wait(100); return paymentMethodStatus; }); const { result, waitForNextUpdate, rerender } = renderHook( ({ amount }) => useMethods( { paymentMethodStatus, amount, flow: 'credit', }, { api: apiMock, isAuthenticated: true, } ), { initialProps: { amount: 0, }, } ); expect(result.current.loading).toBe(true); rerender({ amount: 10000, }); await waitForNextUpdate(); expect(result.current.loading).toBe(false); expect(result.current.newMethods.length).toBe(4); expect(result.current.newMethods).toEqual([ { isSaved: false, type: PAYMENT_METHOD_TYPES.CARD, value: PAYMENT_METHOD_TYPES.CARD, }, { isSaved: false, type: PAYMENT_METHOD_TYPES.PAYPAL, value: PAYMENT_METHOD_TYPES.PAYPAL, }, { isSaved: false, type: PAYMENT_METHOD_TYPES.BITCOIN, value: PAYMENT_METHOD_TYPES.BITCOIN, }, { isSaved: false, type: PAYMENT_METHOD_TYPES.CASH, value: PAYMENT_METHOD_TYPES.CASH, }, ]); });
7,219
0
petrpan-code/ProtonMail/WebClients/packages/components/payments
petrpan-code/ProtonMail/WebClients/packages/components/payments/react-extensions/usePaypal.test.ts
import { renderHook } from '@testing-library/react-hooks'; import { MAX_CREDIT_AMOUNT, MIN_PAYPAL_AMOUNT } from '@proton/shared/lib/constants'; import { addTokensResponse, apiMock } from '@proton/testing'; import { PAYMENT_METHOD_TYPES } from '../core'; import { usePaypal } from './usePaypal'; const onChargeableMock = jest.fn(); const verifyPaymentMock = jest.fn(); beforeEach(() => { jest.clearAllMocks(); }); it('should render', () => { const { result } = renderHook(() => usePaypal( { amountAndCurrency: { Amount: 1000, Currency: 'USD', }, isCredit: false, onChargeable: onChargeableMock, }, { api: apiMock, verifyPayment: verifyPaymentMock, } ) ); expect(result.current).toBeDefined(); expect(result.current.meta.type).toBe('paypal'); expect(result.current.fetchingToken).toBe(false); expect(result.current.verifyingToken).toBe(false); expect(result.current.verificationError).toBe(null); expect(result.current.tokenFetched).toBe(false); expect(result.current.processingToken).toBe(false); expect(result.current.paymentProcessor).toBeDefined(); }); it('should render with credit', () => { const { result } = renderHook(() => usePaypal( { amountAndCurrency: { Amount: 1000, Currency: 'USD', }, isCredit: true, onChargeable: onChargeableMock, }, { api: apiMock, verifyPayment: verifyPaymentMock, } ) ); expect(result.current).toBeDefined(); expect(result.current.meta.type).toBe('paypal-credit'); expect(result.current.fetchingToken).toBe(false); expect(result.current.verifyingToken).toBe(false); expect(result.current.verificationError).toBe(null); expect(result.current.tokenFetched).toBe(false); expect(result.current.processingToken).toBe(false); expect(result.current.paymentProcessor).toBeDefined(); }); it('should destroy payment processor on unmount', () => { const { result, unmount } = renderHook(() => usePaypal( { amountAndCurrency: { Amount: 1000, Currency: 'USD', }, isCredit: false, onChargeable: onChargeableMock, }, { api: apiMock, verifyPayment: verifyPaymentMock, } ) ); result.current.paymentProcessor!.destroy = jest.fn(); unmount(); expect(result.current.paymentProcessor!.destroy).toHaveBeenCalledTimes(1); }); it('should update fetchedPaymentToken', () => { const { result } = renderHook(() => usePaypal( { amountAndCurrency: { Amount: 1000, Currency: 'USD', }, isCredit: false, onChargeable: onChargeableMock, }, { api: apiMock, verifyPayment: verifyPaymentMock, } ) ); expect(result.current.tokenFetched).toBe(false); result.current.paymentProcessor!.updateState({ fetchedPaymentToken: 'token' }); expect(result.current.tokenFetched).toBe(true); }); it('should update verificationError', () => { const { result } = renderHook(() => usePaypal( { amountAndCurrency: { Amount: 1000, Currency: 'USD', }, isCredit: false, onChargeable: onChargeableMock, }, { api: apiMock, verifyPayment: verifyPaymentMock, } ) ); expect(result.current.verificationError).toBe(null); result.current.paymentProcessor!.updateState({ verificationError: 'error' }); expect(result.current.verificationError).toBe('error'); }); it('should update verificationError when token fetching fails', async () => { addTokensResponse().throw(); const { result } = renderHook(() => usePaypal( { amountAndCurrency: { Amount: 1000, Currency: 'USD', }, isCredit: false, onChargeable: onChargeableMock, }, { api: apiMock, verifyPayment: verifyPaymentMock, } ) ); expect(result.current.verificationError).toBe(null); const tokenPromise = result.current.fetchPaymentToken(); await expect(tokenPromise).rejects.toThrowError(new Error()); expect(result.current.verificationError).toEqual(new Error()); }); it('should update verificationError when token verification fails', async () => { addTokensResponse().pending(); verifyPaymentMock.mockRejectedValueOnce(new Error('From the endpoint')); const { result } = renderHook(() => usePaypal( { amountAndCurrency: { Amount: 1000, Currency: 'USD', }, isCredit: false, onChargeable: onChargeableMock, }, { api: apiMock, verifyPayment: verifyPaymentMock, } ) ); expect(result.current.verificationError).toBe(null); await result.current.fetchPaymentToken(); const tokenPromise = result.current.verifyPaymentToken(); await expect(tokenPromise).rejects.toThrowError(new Error('From the endpoint')); expect(result.current.verificationError).toEqual(new Error('Paypal payment verification failed')); }); it('should remove pre-fetched token if verification fails', async () => { addTokensResponse().pending(); verifyPaymentMock.mockRejectedValueOnce(new Error('From the endpoint')); const { result } = renderHook(() => usePaypal( { amountAndCurrency: { Amount: 1000, Currency: 'USD', }, isCredit: false, onChargeable: onChargeableMock, }, { api: apiMock, verifyPayment: verifyPaymentMock, } ) ); await result.current.fetchPaymentToken(); expect(result.current.tokenFetched).toBe(true); const tokenPromise = result.current.processPaymentToken(); await expect(tokenPromise).rejects.toThrowError(new Error('From the endpoint')); expect(result.current.tokenFetched).toBe(false); }); it('should process payment token', async () => { addTokensResponse().pending(); const { result } = renderHook(() => usePaypal( { amountAndCurrency: { Amount: 1000, Currency: 'USD', }, isCredit: false, onChargeable: onChargeableMock, }, { api: apiMock, verifyPayment: verifyPaymentMock, } ) ); const tokenPromise = result.current.processPaymentToken(); expect(result.current.processingToken).toBe(true); const token = await tokenPromise; expect(token).toEqual({ Amount: 1000, Currency: 'USD', chargeable: true, type: PAYMENT_METHOD_TYPES.PAYPAL, }); expect(result.current.tokenFetched).toBe(true); expect(result.current.verifyingToken).toBe(false); expect(result.current.verificationError).toBe(null); expect(result.current.processingToken).toBe(false); }); it('should update desabled state when the amount changes', () => { const { result, rerender } = renderHook( ({ Amount }) => usePaypal( { amountAndCurrency: { Amount, Currency: 'USD', }, isCredit: false, onChargeable: onChargeableMock, }, { api: apiMock, verifyPayment: verifyPaymentMock, } ), { initialProps: { Amount: 0, }, } ); expect(result.current.disabled).toBe(false); rerender({ Amount: MIN_PAYPAL_AMOUNT - 1, }); expect(result.current.disabled).toBe(true); rerender({ Amount: MIN_PAYPAL_AMOUNT, }); expect(result.current.disabled).toBe(false); rerender({ Amount: (MIN_PAYPAL_AMOUNT + MAX_CREDIT_AMOUNT) / 2, }); expect(result.current.disabled).toBe(false); rerender({ Amount: MAX_CREDIT_AMOUNT, }); expect(result.current.disabled).toBe(false); rerender({ Amount: MAX_CREDIT_AMOUNT + 1, }); expect(result.current.disabled).toBe(true); rerender({ Amount: 0, }); expect(result.current.disabled).toBe(false); }); it('should have isInitialState === true when tokenFetched === false and verificationError === null', () => { const { result } = renderHook( ({ Amount }) => usePaypal( { amountAndCurrency: { Amount, Currency: 'USD', }, isCredit: false, onChargeable: onChargeableMock, }, { api: apiMock, verifyPayment: verifyPaymentMock, } ), { initialProps: { Amount: 0, }, } ); expect(result.current.isInitialState).toBe(true); result.current.paymentProcessor!.updateState({ fetchedPaymentToken: 'token' }); expect(result.current.isInitialState).toBe(false); result.current.paymentProcessor!.updateState({ fetchedPaymentToken: null }); expect(result.current.isInitialState).toBe(true); result.current.paymentProcessor!.updateState({ verificationError: 'error' }); expect(result.current.isInitialState).toBe(false); result.current.paymentProcessor!.updateState({ verificationError: null }); expect(result.current.isInitialState).toBe(true); result.current.paymentProcessor!.updateState({ fetchedPaymentToken: 'token', verificationError: 'error' }); expect(result.current.isInitialState).toBe(false); result.current.reset(); expect(result.current.isInitialState).toBe(false); // because reset() must NOT clear verificationError. result.current.paymentProcessor!.updateState({ verificationError: null }); expect(result.current.isInitialState).toBe(true); });
7,221
0
petrpan-code/ProtonMail/WebClients/packages/components/payments
petrpan-code/ProtonMail/WebClients/packages/components/payments/react-extensions/useSavedMethod.test.ts
import { renderHook } from '@testing-library/react-hooks'; import { addTokensResponse, apiMock } from '@proton/testing'; import { Autopay, PAYMENT_METHOD_TYPES, PaymentMethodPaypal, SavedPaymentMethod } from '../core'; import { useSavedMethod } from './useSavedMethod'; const onChargeableMock = jest.fn(); const verifyPaymentMock = jest.fn(); beforeEach(() => { jest.clearAllMocks(); }); const savedMethod: SavedPaymentMethod = { Order: 500, ID: '1', Type: PAYMENT_METHOD_TYPES.CARD, Details: { Name: 'John Doe', ExpMonth: '12', ExpYear: '2032', ZIP: '12345', Country: 'US', Last4: '1234', Brand: 'Visa', }, Autopay: Autopay.ENABLE, }; it('should render', async () => { const { result } = renderHook(() => useSavedMethod( { amountAndCurrency: { Amount: 1000, Currency: 'USD', }, savedMethod, onChargeable: onChargeableMock, }, { api: apiMock, verifyPayment: verifyPaymentMock, } ) ); expect(result.current).toBeDefined(); expect(result.current.meta.type).toBe('saved'); expect(result.current.fetchingToken).toBe(false); expect(result.current.verifyingToken).toBe(false); expect(result.current.processingToken).toBe(false); expect(result.current.paymentProcessor).toBeDefined(); }); it('should render without savedMethod', async () => { const { result } = renderHook(() => useSavedMethod( { amountAndCurrency: { Amount: 1000, Currency: 'USD', }, onChargeable: onChargeableMock, }, { api: apiMock, verifyPayment: verifyPaymentMock, } ) ); expect(result.current).toBeDefined(); expect(result.current.meta.type).toBe('saved'); expect(result.current.fetchingToken).toBe(false); expect(result.current.verifyingToken).toBe(false); expect(result.current.processingToken).toBe(false); expect(result.current.paymentProcessor).toBeUndefined(); }); it('should destroy paymentProcessor', async () => { const { result, unmount } = renderHook(() => useSavedMethod( { amountAndCurrency: { Amount: 1000, Currency: 'USD', }, savedMethod, onChargeable: onChargeableMock, }, { api: apiMock, verifyPayment: verifyPaymentMock, } ) ); expect(result.current).toBeDefined(); expect(result.current.meta.type).toBe('saved'); expect(result.current.fetchingToken).toBe(false); expect(result.current.verifyingToken).toBe(false); expect(result.current.processingToken).toBe(false); expect(result.current.paymentProcessor).toBeDefined(); result.current.paymentProcessor!.destroy = jest.fn(); unmount(); expect(result.current.paymentProcessor!.destroy).toBeCalled(); }); it('should fetch token', async () => { addTokensResponse(); const { result } = renderHook(() => useSavedMethod( { amountAndCurrency: { Amount: 1000, Currency: 'USD', }, savedMethod, onChargeable: onChargeableMock, }, { api: apiMock, verifyPayment: verifyPaymentMock, } ) ); const tokenPromise = result.current.fetchPaymentToken(); expect(result.current.fetchingToken).toBe(true); const token = await tokenPromise; expect(token).toEqual({ Amount: 1000, Currency: 'USD', Payment: { Type: 'token', Details: { Token: 'token123', }, }, chargeable: true, type: 'card', }); }); it('should process token', async () => { addTokensResponse().pending(); verifyPaymentMock.mockResolvedValue({ Payment: { Type: 'token', Details: { Token: 'token123', }, }, }); const { result } = renderHook(() => useSavedMethod( { amountAndCurrency: { Amount: 1000, Currency: 'USD', }, savedMethod, onChargeable: onChargeableMock, }, { api: apiMock, verifyPayment: verifyPaymentMock, } ) ); await result.current.fetchPaymentToken(); expect(result.current.fetchingToken).toBe(false); const processPromise = result.current.processPaymentToken(); expect(result.current.processingToken).toBe(true); const token = await processPromise; expect(result.current.processingToken).toBe(false); expect(token).toEqual({ Amount: 1000, Currency: 'USD', Payment: { Type: 'token', Details: { Token: 'token123', }, }, chargeable: true, type: 'card', }); }); it('should throw during verification if there is no saved method', async () => { const { result } = renderHook(() => useSavedMethod( { amountAndCurrency: { Amount: 1000, Currency: 'USD', }, onChargeable: onChargeableMock, }, { api: apiMock, verifyPayment: verifyPaymentMock, } ) ); await expect(() => result.current.verifyPaymentToken()).rejects.toThrowError('There is no saved method to verify'); }); it('should reset token if verification failed', async () => { addTokensResponse().pending(); verifyPaymentMock.mockRejectedValue(new Error('Verification failed')); const { result } = renderHook(() => useSavedMethod( { amountAndCurrency: { Amount: 1000, Currency: 'USD', }, savedMethod, onChargeable: onChargeableMock, }, { api: apiMock, verifyPayment: verifyPaymentMock, } ) ); await expect(result.current.processPaymentToken()).rejects.toThrowError('Verification failed'); expect(result.current.verifyingToken).toBe(false); expect(result.current.paymentProcessor?.fetchedPaymentToken).toEqual(null); }); it('should update the saved method', async () => { const { result, rerender } = renderHook( ({ savedMethod }) => useSavedMethod( { amountAndCurrency: { Amount: 1000, Currency: 'USD', }, savedMethod, onChargeable: onChargeableMock, }, { api: apiMock, verifyPayment: verifyPaymentMock, } ), { initialProps: { savedMethod: savedMethod as SavedPaymentMethod, }, } ); expect((result.current.paymentProcessor as any).state.method.paymentMethodId).toEqual(savedMethod.ID); expect((result.current.paymentProcessor as any).state.method.type).toEqual(savedMethod.Type); const newSavedMethod: PaymentMethodPaypal = { Order: 400, ID: '2', Type: PAYMENT_METHOD_TYPES.PAYPAL, Details: { BillingAgreementID: 'BA-123', PayerID: 'pid123', Payer: 'payer123', }, }; rerender({ savedMethod: newSavedMethod, }); expect((result.current.paymentProcessor as any).state.method.paymentMethodId).toEqual(newSavedMethod.ID); expect((result.current.paymentProcessor as any).state.method.type).toEqual(newSavedMethod.Type); });
7,316
0
petrpan-code/ProtonMail/WebClients/packages
petrpan-code/ProtonMail/WebClients/packages/hooks/useCombinedRefs.test.ts
import { createElement, useEffect, useRef } from 'react'; import { render } from '@testing-library/react'; import useCombinedRefs from './useCombinedRefs'; describe('useCombinedRefs', () => { it('should correctly combine refs into one ref', async () => { const cbRef = jest.fn(); const refs: { a: null | HTMLDivElement; b: null | HTMLDivElement } = { a: null, b: null }; const Test = () => { const refA = useRef<HTMLDivElement>(null); const refB = useRef<HTMLDivElement>(null); const combinedRef = useCombinedRefs(refA, refB, cbRef, undefined); useEffect(() => { refs.a = refA.current; refs.b = refB.current; return () => { refs.a = refA.current; refs.b = refB.current; }; }); return createElement('div', { ref: combinedRef, 'data-testid': 'div' }); }; const { getByTestId, rerender } = render(createElement(Test)); const div = getByTestId('div'); expect(refs.a).toBe(div); expect(refs.b).toBe(div); expect(cbRef).toHaveBeenCalledWith(div); rerender(createElement('div')); expect(cbRef).toHaveBeenCalledWith(null); expect(refs.a).toBe(null); expect(refs.b).toBe(null); }); });
7,318
0
petrpan-code/ProtonMail/WebClients/packages
petrpan-code/ProtonMail/WebClients/packages/hooks/useControlled.test.ts
import { act, renderHook } from '@testing-library/react-hooks'; import useControlled from './useControlled'; describe('useControlled()', () => { it('initializes with its passed value', () => { const initial = 0; const hook = renderHook(() => useControlled(initial)); const [state] = hook.result.current; expect(state).toBe(initial); }); it('ignores setState if a value from the outside is passed into it', () => { const initial = 0; const hook = renderHook(() => useControlled(initial)); act(() => { const [, setState] = hook.result.current; setState(1); }); const [state] = hook.result.current; expect(state).toBe(initial); }); it('behaves like useState if no value is passed to it', () => { const initial = undefined as undefined | number; const hook = renderHook(() => useControlled(initial, 0)); const [stateOne] = hook.result.current; expect(stateOne).toBe(0); act(() => { const [, setState] = hook.result.current; setState(1); }); const [stateTwo] = hook.result.current; expect(stateTwo).toBe(1); }); it('propagates values passed from the outside when they update', () => { const hook = renderHook(({ initial }) => useControlled(initial), { initialProps: { initial: 0 } }); hook.rerender({ initial: 1 }); const [state] = hook.result.current; expect(state).toBe(1); }); it('switches from uncontrolled to controlled if initially no value is passed but later is', () => { const hook = renderHook(({ initial }) => useControlled(initial), { initialProps: { initial: undefined as undefined | number }, }); act(() => { const [, setState] = hook.result.current; setState(1); }); hook.rerender({ initial: 2 }); const [stateTwo] = hook.result.current; expect(stateTwo).toBe(2); act(() => { const [, setState] = hook.result.current; setState(3); }); const [stateThree] = hook.result.current; expect(stateThree).toBe(2); }); });
7,320
0
petrpan-code/ProtonMail/WebClients/packages
petrpan-code/ProtonMail/WebClients/packages/hooks/useDateCountdown.test.ts
import { act, renderHook } from '@testing-library/react-hooks'; import { DAY, HOUR, MINUTE, SECOND } from '@proton/shared/lib/constants'; import useDateCountdown from './useDateCountdown'; describe('useDateCountdown', () => { beforeAll(() => { jest.useFakeTimers(); }); afterEach(() => { jest.clearAllTimers(); }); afterAll(() => { jest.useRealTimers(); }); describe('interval', () => { it('should default interval to update every second', () => { const diff = 123456789; const expiry = new Date(Date.now() + diff); const { result } = renderHook(() => useDateCountdown(expiry)); const initialExpectedValue = { days: 1, diff, expired: false, hours: 10, minutes: 17, seconds: 36, }; expect(result.current).toStrictEqual(initialExpectedValue); // fast-forward time until 1 millisecond before it should be updated act(() => { jest.advanceTimersByTime(SECOND - 1); }); expect(result.current).toStrictEqual(initialExpectedValue); // fast-forward until 1st update should be act(() => { jest.advanceTimersByTime(1); }); expect(result.current).toStrictEqual({ ...initialExpectedValue, diff: diff - SECOND, seconds: 35 }); }); it('should allow configuration of interval', () => { const diff = 123456789; const interval = 500; const expiry = new Date(Date.now() + diff); const { result } = renderHook(() => useDateCountdown(expiry, { interval })); const initialExpectedValue = { days: 1, diff, expired: false, hours: 10, minutes: 17, seconds: 36, }; expect(result.current).toStrictEqual(initialExpectedValue); // fast-forward time until 1 millisecond before it should be updated act(() => { jest.advanceTimersByTime(interval - 1); }); expect(result.current).toStrictEqual(initialExpectedValue); // fast-forward until 1st update should be act(() => { jest.advanceTimersByTime(1); }); expect(result.current).toStrictEqual({ ...initialExpectedValue, diff: diff - interval }); }); }); describe('expired', () => { it('should be false when date is in the future', () => { const expiry = new Date(Date.now() + 1000); const { result } = renderHook(() => useDateCountdown(expiry)); const value = result.current; expect(value.expired).toBeFalsy(); }); it('should be false when date now', () => { const expiry = new Date(Date.now()); const { result } = renderHook(() => useDateCountdown(expiry)); const value = result.current; expect(value.expired).toBeFalsy(); }); it('should be true when date is in the past', () => { const expiry = new Date(Date.now() - 1000); const { result } = renderHook(() => useDateCountdown(expiry)); const value = result.current; expect(value.expired).toBeTruthy(); }); it('should return negative diff', () => { const expiry = new Date(Date.now()); const { result } = renderHook(() => useDateCountdown(expiry)); const advanceBy = 1 * DAY + 2 * HOUR + 3 * MINUTE + 4 * SECOND; act(() => { jest.advanceTimersByTime(advanceBy); }); expect(result.current).toStrictEqual({ diff: -advanceBy, expired: true, days: 1, hours: 2, minutes: 3, seconds: 4, }); }); }); it('should correctly countdown', () => { let diff = 2 * DAY + 12 * HOUR + 3 * MINUTE + 32 * SECOND; const expiry = new Date(Date.now() + diff); const { result } = renderHook(() => useDateCountdown(expiry)); expect(result.current).toStrictEqual({ diff, expired: false, days: 2, hours: 12, minutes: 3, seconds: 32, }); // fast-forward time 1 Day act(() => { jest.advanceTimersByTime(DAY); }); diff -= DAY; expect(result.current).toStrictEqual({ diff, expired: false, days: 1, hours: 12, minutes: 3, seconds: 32, }); // fast-forward time 1 Hour act(() => { jest.advanceTimersByTime(HOUR); }); diff -= HOUR; expect(result.current).toStrictEqual({ diff, expired: false, days: 1, hours: 11, minutes: 3, seconds: 32, }); // fast-forward time 1 Minute act(() => { jest.advanceTimersByTime(MINUTE); }); diff -= MINUTE; expect(result.current).toStrictEqual({ diff, expired: false, days: 1, hours: 11, minutes: 2, seconds: 32, }); // fast-forward time 1 Second act(() => { jest.advanceTimersByTime(SECOND); }); diff -= SECOND; expect(result.current).toStrictEqual({ diff, expired: false, days: 1, hours: 11, minutes: 2, seconds: 31, }); // fast-forward rest act(() => { jest.advanceTimersByTime(1 * DAY + 11 * HOUR + 2 * MINUTE + 31 * SECOND); }); expect(result.current).toStrictEqual({ diff: 0, expired: false, days: 0, hours: 0, minutes: 0, seconds: 0, }); // fast-forward to past expiry act(() => { jest.advanceTimersByTime(1 * DAY + 2 * HOUR + 3 * MINUTE + 4 * SECOND); }); expect(result.current).toStrictEqual({ diff: -93784000, expired: true, days: 1, hours: 2, minutes: 3, seconds: 4, }); }); });
7,322
0
petrpan-code/ProtonMail/WebClients/packages
petrpan-code/ProtonMail/WebClients/packages/hooks/useInstance.test.ts
import { act, renderHook } from '@testing-library/react-hooks'; import useInstance from './useInstance'; describe('useInstance()', () => { it('initiates with the value returned from its callback argument', () => { const hook = renderHook(() => useInstance(() => 'initial')); expect(hook.result.current).toBe('initial'); }); it('keeps referential equality of the initial value between render cycles', () => { const initial = {}; const hook = renderHook(() => useInstance(() => initial)); act(() => {}); expect(hook.result.current).toBe(initial); }); it('only executes the passed callback once', () => { const callback = jest.fn(() => 'initial'); renderHook(() => useInstance(callback)); act(() => {}); expect(callback).toHaveBeenCalledTimes(1); }); });
7,324
0
petrpan-code/ProtonMail/WebClients/packages
petrpan-code/ProtonMail/WebClients/packages/hooks/useInterval.test.ts
import { renderHook } from '@testing-library/react-hooks'; import useInterval from './useInterval'; describe('useInterval', () => { let callback: jest.Mock<any, any>; let setInterval: jest.SpyInstance<any, any>; let clearInterval: jest.SpyInstance<any, any>; beforeEach(() => { callback = jest.fn(); setInterval = jest.spyOn(window, 'setInterval'); clearInterval = jest.spyOn(window, 'clearInterval'); }); beforeAll(() => { jest.useFakeTimers(); }); afterEach(() => { callback.mockRestore(); jest.clearAllTimers(); }); afterAll(() => { jest.useRealTimers(); }); it('should init hook with no delay', () => { const { result } = renderHook(() => useInterval(callback, null)); const value = result.current; expect(value).toBeUndefined(); // if null delay provided, it's assumed as no delay expect(setInterval).not.toHaveBeenCalled(); }); it('should set pass delay to setInterval', () => { const delay = 5000; const { result } = renderHook(() => useInterval(callback, delay)); const value = result.current; expect(value).toBeUndefined(); expect(setInterval).toHaveBeenCalledTimes(1); expect(setInterval).toHaveBeenCalledWith(expect.any(Function), delay); }); it('should repeatedly calls provided callback with a fixed time delay between each call', () => { renderHook(() => useInterval(callback, 200)); expect(callback).not.toHaveBeenCalled(); // fast-forward time until 1 millisecond before it should be executed jest.advanceTimersByTime(199); expect(callback).not.toHaveBeenCalled(); // fast-forward until 1st call should be executed jest.advanceTimersByTime(1); expect(callback).toHaveBeenCalledTimes(1); // fast-forward until next timer should be executed jest.advanceTimersToNextTimer(); expect(callback).toHaveBeenCalledTimes(2); // fast-forward until 3 more timers should be executed jest.advanceTimersToNextTimer(3); expect(callback).toHaveBeenCalledTimes(5); }); it('should clear interval on unmount', () => { const { unmount } = renderHook(() => useInterval(callback, 200)); const initialTimerCount = jest.getTimerCount(); expect(clearInterval).not.toHaveBeenCalled(); unmount(); expect(clearInterval).toHaveBeenCalledTimes(1); expect(jest.getTimerCount()).toBe(initialTimerCount - 1); }); it('should handle new interval when delay is updated', () => { let delay = 200; const { rerender } = renderHook(() => useInterval(callback, delay)); expect(callback).not.toHaveBeenCalled(); // fast-forward initial delay jest.advanceTimersByTime(200); expect(callback).toHaveBeenCalledTimes(1); // update delay by increasing previous one delay = 500; rerender(); // fast-forward initial delay again but this time it should not execute the cb jest.advanceTimersByTime(200); expect(callback).toHaveBeenCalledTimes(1); // fast-forward remaining time for new delay jest.advanceTimersByTime(300); expect(callback).toHaveBeenCalledTimes(2); }); it('should clear pending interval when delay is updated', () => { let delay = 200; const { rerender } = renderHook(() => useInterval(callback, delay)); expect(clearInterval).not.toHaveBeenCalled(); const initialTimerCount = jest.getTimerCount(); // update delay while there is a pending interval delay = 500; rerender(); expect(clearInterval).toHaveBeenCalledTimes(1); expect(jest.getTimerCount()).toBe(initialTimerCount); }); });
7,326
0
petrpan-code/ProtonMail/WebClients/packages
petrpan-code/ProtonMail/WebClients/packages/hooks/useIsMounted.test.ts
import { act, renderHook } from '@testing-library/react-hooks'; import useIsMounted from './useIsMounted'; describe('useIsMounted()', () => { it('returns false initially', () => { const hook = renderHook(() => useIsMounted()); const isMounted = hook.result.current(); /** * TODO: expected this to return false if the callback * returned from renderHook is called immediately, however * this is true it seems. * * Tried removing the useCallback from inside useIsMounted, * tried removing the callback entirely and just returning * the ref directly, but it's true every time. * * This is probably an issue with @testing-library/react-hooks. * * The test below also doesn't really make sense given this * as it's true both before and after the act() call. */ // expect(isMounted).toBe(false); expect(isMounted).toBe(true); }); it('returns true after mount', () => { const hook = renderHook(() => useIsMounted()); act(() => {}); const isMounted = hook.result.current(); expect(isMounted).toBe(true); }); });
7,328
0
petrpan-code/ProtonMail/WebClients/packages
petrpan-code/ProtonMail/WebClients/packages/hooks/useLoading.test.ts
import { act, renderHook } from '@testing-library/react-hooks'; import useLoading, { useLoadingByKey } from '@proton/hooks/useLoading'; import { createPromise } from '@proton/shared/lib/helpers/promise'; describe('useLoading', () => { it('should return loading false by default', () => { const { result } = renderHook(() => useLoading()); const [loading] = result.current; expect(loading).toEqual(false); }); it('should allow setting of initial loading state', () => { const { result } = renderHook(() => useLoading(true)); const [loading] = result.current; expect(loading).toEqual(true); }); it('should resolve withLoading if there is no promise', async () => { const { result } = renderHook(() => useLoading()); const [loading, withLoading] = result.current; await act(async () => { const resolved = await withLoading(undefined); expect(resolved).toEqual(undefined); }); expect(loading).toEqual(false); }); it('should resolve promise and returns the result', async () => { const { result } = renderHook(() => useLoading()); const [, withLoading] = result.current; await act(async () => { const resolved = await withLoading(Promise.resolve('resolved result')); expect(resolved).toEqual('resolved result'); }); const [loading] = result.current; expect(loading).toEqual(false); }); it('should reject if promise rejects', async () => { const { result } = renderHook(() => useLoading()); const [, withLoading] = result.current; const error = new Error('some error'); expect.assertions(2); await act(async () => { try { await withLoading(Promise.reject(error)); } catch (e) { expect(e).toEqual(error); } }); const [loading] = result.current; expect(loading).toEqual(false); }); it('should render loading state', async () => { const { result } = renderHook(() => useLoading()); const [, withLoading] = result.current; const { promise, resolve } = createPromise<void>(); let wrappedPromise: Promise<unknown>; act(() => { wrappedPromise = withLoading(promise); }); let [loading] = result.current; expect(loading).toEqual(true); await act(async () => { resolve(); await wrappedPromise; }); [loading] = result.current; expect(loading).toEqual(false); }); it('should ignore previous promises', async () => { const { result } = renderHook(() => useLoading()); const [, withLoading] = result.current; const { promise: promise1, resolve: resolve1 } = createPromise(); const { promise: promise2, resolve: resolve2 } = createPromise(); await act(async () => { const wrappedPromise1 = withLoading(promise1); const wrappedPromise2 = withLoading(promise2); resolve1('First result'); resolve2('Second result'); expect(await wrappedPromise1).toEqual(undefined); expect(await wrappedPromise2).toEqual('Second result'); }); }); it('should ignore previous errors', async () => { const { result } = renderHook(() => useLoading()); const [, withLoading] = result.current; const { promise: promise1, reject: reject1 } = createPromise(); const { promise: promise2, reject: reject2 } = createPromise(); await act(async () => { const wrappedPromise1 = withLoading(promise1); const wrappedPromise2 = withLoading(promise2); let handledFirstReject = false; wrappedPromise1.catch(() => { handledFirstReject = true; }); let handledSecondReject = false; wrappedPromise2.catch(() => { handledSecondReject = true; }); reject1('First reject reason'); reject2('Second reject reason'); // Handle promises before doing the checks. Switching the control flow in the event loop. expect.assertions(3); await new Promise((resolve) => setTimeout(resolve)); expect(handledFirstReject).toEqual(false); expect(handledSecondReject).toEqual(true); expect(await wrappedPromise1).toEqual(undefined); }); }); it('should support functions as an argument', async () => { const { result } = renderHook(() => useLoading()); const [, withLoading] = result.current; async function run(): Promise<string> { return 'resolved result'; } await act(async () => { const resolvedResult = await withLoading(run); expect(resolvedResult).toEqual('resolved result'); }); }); it('should expose setLoading', async () => { const { result } = renderHook(() => useLoading()); const [, , setLoading] = result.current; act(() => { setLoading(true); }); const [loading] = result.current; expect(loading).toBe(true); }); }); describe('useLoadingByKey', () => { describe('when initial state is not provided', () => { it('should return empty map', () => { const { result } = renderHook(() => useLoadingByKey()); const [loading] = result.current; expect(loading).toStrictEqual({}); }); }); describe('when initial state is provided', () => { it('should return it at first', () => { const { result } = renderHook(() => useLoadingByKey({ keyA: true })); const [loading] = result.current; expect(loading).toStrictEqual({ keyA: true }); }); }); describe('when promise is undefined', () => { it('should resolve withLoading', async () => { const { result } = renderHook(() => useLoadingByKey()); const [, withLoading] = result.current; const resolved = await act(() => withLoading('keyA', undefined)); expect(resolved).toEqual(undefined); const [loading] = result.current; expect(loading).toEqual({ keyA: false }); }); }); describe('when promise is defined', () => { it('should resolve promise and returns the result', async () => { const { result } = renderHook(() => useLoadingByKey()); const [, withLoading] = result.current; await act(async () => { const resolved = await withLoading('keyA', Promise.resolve('resolved result')); expect(resolved).toEqual('resolved result'); }); const [loading] = result.current; expect(loading).toEqual({ keyA: false }); }); it('should reject if promise rejects', async () => { const { result } = renderHook(() => useLoadingByKey()); const [, withLoading] = result.current; const error = new Error('some error'); expect.assertions(2); await act(async () => { try { await withLoading('keyA', Promise.reject(error)); } catch (e) { expect(e).toEqual(error); } }); const [loading] = result.current; expect(loading).toStrictEqual({ keyA: false }); }); it('should render loading state', async () => { const { result } = renderHook(() => useLoadingByKey()); const [, withLoading] = result.current; const { promise, resolve } = createPromise<void>(); let wrappedPromise: Promise<unknown>; act(() => { wrappedPromise = withLoading('keyA', promise); }); let [loading] = result.current; expect(loading).toStrictEqual({ keyA: true }); await act(async () => { resolve(); await wrappedPromise; }); [loading] = result.current; expect(loading).toStrictEqual({ keyA: false }); }); it('should ignore previous promises', async () => { const { result } = renderHook(() => useLoadingByKey()); const [, withLoading] = result.current; const { promise: promise1, resolve: resolve1 } = createPromise(); const { promise: promise2, resolve: resolve2 } = createPromise(); await act(async () => { const wrappedPromise1 = withLoading('keyA', promise1); const wrappedPromise2 = withLoading('keyA', promise2); resolve1('First result'); resolve2('Second result'); expect(await wrappedPromise1).toEqual(undefined); expect(await wrappedPromise2).toEqual('Second result'); }); }); it('should ignore previous errors', async () => { const { result } = renderHook(() => useLoadingByKey()); const [, withLoading] = result.current; const { promise: promise1, reject: reject1 } = createPromise(); const { promise: promise2, reject: reject2 } = createPromise(); await act(async () => { const wrappedPromise1 = withLoading('keyA', promise1); const wrappedPromise2 = withLoading('keyA', promise2); let handledFirstReject = false; wrappedPromise1.catch(() => { handledFirstReject = true; }); let handledSecondReject = false; wrappedPromise2.catch(() => { handledSecondReject = true; }); reject1('First reject reason'); reject2('Second reject reason'); // Handle promises before doing the checks. Switching the control flow in the event loop. expect.assertions(3); await new Promise((resolve) => setTimeout(resolve)); expect(handledFirstReject).toEqual(false); expect(handledSecondReject).toEqual(true); expect(await wrappedPromise1).toEqual(undefined); }); }); it('should ignore previous errors', async () => { const { result } = renderHook(() => useLoadingByKey()); const [, withLoading] = result.current; const { promise: promise1, reject: reject1 } = createPromise(); const { promise: promise2, reject: reject2 } = createPromise(); await act(async () => { const wrappedPromise1 = withLoading('keyA', promise1); const wrappedPromise2 = withLoading('keyA', promise2); let handledFirstReject = false; wrappedPromise1.catch(() => { handledFirstReject = true; }); let handledSecondReject = false; wrappedPromise2.catch(() => { handledSecondReject = true; }); reject1('First reject reason'); reject2('Second reject reason'); // Handle promises before doing the checks. Switching the control flow in the event loop. expect.assertions(3); await new Promise((resolve) => setTimeout(resolve)); expect(handledFirstReject).toEqual(false); expect(handledSecondReject).toEqual(true); expect(await wrappedPromise1).toEqual(undefined); }); }); it('should support functions as an argument', async () => { const { result } = renderHook(() => useLoadingByKey()); const [, withLoading] = result.current; async function run(): Promise<string> { return 'resolved result'; } await act(async () => { const resolvedResult = await withLoading('keyA', run); expect(resolvedResult).toEqual('resolved result'); }); }); it('should expose setLoading', async () => { const { result } = renderHook(() => useLoadingByKey()); const [, , setLoading] = result.current; act(() => { setLoading('keyA', true); }); const [loading] = result.current; expect(loading).toStrictEqual({ keyA: true }); }); }); describe('when several keys are used', () => { it('should not conflict between each other', async () => { const { result } = renderHook(() => useLoadingByKey()); const [, withLoading] = result.current; const { promise: promise1, resolve: resolve1 } = createPromise(); const { promise: promise2, resolve: resolve2 } = createPromise(); let wrappedPromise1: Promise<unknown>; let wrappedPromise2: Promise<unknown>; await act(async () => { wrappedPromise1 = withLoading('keyA', promise1); }); let [loading] = result.current; expect(loading).toStrictEqual({ keyA: true }); await act(async () => { wrappedPromise2 = withLoading('keyB', promise2); }); [loading] = result.current; expect(loading).toStrictEqual({ keyA: true, keyB: true }); await act(async () => { resolve2('Second result'); expect(await wrappedPromise2).toEqual('Second result'); }); [loading] = result.current; expect(loading).toStrictEqual({ keyA: true, keyB: false }); await act(async () => { resolve1('First result'); expect(await wrappedPromise1).toEqual('First result'); }); [loading] = result.current; expect(loading).toStrictEqual({ keyA: false, keyB: false }); }); }); });
7,330
0
petrpan-code/ProtonMail/WebClients/packages
petrpan-code/ProtonMail/WebClients/packages/hooks/usePrevious.test.ts
import { renderHook } from '@testing-library/react-hooks'; import usePrevious from './usePrevious'; describe('usePrevious()', () => { it('remembers the value passed to it in the previous render cycle', () => { const hook = renderHook(({ initial }) => usePrevious(initial), { initialProps: { initial: 0 } }); hook.rerender({ initial: 1 }); const previous = hook.result.current; expect(previous).toBe(0); }); });
7,332
0
petrpan-code/ProtonMail/WebClients/packages
petrpan-code/ProtonMail/WebClients/packages/hooks/useSynchronizingState.test.ts
import { act, renderHook } from '@testing-library/react-hooks'; import useSynchronizingState from './useSynchronizingState'; describe('useSynchronizingState()', () => { it('initiates with the value passed to it', () => { const hook = renderHook(() => useSynchronizingState('initial')); const [value] = hook.result.current; expect(value).toBe('initial'); }); it('sets the state just as useState would', () => { const initial = 0; const hook = renderHook(() => useSynchronizingState(initial)); act(() => { const [, setState] = hook.result.current; setState(1); }); const [value] = hook.result.current; expect(value).toBe(1); }); it('synchronizes with the value passed to it on updates', () => { const hook = renderHook(({ initial }) => useSynchronizingState(initial), { initialProps: { initial: 0 } }); hook.rerender({ initial: 1 }); const [value] = hook.result.current; expect(value).toBe(1); }); });
7,431
0
petrpan-code/ProtonMail/WebClients/packages/metrics
petrpan-code/ProtonMail/WebClients/packages/metrics/tests/Counter.test.ts
import Counter from '../lib/Counter'; import MetricsApi from '../lib/MetricsApi'; import MetricsRequestService from '../lib/MetricsRequestService'; import MetricSchema from '../lib/types/MetricSchema'; jest.mock('../lib/MetricsApi'); const metricsApi = new MetricsApi(); jest.mock('../lib/MetricsRequestService'); const metricsRequestService = new MetricsRequestService(metricsApi, { reportMetrics: true }); interface DefaultMetricSchema extends MetricSchema { Labels: { foo: 'bar'; }; } const time = new Date('2020-01-01'); describe('Counter', () => { beforeAll(() => { jest.useFakeTimers(); }); beforeEach(() => { jest.clearAllTimers(); jest.setSystemTime(time); }); afterAll(() => { jest.useRealTimers(); }); it('construct correct metric report', () => { const name = 'name'; const version = 1; const counter = new Counter<DefaultMetricSchema>({ name, version }, metricsRequestService); counter.increment({ foo: 'bar' }); expect(metricsRequestService.report).toHaveBeenCalledWith({ Name: name, Version: version, Timestamp: time.getTime() / 1000, Data: { Value: 1, Labels: { foo: 'bar' }, }, }); }); });
7,432
0
petrpan-code/ProtonMail/WebClients/packages/metrics
petrpan-code/ProtonMail/WebClients/packages/metrics/tests/Histogram.test.ts
import Histogram from '../lib/Histogram'; import MetricsApi from '../lib/MetricsApi'; import MetricsRequestService from '../lib/MetricsRequestService'; import MetricSchema from '../lib/types/MetricSchema'; jest.mock('../lib/MetricsApi'); const metricsApi = new MetricsApi(); jest.mock('../lib/MetricsRequestService'); const metricsRequestService = new MetricsRequestService(metricsApi, { reportMetrics: true }); interface DefaultMetricSchema extends MetricSchema { Labels: { foo: 'bar'; }; } const time = new Date('2020-01-01'); describe('Histogram', () => { beforeAll(() => { jest.useFakeTimers(); }); beforeEach(() => { jest.clearAllTimers(); jest.setSystemTime(time); }); afterAll(() => { jest.useRealTimers(); }); it('construct correct metric report', () => { const name = 'name'; const version = 1; const counter = new Histogram<DefaultMetricSchema>({ name, version }, metricsRequestService); const value = 123.456; counter.observe({ Value: value, Labels: { foo: 'bar' } }); expect(metricsRequestService.report).toHaveBeenCalledWith({ Name: name, Version: version, Timestamp: time.getTime() / 1000, Data: { Value: value, Labels: { foo: 'bar' }, }, }); }); });
7,433
0
petrpan-code/ProtonMail/WebClients/packages/metrics
petrpan-code/ProtonMail/WebClients/packages/metrics/tests/Metric.test.ts
import Metric from '../lib/Metric'; import MetricsApi from '../lib/MetricsApi'; import MetricsRequestService from '../lib/MetricsRequestService'; import MetricSchema from '../lib/types/MetricSchema'; jest.mock('../lib/MetricsApi'); const metricsApi = new MetricsApi(); jest.mock('../lib/MetricsRequestService'); const metricsRequestService = new MetricsRequestService(metricsApi, { reportMetrics: true }); class MetricInstance<D extends MetricSchema> extends Metric<D> {} interface DefaultMetricSchema extends MetricSchema { Labels: { foo: 'bar'; }; } describe('Metric', () => { it('does not throw when creating a metric with a valid name', () => { const validNames = ['name', 'hello_there', 'aAAa_2bB']; const version = 1; for (let i = 0; i < validNames.length; i++) { const name = validNames[i]; expect(() => { new MetricInstance<DefaultMetricSchema>({ name, version }, metricsRequestService); }).not.toThrow(); } }); it('throws when creating a metric with an invalid name', () => { const invalidNames = [ 'ends_with_an_underscore_', '123_starts_with_a_number', 'contains_special_characters!@£$%^&*()', ]; const version = 1; for (let i = 0; i < invalidNames.length; i++) { const name = invalidNames[i]; expect(() => { new MetricInstance<DefaultMetricSchema>({ name, version }, metricsRequestService); }).toThrow(); } }); });
7,434
0
petrpan-code/ProtonMail/WebClients/packages/metrics
petrpan-code/ProtonMail/WebClients/packages/metrics/tests/MetricsApi.test.ts
import { HTTP_STATUS_CODE, SECOND } from '@proton/shared/lib/constants'; import { wait } from '@proton/shared/lib/helpers/promise'; import { METRICS_DEFAULT_RETRY_SECONDS, METRICS_MAX_ATTEMPTS, METRICS_REQUEST_TIMEOUT_SECONDS } from '../constants'; import MetricsApi from '../lib/MetricsApi'; jest.mock('@proton/shared/lib/helpers/promise'); function getHeader(headers: HeadersInit | undefined, headerName: string) { // @ts-ignore return headers[headerName]; } describe('MetricsApi', () => { beforeEach(() => { fetchMock.resetMocks(); }); describe('constructor', () => { describe('auth headers', () => { it('sets auth headers when uid is defined', async () => { const uid = 'uid'; const metricsApi = new MetricsApi({ uid }); await metricsApi.fetch('/route'); const content = fetchMock.mock.lastCall?.[1]; expect(fetchMock).toHaveBeenCalledTimes(1); expect(getHeader(content?.headers, 'x-pm-uid')).toBe(uid); }); it('does not set auth headers when uid is not defined', async () => { const metricsApi = new MetricsApi(); await metricsApi.fetch('/route'); const content = fetchMock.mock.lastCall?.[1]; expect(fetchMock).toHaveBeenCalledTimes(1); expect(getHeader(content?.headers, 'x-pm-uid')).toBe(undefined); }); }); describe('app version headers', () => { it('sets app version headers when clientID and appVersion are defined', async () => { const clientID = 'clientID'; const appVersion = 'appVersion'; const metricsApi = new MetricsApi({ clientID, appVersion }); await metricsApi.fetch('/route'); const content = fetchMock.mock.lastCall?.[1]; expect(fetchMock).toHaveBeenCalledTimes(1); expect(getHeader(content?.headers, 'x-pm-appversion')).toBe(`${clientID}@${appVersion}-dev`); }); it('does not set app version headers when clientID is not defined', async () => { const appVersion = 'appVersion'; const metricsApi = new MetricsApi({ appVersion }); await metricsApi.fetch('/route'); const content = fetchMock.mock.lastCall?.[1]; expect(fetchMock).toHaveBeenCalledTimes(1); expect(getHeader(content?.headers, 'x-pm-appversion')).toBe(undefined); }); it('does not set app version headers when appVersion is not defined', async () => { const clientID = 'clientID'; const metricsApi = new MetricsApi({ clientID }); await metricsApi.fetch('/route'); const content = fetchMock.mock.lastCall?.[1]; expect(fetchMock).toHaveBeenCalledTimes(1); expect(getHeader(content?.headers, 'x-pm-appversion')).toBe(undefined); }); }); }); describe('setAuthHeaders', () => { it('sets auth headers when uid is defined', async () => { const uid = 'uid'; const metricsApi = new MetricsApi(); metricsApi.setAuthHeaders(uid); await metricsApi.fetch('/route'); const content = fetchMock.mock.lastCall?.[1]; expect(fetchMock).toHaveBeenCalledTimes(1); expect(getHeader(content?.headers, 'x-pm-uid')).toBe(uid); }); it('does not set auth headers when uid is an empty string', async () => { const uid = ''; const metricsApi = new MetricsApi(); metricsApi.setAuthHeaders(uid); await metricsApi.fetch('/route'); const content = fetchMock.mock.lastCall?.[1]; expect(fetchMock).toHaveBeenCalledTimes(1); expect(getHeader(content?.headers, 'x-pm-uid')).toBe(undefined); }); }); describe('setAuthHeaders', () => { it('sets app version headers when clientID and appVersion are defined', async () => { const clientID = 'clientID'; const appVersion = 'appVersion'; const metricsApi = new MetricsApi(); metricsApi.setVersionHeaders(clientID, appVersion); await metricsApi.fetch('/route'); const content = fetchMock.mock.lastCall?.[1]; expect(fetchMock).toHaveBeenCalledTimes(1); expect(getHeader(content?.headers, 'x-pm-appversion')).toBe(`${clientID}@${appVersion}-dev`); }); it('does not set app version headers when clientID is an empty string', async () => { const clientID = ''; const appVersion = 'appVersion'; const metricsApi = new MetricsApi(); metricsApi.setVersionHeaders(clientID, appVersion); await metricsApi.fetch('/route'); const content = fetchMock.mock.lastCall?.[1]; expect(fetchMock).toHaveBeenCalledTimes(1); expect(getHeader(content?.headers, 'x-pm-appversion')).toBe(undefined); }); it('does not set app version headers when appVersion is an empty string', async () => { const clientID = 'clientID'; const appVersion = ''; const metricsApi = new MetricsApi(); metricsApi.setVersionHeaders(clientID, appVersion); await metricsApi.fetch('/route'); const content = fetchMock.mock.lastCall?.[1]; expect(fetchMock).toHaveBeenCalledTimes(1); expect(getHeader(content?.headers, 'x-pm-appversion')).toBe(undefined); }); }); describe('fetch', () => { it('throws if fetch rejects', async () => { fetchMock.mockResponseOnce(() => Promise.reject(new Error('asd'))); const metricsApi = new MetricsApi(); await expect(async () => { await metricsApi.fetch('/route'); }).rejects.toThrow(); }); it('sets content-type header to application/json', async () => { const metricsApi = new MetricsApi(); await metricsApi.fetch('/route'); const content = fetchMock.mock.lastCall?.[1]; expect(fetchMock).toHaveBeenCalledTimes(1); expect(getHeader(content?.headers, 'content-type')).toBe('application/json'); }); it('sets priority header to u=6', async () => { const metricsApi = new MetricsApi(); await metricsApi.fetch('/route'); const content = fetchMock.mock.lastCall?.[1]; expect(fetchMock).toHaveBeenCalledTimes(1); expect(getHeader(content?.headers, 'priority')).toBe('u=6'); }); it('forwards request info', async () => { const route = '/route'; const metricsApi = new MetricsApi(); await metricsApi.fetch(route); const url = fetchMock.mock.lastCall?.[0]; expect(fetchMock).toHaveBeenCalledTimes(1); expect(url).toBe(route); }); it('forwards request init params', async () => { const method = 'post'; const body = 'body'; const metricsApi = new MetricsApi(); await metricsApi.fetch('/route', { method, body, headers: { foo: 'bar', }, }); const content = fetchMock.mock.lastCall?.[1]; expect(fetchMock).toHaveBeenCalledTimes(1); expect(content?.method).toBe(method); expect(content?.body).toBe(body); expect(getHeader(content?.headers, 'foo')).toBe('bar'); }); describe('retry', () => { const getRetryImplementation = (url: string, retrySeconds?: string) => async (req: Request) => { if (req.url === url) { return retrySeconds === undefined ? { status: HTTP_STATUS_CODE.TOO_MANY_REQUESTS } : { status: HTTP_STATUS_CODE.TOO_MANY_REQUESTS, headers: { 'retry-after': retrySeconds, }, }; } return ''; }; it('retries request if response contains retry-after header', async () => { fetchMock.mockResponseOnce(getRetryImplementation('/retry', '1')); const metricsApi = new MetricsApi(); await metricsApi.fetch('/retry'); expect(fetchMock).toHaveBeenCalledTimes(2); }); it('respects the time the retry header contains', async () => { fetchMock.mockResponseOnce(getRetryImplementation('/retry', '1')); fetchMock.mockResponseOnce(getRetryImplementation('/retry', '2')); fetchMock.mockResponseOnce(getRetryImplementation('/retry', '3')); const metricsApi = new MetricsApi(); await metricsApi.fetch('/retry'); expect(wait).toHaveBeenNthCalledWith(1, 1 * SECOND); expect(wait).toHaveBeenNthCalledWith(2, 2 * SECOND); expect(wait).toHaveBeenNthCalledWith(3, 3 * SECOND); }); it(`retires a maximum of ${METRICS_MAX_ATTEMPTS} times`, async () => { fetchMock.mockResponse(getRetryImplementation('/retry', '1')); const metricsApi = new MetricsApi(); await metricsApi.fetch('/retry'); expect(fetchMock).toHaveBeenCalledTimes(METRICS_MAX_ATTEMPTS); }); it(`uses default retry of ${METRICS_DEFAULT_RETRY_SECONDS} if retry is 0`, async () => { fetchMock.mockResponseOnce(getRetryImplementation('/retry', '0')); const metricsApi = new MetricsApi(); await metricsApi.fetch('/retry'); expect(wait).toHaveBeenCalledWith(METRICS_DEFAULT_RETRY_SECONDS * SECOND); }); it(`uses default retry of ${METRICS_DEFAULT_RETRY_SECONDS} if retry is NaN`, async () => { fetchMock.mockResponseOnce(getRetryImplementation('/retry', 'hello')); const metricsApi = new MetricsApi(); await metricsApi.fetch('/retry'); expect(wait).toHaveBeenCalledWith(METRICS_DEFAULT_RETRY_SECONDS * SECOND); }); it(`uses default retry of ${METRICS_DEFAULT_RETRY_SECONDS} if retry is negative`, async () => { fetchMock.mockResponseOnce(getRetryImplementation('/retry', '-1')); const metricsApi = new MetricsApi(); await metricsApi.fetch('/retry'); expect(wait).toHaveBeenCalledWith(METRICS_DEFAULT_RETRY_SECONDS * SECOND); }); it(`uses default retry of ${METRICS_DEFAULT_RETRY_SECONDS} if retry is not defined`, async () => { fetchMock.mockResponseOnce(getRetryImplementation('/retry')); const metricsApi = new MetricsApi(); await metricsApi.fetch('/retry'); expect(wait).toHaveBeenCalledWith(METRICS_DEFAULT_RETRY_SECONDS * SECOND); }); it('floors non integer values', async () => { fetchMock.mockResponseOnce(getRetryImplementation('/retry', '2.5')); const metricsApi = new MetricsApi(); await metricsApi.fetch('/retry'); expect(wait).toHaveBeenCalledWith(2 * SECOND); }); }); describe('timeout', () => { beforeAll(() => { jest.useFakeTimers(); }); beforeEach(() => { jest.clearAllTimers(); }); afterAll(() => { jest.useRealTimers(); }); const timeoutRequestMock = () => new Promise<{ body: string }>((resolve) => { setTimeout(() => resolve({ body: 'ok' }), METRICS_REQUEST_TIMEOUT_SECONDS * SECOND + 1); jest.advanceTimersByTime(METRICS_REQUEST_TIMEOUT_SECONDS * SECOND + 1); }); it('retries request if request aborts', async () => { fetchMock.mockAbort(); const metricsApi = new MetricsApi(); await metricsApi.fetch('/route'); expect(fetchMock).toHaveBeenCalledTimes(METRICS_MAX_ATTEMPTS); await expect(fetchMock).rejects.toThrow('The operation was aborted.'); }); it(`retries request if response takes longer than ${METRICS_REQUEST_TIMEOUT_SECONDS} seconds`, async () => { fetchMock.mockResponseOnce(timeoutRequestMock); const metricsApi = new MetricsApi(); await metricsApi.fetch('/route'); expect(fetchMock).toHaveBeenCalledTimes(2); }); it(`waits ${METRICS_DEFAULT_RETRY_SECONDS} seconds before retrying`, async () => { fetchMock.mockResponseOnce(timeoutRequestMock); const metricsApi = new MetricsApi(); await metricsApi.fetch('/route'); expect(wait).toHaveBeenNthCalledWith(1, METRICS_DEFAULT_RETRY_SECONDS * SECOND); }); it(`retires a maximum of ${METRICS_MAX_ATTEMPTS} times`, async () => { fetchMock.mockResponse(timeoutRequestMock); const metricsApi = new MetricsApi(); await metricsApi.fetch('/route'); expect(fetchMock).toHaveBeenCalledTimes(METRICS_MAX_ATTEMPTS); }); }); }); });
7,435
0
petrpan-code/ProtonMail/WebClients/packages/metrics
petrpan-code/ProtonMail/WebClients/packages/metrics/tests/MetricsBase.test.ts
import MetricsApi from '../lib/MetricsApi'; import MetricsBase from '../lib/MetricsBase'; import MetricsRequestService from '../lib/MetricsRequestService'; jest.mock('../lib/MetricsApi'); const metricsApi = new MetricsApi(); jest.mock('../lib/MetricsRequestService', () => { return jest.fn().mockImplementation(() => { return { api: metricsApi, setReportMetrics: jest.fn(), processAllRequests: jest.fn(), stopBatchingProcess: jest.fn(), startBatchingProcess: jest.fn(), }; }); }); const metricsRequestService = new MetricsRequestService(metricsApi, { reportMetrics: true }); describe('MetricsBase', () => { describe('init', () => { it('sets auth headers', () => { const uid = 'uid'; const clientID = 'clientID'; const appVersion = 'appVersion'; const metrics = new MetricsBase(metricsRequestService); metrics.init({ uid, clientID, appVersion }); expect(metricsRequestService.api.setAuthHeaders).toHaveBeenCalledWith(uid); }); it('sets version headers', () => { const uid = 'uid'; const clientID = 'clientID'; const appVersion = 'appVersion'; const metrics = new MetricsBase(metricsRequestService); metrics.init({ uid, clientID, appVersion }); expect(metricsRequestService.api.setVersionHeaders).toHaveBeenCalledWith(clientID, appVersion); }); }); describe('setVersionHeaders', () => { it('sets version headers', () => { const clientID = 'clientID'; const appVersion = 'appVersion'; const metrics = new MetricsBase(metricsRequestService); metrics.setVersionHeaders(clientID, appVersion); expect(metricsRequestService.api.setVersionHeaders).toHaveBeenCalledWith(clientID, appVersion); }); }); describe('setAuthHeaders', () => { it('sets auth headers', () => { const uid = 'uid'; const metrics = new MetricsBase(metricsRequestService); metrics.setAuthHeaders(uid); expect(metricsRequestService.api.setAuthHeaders).toHaveBeenCalledWith(uid); }); }); describe('clearAuthHeaders', () => { it(`sets auth headers with uid ''`, () => { const metrics = new MetricsBase(metricsRequestService); metrics.clearAuthHeaders(); expect(metricsRequestService.api.setAuthHeaders).toHaveBeenCalledWith(''); }); }); describe('setReportMetrics', () => { it('sets report metrics to false', () => { const metrics = new MetricsBase(metricsRequestService); metrics.setReportMetrics(false); expect(metricsRequestService.setReportMetrics).toHaveBeenCalledWith(false); }); it('sets report metrics to true', () => { const metrics = new MetricsBase(metricsRequestService); metrics.setReportMetrics(true); expect(metricsRequestService.setReportMetrics).toHaveBeenCalledWith(true); }); }); describe('processAllRequests', () => { it('calls processAllRequests', async () => { const metrics = new MetricsBase(metricsRequestService); await metrics.processAllRequests(); expect(metricsRequestService.processAllRequests).toHaveBeenCalledTimes(1); }); }); describe('stopBatchingProcess', () => { it('calls stopBatchingProcess', async () => { const metrics = new MetricsBase(metricsRequestService); await metrics.stopBatchingProcess(); expect(metricsRequestService.stopBatchingProcess).toHaveBeenCalledTimes(1); }); }); describe('startBatchingProcess', () => { it('calls startBatchingProcess', async () => { const metrics = new MetricsBase(metricsRequestService); await metrics.startBatchingProcess(); expect(metricsRequestService.startBatchingProcess).toHaveBeenCalledTimes(1); }); }); });
7,436
0
petrpan-code/ProtonMail/WebClients/packages/metrics
petrpan-code/ProtonMail/WebClients/packages/metrics/tests/MetricsRequestService.test.ts
import MetricsApi from '../lib/MetricsApi'; import MetricsRequestService from '../lib/MetricsRequestService'; import MetricsRequest from '../lib/types/MetricsRequest'; jest.mock('../lib/MetricsApi'); const metricsApi = new MetricsApi(); const getMetricsRequest = (name: string): MetricsRequest => ({ Name: name, Version: 1, Timestamp: 1, Data: {}, }); const defaultMetricsRequest = getMetricsRequest('Name'); describe('MetricsRequestService', () => { beforeAll(() => { jest.useFakeTimers(); }); beforeEach(() => { jest.clearAllTimers(); }); afterAll(() => { jest.useRealTimers(); }); it('makes construct correct request', () => { const requestService = new MetricsRequestService(metricsApi, { reportMetrics: true }); requestService.report(defaultMetricsRequest); expect(metricsApi.fetch).toHaveBeenCalledTimes(1); expect(metricsApi.fetch).toHaveBeenCalledWith('api/data/v1/metrics', { method: 'post', body: JSON.stringify({ Metrics: [defaultMetricsRequest] }), }); }); describe('report metrics', () => { it('allows api calls if reportMetrics was set to true in constructor', () => { const requestService = new MetricsRequestService(metricsApi, { reportMetrics: true }); requestService.report(defaultMetricsRequest); expect(metricsApi.fetch).toHaveBeenCalledTimes(1); }); it('disallows api calls if reportMetrics was set to false in constructor', () => { const requestService = new MetricsRequestService(metricsApi, { reportMetrics: false }); requestService.report(defaultMetricsRequest); expect(metricsApi.fetch).not.toHaveBeenCalled(); }); describe('setter', () => { it('allows api calls if reportMetrics is set to true via setter', () => { const requestService = new MetricsRequestService(metricsApi, { reportMetrics: false }); requestService.setReportMetrics(true); requestService.report(defaultMetricsRequest); expect(metricsApi.fetch).toHaveBeenCalledTimes(1); }); it('disallows api calls if reportMetrics is set to false via setter', () => { const requestService = new MetricsRequestService(metricsApi, { reportMetrics: true }); requestService.setReportMetrics(false); requestService.report(defaultMetricsRequest); expect(metricsApi.fetch).not.toHaveBeenCalled(); }); }); }); describe('batching', () => { describe('batch parameters', () => { it('does not batch if frequency is 0', () => { const requestService = new MetricsRequestService(metricsApi, { reportMetrics: true, batch: { frequency: 0, size: 1, }, }); requestService.report(defaultMetricsRequest); expect(metricsApi.fetch).toHaveBeenCalledTimes(1); }); it('does not batch if frequency is negative', () => { const requestService = new MetricsRequestService(metricsApi, { reportMetrics: true, batch: { frequency: -1, size: 1, }, }); requestService.report(defaultMetricsRequest); expect(metricsApi.fetch).toHaveBeenCalledTimes(1); }); it('does not batch if size is 0', () => { const requestService = new MetricsRequestService(metricsApi, { reportMetrics: true, batch: { frequency: 1, size: 0, }, }); requestService.report(defaultMetricsRequest); expect(metricsApi.fetch).toHaveBeenCalledTimes(1); }); it('does not batch if size is negative', () => { const requestService = new MetricsRequestService(metricsApi, { reportMetrics: true, batch: { frequency: 1, size: -1, }, }); requestService.report(defaultMetricsRequest); expect(metricsApi.fetch).toHaveBeenCalledTimes(1); }); it('batches if frequency and size are positive', () => { const requestService = new MetricsRequestService(metricsApi, { reportMetrics: true, batch: { frequency: 1, size: 1, }, }); requestService.report(getMetricsRequest('Request 1')); requestService.report(getMetricsRequest('Request 2')); expect(metricsApi.fetch).not.toHaveBeenCalled(); jest.advanceTimersByTime(1); expect(metricsApi.fetch).toHaveBeenCalledWith('api/data/v1/metrics', { method: 'post', body: JSON.stringify({ Metrics: [getMetricsRequest('Request 1')] }), }); jest.advanceTimersByTime(1); expect(metricsApi.fetch).toHaveBeenCalledWith('api/data/v1/metrics', { method: 'post', body: JSON.stringify({ Metrics: [getMetricsRequest('Request 2')] }), }); }); }); it('delays api calls until frequency timeout has expired', () => { const batchFrequency = 100; const batchSize = 5; const requestService = new MetricsRequestService(metricsApi, { reportMetrics: true, batch: { frequency: batchFrequency, size: batchSize, }, }); requestService.report(defaultMetricsRequest); expect(metricsApi.fetch).not.toHaveBeenCalled(); // fast-forward time until 1 millisecond before it should be executed jest.advanceTimersByTime(batchFrequency - 1); expect(metricsApi.fetch).not.toHaveBeenCalled(); // fast-forward until 1st call should be executed jest.advanceTimersByTime(1); expect(metricsApi.fetch).toHaveBeenCalledTimes(1); }); it('does not call api if there are no items to process', () => { const batchFrequency = 100; const batchSize = 5; const requestService = new MetricsRequestService(metricsApi, { reportMetrics: true, batch: { frequency: batchFrequency, size: batchSize, }, }); requestService.startBatchingProcess(); jest.advanceTimersByTime(batchFrequency); expect(metricsApi.fetch).not.toHaveBeenCalled(); }); it('batches calls in order they were reported', () => { const batchFrequency = 100; const batchSize = 2; const requestService = new MetricsRequestService(metricsApi, { reportMetrics: true, batch: { frequency: batchFrequency, size: batchSize, }, }); requestService.report(getMetricsRequest('Request 1')); requestService.report(getMetricsRequest('Request 2')); requestService.report(getMetricsRequest('Request 3')); requestService.report(getMetricsRequest('Request 4')); expect(metricsApi.fetch).not.toHaveBeenCalled(); jest.advanceTimersByTime(batchFrequency); expect(metricsApi.fetch).toHaveBeenCalledWith('api/data/v1/metrics', { method: 'post', body: JSON.stringify({ Metrics: [getMetricsRequest('Request 1'), getMetricsRequest('Request 2')] }), }); jest.advanceTimersByTime(batchFrequency); expect(metricsApi.fetch).toHaveBeenCalledWith('api/data/v1/metrics', { method: 'post', body: JSON.stringify({ Metrics: [getMetricsRequest('Request 3'), getMetricsRequest('Request 4')] }), }); }); it('handles partial batches', () => { const batchFrequency = 100; const batchSize = 2; const requestService = new MetricsRequestService(metricsApi, { reportMetrics: true, batch: { frequency: batchFrequency, size: batchSize, }, }); requestService.report(getMetricsRequest('Request 1')); requestService.report(getMetricsRequest('Request 2')); requestService.report(getMetricsRequest('Request 3')); expect(metricsApi.fetch).not.toHaveBeenCalled(); jest.advanceTimersByTime(batchFrequency); expect(metricsApi.fetch).toHaveBeenCalledWith('api/data/v1/metrics', { method: 'post', body: JSON.stringify({ Metrics: [getMetricsRequest('Request 1'), getMetricsRequest('Request 2')] }), }); jest.advanceTimersByTime(batchFrequency); expect(metricsApi.fetch).toHaveBeenCalledWith('api/data/v1/metrics', { method: 'post', body: JSON.stringify({ Metrics: [getMetricsRequest('Request 3')] }), }); }); }); describe('startBatchingProcess', () => { it('starts batching interval on first report call if batch params are defined', () => { const requestService = new MetricsRequestService(metricsApi, { reportMetrics: true, batch: { frequency: 1, size: 1, }, }); requestService.report(defaultMetricsRequest); expect(metricsApi.fetch).not.toHaveBeenCalled(); jest.advanceTimersByTime(1); expect(metricsApi.fetch).toHaveBeenCalledTimes(1); }); it('does not set batching interval if no batch params are set', () => { const requestService = new MetricsRequestService(metricsApi, { reportMetrics: true, }); requestService.report(defaultMetricsRequest); expect(metricsApi.fetch).toHaveBeenCalledTimes(1); /** * Advance timers to when call should have been * performed if batching was enabled and ensure * no extra calls have been made */ jest.advanceTimersByTime(1); expect(metricsApi.fetch).toHaveBeenCalledTimes(1); }); }); describe('stopBatchingProcess', () => { it('stops any further batch requests from occurring until startBatchingProcess is called', () => { const requestService = new MetricsRequestService(metricsApi, { reportMetrics: true, batch: { frequency: 1, size: 1, }, }); requestService.report(defaultMetricsRequest); requestService.report(defaultMetricsRequest); expect(metricsApi.fetch).not.toHaveBeenCalled(); jest.advanceTimersByTime(1); expect(metricsApi.fetch).toHaveBeenCalledTimes(1); requestService.stopBatchingProcess(); jest.advanceTimersByTime(4); expect(metricsApi.fetch).toHaveBeenCalledTimes(1); requestService.startBatchingProcess(); jest.advanceTimersByTime(1); expect(metricsApi.fetch).toHaveBeenCalledTimes(2); }); }); describe('processAllRequests', () => { it('does not make a request if there is no queue', async () => { const batchFrequency = 10; const requestService = new MetricsRequestService(metricsApi, { reportMetrics: true, batch: { frequency: batchFrequency, size: 1, }, }); await requestService.processAllRequests(); expect(metricsApi.fetch).not.toHaveBeenCalled(); }); it('processes all requests in queue regardless of batch size', async () => { const batchFrequency = 10; const requestService = new MetricsRequestService(metricsApi, { reportMetrics: true, batch: { frequency: batchFrequency, size: 1, }, }); requestService.report(getMetricsRequest('Request 1')); requestService.report(getMetricsRequest('Request 2')); requestService.report(getMetricsRequest('Request 3')); expect(metricsApi.fetch).not.toHaveBeenCalled(); jest.advanceTimersByTime(batchFrequency); expect(metricsApi.fetch).toHaveBeenCalledWith('api/data/v1/metrics', { method: 'post', body: JSON.stringify({ Metrics: [getMetricsRequest('Request 1')] }), }); jest.advanceTimersByTime(1); await requestService.processAllRequests(); expect(metricsApi.fetch).toHaveBeenCalledTimes(2); expect(metricsApi.fetch).toHaveBeenCalledWith('api/data/v1/metrics', { method: 'post', body: JSON.stringify({ Metrics: [getMetricsRequest('Request 2'), getMetricsRequest('Request 3')] }), }); }); it('clears queue', async () => { const batchFrequency = 10; const requestService = new MetricsRequestService(metricsApi, { reportMetrics: true, batch: { frequency: batchFrequency, size: 1, }, }); requestService.report(getMetricsRequest('Request 1')); requestService.report(getMetricsRequest('Request 2')); requestService.report(getMetricsRequest('Request 3')); expect(metricsApi.fetch).not.toHaveBeenCalled(); await requestService.processAllRequests(); expect(metricsApi.fetch).toHaveBeenCalledTimes(1); jest.advanceTimersByTime(batchFrequency); expect(metricsApi.fetch).toHaveBeenCalledTimes(1); }); }); describe('clearQueue', () => { it('removes all items from queue', () => { const batchFrequency = 10; const requestService = new MetricsRequestService(metricsApi, { reportMetrics: true, batch: { frequency: batchFrequency, size: 1, }, }); requestService.report(getMetricsRequest('Request 1')); requestService.report(getMetricsRequest('Request 2')); requestService.report(getMetricsRequest('Request 3')); expect(metricsApi.fetch).not.toHaveBeenCalled(); jest.advanceTimersByTime(batchFrequency); expect(metricsApi.fetch).toHaveBeenCalledTimes(1); requestService.clearQueue(); jest.advanceTimersByTime(batchFrequency); expect(metricsApi.fetch).toHaveBeenCalledTimes(1); }); }); });
7,437
0
petrpan-code/ProtonMail/WebClients/packages/metrics
petrpan-code/ProtonMail/WebClients/packages/metrics/tests/integration.test.ts
import Counter from '../lib/Counter'; import Histogram from '../lib/Histogram'; import MetricsApi from '../lib/MetricsApi'; import MetricsBase from '../lib/MetricsBase'; import MetricsRequestService from '../lib/MetricsRequestService'; import IMetricsRequestService from '../lib/types/IMetricsRequestService'; import MetricSchema from '../lib/types/MetricSchema'; export const counterName = 'counter_name'; export const counterVersion = 1; export const histogramName = 'histogram_name'; export const histogramVersion = 1; class MetricsTest extends MetricsBase { public counter: Counter<MetricSchema>; public histogram: Histogram<MetricSchema>; constructor(requestService: IMetricsRequestService) { super(requestService); this.counter = new Counter<MetricSchema>({ name: counterName, version: counterVersion }, this.requestService); this.histogram = new Histogram<MetricSchema>( { name: histogramName, version: histogramVersion }, this.requestService ); } } const metricsApi = new MetricsApi(); const metricsRequestService = new MetricsRequestService(metricsApi, { reportMetrics: true }); const metrics = new MetricsTest(metricsRequestService); const uid = 'uid'; const clientID = 'clientID'; const appVersion = 'appVersion'; metrics.init({ uid, clientID, appVersion, }); const time = new Date('2020-01-01'); describe('metrics', () => { beforeAll(() => { jest.useFakeTimers(); }); beforeEach(() => { fetchMock.resetMocks(); jest.clearAllTimers(); jest.setSystemTime(time); }); afterAll(() => { jest.useRealTimers(); }); describe('counter requests', () => { it('uses the metrics v1 url', () => { metrics.counter.increment({ foo: 'bar', }); const url = fetchMock.mock.lastCall?.[0]; expect(fetchMock).toHaveBeenCalledTimes(1); expect(url).toBe('api/data/v1/metrics'); }); it('makes a post request', async () => { metrics.counter.increment({ foo: 'bar', }); const content = fetchMock.mock.lastCall?.[1]; expect(fetchMock).toHaveBeenCalledTimes(1); expect(content?.method).toBe('post'); }); it('contains the correct headers', async () => { metrics.counter.increment({ foo: 'bar', }); const content = fetchMock.mock.lastCall?.[1]; expect(fetchMock).toHaveBeenCalledTimes(1); expect(content?.headers).toEqual({ 'content-type': 'application/json', priority: 'u=6', 'x-pm-appversion': `${clientID}@${appVersion}-dev`, 'x-pm-uid': uid, }); }); it('sends the metric name', async () => { metrics.counter.increment({ foo: 'bar', }); const content = fetchMock.mock.lastCall?.[1]; // @ts-ignore const body = JSON.parse(content?.body); expect(fetchMock).toHaveBeenCalledTimes(1); expect(body.Metrics[0].Name).toEqual(counterName); }); it('sends the metric version', async () => { metrics.counter.increment({ foo: 'bar', }); const content = fetchMock.mock.lastCall?.[1]; // @ts-ignore const body = JSON.parse(content?.body); expect(fetchMock).toHaveBeenCalledTimes(1); expect(body.Metrics[0].Version).toEqual(counterVersion); }); it('uses the current time for the timestamp', async () => { metrics.counter.increment({ foo: 'bar', }); const content = fetchMock.mock.lastCall?.[1]; // @ts-ignore const body = JSON.parse(content?.body); expect(fetchMock).toHaveBeenCalledTimes(1); expect(body.Metrics[0].Timestamp).toEqual(time.getTime() / 1000); }); it('sends Value as 1', async () => { metrics.counter.increment({ foo: 'bar', }); const content = fetchMock.mock.lastCall?.[1]; // @ts-ignore const body = JSON.parse(content?.body); expect(fetchMock).toHaveBeenCalledTimes(1); expect(body.Metrics[0].Data.Value).toBe(1); }); it('sends labels', async () => { const labels = { foo: 'bar', bar: 'foo', }; metrics.counter.increment(labels); const content = fetchMock.mock.lastCall?.[1]; // @ts-ignore const body = JSON.parse(content?.body); expect(fetchMock).toHaveBeenCalledTimes(1); expect(body.Metrics[0].Data.Labels).toEqual(labels); }); }); describe('histogram requests', () => { it('uses the metrics v1 url', async () => { metrics.histogram.observe({ Labels: { foo: 'bar', }, Value: 1, }); const url = fetchMock.mock.lastCall?.[0]; expect(fetchMock).toHaveBeenCalledTimes(1); expect(url).toBe('api/data/v1/metrics'); }); it('makes a post request', async () => { metrics.histogram.observe({ Labels: { foo: 'bar', }, Value: 1, }); const content = fetchMock.mock.lastCall?.[1]; expect(fetchMock).toHaveBeenCalledTimes(1); expect(content?.method).toBe('post'); }); it('contains the correct headers', async () => { metrics.histogram.observe({ Labels: { foo: 'bar', }, Value: 1, }); const content = fetchMock.mock.lastCall?.[1]; expect(fetchMock).toHaveBeenCalledTimes(1); expect(content?.headers).toEqual({ 'content-type': 'application/json', priority: 'u=6', 'x-pm-appversion': `${clientID}@${appVersion}-dev`, 'x-pm-uid': uid, }); }); it('sends the metric name', async () => { metrics.histogram.observe({ Labels: { foo: 'bar', }, Value: 1, }); const content = fetchMock.mock.lastCall?.[1]; // @ts-ignore const body = JSON.parse(content?.body); expect(fetchMock).toHaveBeenCalledTimes(1); expect(body.Metrics[0].Name).toEqual(histogramName); }); it('sends the metric version', async () => { metrics.histogram.observe({ Labels: { foo: 'bar', }, Value: 1, }); const content = fetchMock.mock.lastCall?.[1]; // @ts-ignore const body = JSON.parse(content?.body); expect(fetchMock).toHaveBeenCalledTimes(1); expect(body.Metrics[0].Version).toEqual(histogramVersion); }); it('uses the current time for the timestamp', async () => { metrics.histogram.observe({ Labels: { foo: 'bar', }, Value: 1, }); const content = fetchMock.mock.lastCall?.[1]; // @ts-ignore const body = JSON.parse(content?.body); expect(fetchMock).toHaveBeenCalledTimes(1); expect(body.Metrics[0].Timestamp).toEqual(time.getTime() / 1000); }); it('sends float Values', async () => { const Value = 1.234; metrics.histogram.observe({ Labels: { foo: 'bar', }, Value, }); const content = fetchMock.mock.lastCall?.[1]; // @ts-ignore const body = JSON.parse(content?.body); expect(fetchMock).toHaveBeenCalledTimes(1); expect(body.Metrics[0].Data.Value).toBe(Value); }); it('sends Labels', async () => { const Labels = { foo: 'bar', bar: 'foo', }; metrics.histogram.observe({ Labels, Value: 1, }); const content = fetchMock.mock.lastCall?.[1]; // @ts-ignore const body = JSON.parse(content?.body); expect(fetchMock).toHaveBeenCalledTimes(1); expect(body.Metrics[0].Data.Labels).toEqual(Labels); }); }); });
7,438
0
petrpan-code/ProtonMail/WebClients/packages/metrics
petrpan-code/ProtonMail/WebClients/packages/metrics/tests/observeApiError.test.ts
import observeApiError from '../lib/observeApiError'; const metricObserver = jest.fn(); describe('observeApiError', () => { it('ignores reporting if error is undefined', () => { observeApiError(undefined, metricObserver); expect(metricObserver).toHaveBeenCalledTimes(0); }); it('ignores reporting if error is null', () => { observeApiError(null, metricObserver); expect(metricObserver).toHaveBeenCalledTimes(0); }); it('ignores reporting if error is not an object', () => { observeApiError('string', metricObserver); expect(metricObserver).toHaveBeenCalledTimes(0); }); it('ignores reporting if status is -1 (offline)', () => { observeApiError({ status: -1 }, metricObserver); expect(metricObserver).toHaveBeenCalledTimes(0); }); it('ignores reporting if status is 0', () => { observeApiError({ status: 0 }, metricObserver); expect(metricObserver).toHaveBeenCalledTimes(0); }); it('ignores reporting if error does not contain a status property', () => { observeApiError('', metricObserver); expect(metricObserver).toHaveBeenCalledTimes(0); }); it('ignores reporting if it is an abort error', () => { observeApiError({ name: 'AbortError ' }, metricObserver); expect(metricObserver).toHaveBeenCalledTimes(0); }); it('ignores reporting if it is an HV error', () => { observeApiError({ status: 422, data: { Error: 'HV required', Code: 9001 } }, metricObserver); expect(metricObserver).toHaveBeenCalledTimes(0); }); it('returns 5xx if error.status is 500', () => { observeApiError({ status: 500 }, metricObserver); expect(metricObserver).toHaveBeenCalledTimes(1); expect(metricObserver).toHaveBeenCalledWith('5xx'); }); it('returns 5xx if error.status is larger than 500', () => { observeApiError({ status: 501 }, metricObserver); expect(metricObserver).toHaveBeenCalledTimes(1); expect(metricObserver).toHaveBeenCalledWith('5xx'); }); it('returns 4xx if error.status is 400', () => { observeApiError({ status: 400 }, metricObserver); expect(metricObserver).toHaveBeenCalledTimes(1); expect(metricObserver).toHaveBeenCalledWith('4xx'); }); it('returns 4xx if error.status is larger than 400', () => { observeApiError({ status: 401 }, metricObserver); expect(metricObserver).toHaveBeenCalledTimes(1); expect(metricObserver).toHaveBeenCalledWith('4xx'); }); it('returns failure if error.status is not in the correct range', () => { observeApiError({ status: 200 }, metricObserver); expect(metricObserver).toHaveBeenCalledTimes(1); expect(metricObserver).toHaveBeenCalledWith('failure'); }); });
8,196
0
petrpan-code/ProtonMail/WebClients/packages
petrpan-code/ProtonMail/WebClients/packages/recovery-kit/standard-fonts.test.ts
/** * This is a test to ensure the bigint polyfill patch is applied. It is intended to catch a scenario where the * ed25519 library may get updated and we won't get notified through the yarn install. */ describe('pdf-lib', () => { it('should use the minified build of @pdf-lib/standard-fonts', () => { const file = require('@pdf-lib/standard-fonts/package.json'); expect(file.module).toBe('dist/standard-fonts.min.js'); expect(file.main).toBe('dist/standard-fonts.min.js'); expect(file.unpkg).toBe('dist/standard-fonts.min.js'); }); });
8,925
0
petrpan-code/ProtonMail/WebClients/packages/sieve/src
petrpan-code/ProtonMail/WebClients/packages/sieve/src/fromSieve/fromTree.test.ts
import folder from '../../fixtures/folder'; import v1StartsEndsTest from '../../fixtures/v1StartsEndsTest'; import v2 from '../../fixtures/v2'; import v2Attachments from '../../fixtures/v2Attachments'; import v2Complex from '../../fixtures/v2Complex'; import v2EscapeVariables from '../../fixtures/v2EscapeVariables'; import v2From from '../../fixtures/v2From'; import v2InvalidStructure from '../../fixtures/v2InvalidStructure'; import v2SpamOnly from '../../fixtures/v2SpamOnly'; import v2StartsEndsTest from '../../fixtures/v2StartsEndsTest'; import v2Vacation from '../../fixtures/v2Vacation'; import v2VacationDouble from '../../fixtures/v2VacationDouble'; import v2VariableManyConditionsComplex from '../../fixtures/v2VariableManyConditionsComplex'; import { fromSieveTree } from './fromSieveTree'; describe('To Tree testing', () => { it('fromSieveTree - Should match simple test', () => { const { simple, tree } = folder; const generated = fromSieveTree(tree); expect(generated).toEqual(simple); }); it('fromSieveTree - Should match on v2', () => { const { simple, tree } = v2; const generated = fromSieveTree(tree); expect(generated).toEqual(simple); }); it('fromSieveTree - Should match on v1 with tree', () => { const { simple, tree } = v1StartsEndsTest; const generated = fromSieveTree(tree); expect(generated).toEqual(simple); }); it('fromSieveTree - Should match on v2 with tree', () => { const { simple, tree } = v2StartsEndsTest; const generated = fromSieveTree(tree); expect(generated).toEqual(simple); }); it('fromSieveTree - Should match on v2 with attachments', () => { const { simple, tree } = v2Attachments; const generated = fromSieveTree(tree); expect(generated).toEqual(simple); }); it('fromSieveTree - Should match on v2 with vacation', () => { const { simple, tree } = v2Vacation; const generated = fromSieveTree(tree); expect(generated).toEqual(simple); }); it('fromSieveTree - Should match on v2 with from', () => { const { simple, tree } = v2From; const generated = fromSieveTree(tree); expect(generated).toEqual(simple); }); it('fromSieveTree - Should match on v2 with complex', () => { const { simple, tree } = v2Complex; const generated = fromSieveTree(tree); expect(generated).toEqual(simple); }); it('fromSieveTree - Should match on v2 with vacation double', () => { const { simple, tree } = v2VacationDouble; const generated = fromSieveTree(tree); expect(generated).toEqual(simple); }); it('fromSieveTree - Should match on v2 with complex with many conditions and variables', () => { const { simple, tree } = v2VariableManyConditionsComplex; const generated = fromSieveTree(tree); expect(generated).toEqual(simple); }); it('fromSieveTree - Should match on v2 with escape variables', () => { const { simple, tree } = v2EscapeVariables; const generated = fromSieveTree(tree); expect(generated).toEqual(simple); }); it('fromSieveTree - Should error on invalid tree', () => { const { simple, tree } = v2InvalidStructure; const generated = fromSieveTree(tree); expect(generated).toEqual(simple); }); it('fromSieveTree - Should match on v2 with spam only folder', () => { const { simple, tree } = v2SpamOnly; const generated = fromSieveTree(tree); expect(generated).toEqual(simple); }); });
8,928
0
petrpan-code/ProtonMail/WebClients/packages/sieve/src
petrpan-code/ProtonMail/WebClients/packages/sieve/src/toSieve/toTree.test.ts
import archive from '../../fixtures/archive'; import folder from '../../fixtures/folder'; import v1StartsEndsTest from '../../fixtures/v1StartsEndsTest'; import v2 from '../../fixtures/v2'; import v2Attachments from '../../fixtures/v2Attachments'; import v2Complex from '../../fixtures/v2Complex'; import v2EscapeVariables from '../../fixtures/v2EscapeVariables'; import v2From from '../../fixtures/v2From'; import v2StartsEndsTest from '../../fixtures/v2StartsEndsTest'; import v2Vacation from '../../fixtures/v2Vacation'; import { toSieveTree } from './toSieveTree'; describe('To Tree testing', () => { it('toSieveTree - Should match simple test', () => { const { simple, tree } = archive; const generated = toSieveTree(simple, 1); expect(generated).toEqual(tree); }); it('toSieveTree - Should match on folders mapping', () => { const { simple, tree } = folder; const generated = toSieveTree(simple, 1); expect(generated).toEqual(tree); }); it('toSieveTree - Should match on v2', () => { const { simple, tree } = v2; const generated = toSieveTree(simple, 2); expect(generated).toEqual(tree); }); it('toSieveTree - Should match on v1 with tree', () => { const { simple, tree } = v1StartsEndsTest; const generated = toSieveTree(simple, 1); expect(generated).toEqual(tree); }); it('toSieveTree - Should match on v2 with tree', () => { const { simple, tree } = v2StartsEndsTest; const generated = toSieveTree(simple, 2); expect(generated).toEqual(tree); }); it('toSieveTree - Should match on v2 with attachments', () => { const { simple, tree } = v2Attachments; const generated = toSieveTree(simple, 2); expect(generated).toEqual(tree); }); it('toSieveTree - Should match on v2 with vacation', () => { const { simple, tree } = v2Vacation; const generated = toSieveTree(simple, 2); expect(generated).toEqual(tree); }); it('toSieveTree - Should match on v2 with from', () => { const { simple, tree } = v2From; const generated = toSieveTree(simple, 2); expect(generated).toEqual(tree); }); it('toSieveTree - Should match on v2 with complex', () => { const { simple, tree } = v2Complex; const generated = toSieveTree(simple, 2); expect(generated).toEqual(tree); }); it('toSieveTree - Should match on v2 with escape variables', () => { const { simple, tree } = v2EscapeVariables; const generated = toSieveTree(simple, 2); expect(generated).toEqual(tree); }); });