level_0
int64 0
10k
| index
int64 0
0
| repo_id
stringlengths 22
152
| file_path
stringlengths 41
203
| content
stringlengths 11
11.5M
|
---|---|---|---|---|
3,467 | 0 | petrpan-code/ProtonMail/WebClients/applications/mail/src/app/components/eo/message | petrpan-code/ProtonMail/WebClients/applications/mail/src/app/components/eo/message/tests/ViewEOMessage.images.test.tsx | import { findByRole, findByText, fireEvent, screen, waitFor } from '@testing-library/react';
import { VERIFICATION_STATUS } from '@proton/shared/lib/mail/constants';
import { releaseCryptoProxy, setupCryptoProxyForTesting } from '../../../../helpers/test/crypto';
import { EOBody, EOClearAll, EOSubject } from '../../../../helpers/test/eo/helpers';
import { getIframeRootDiv } from '../../../message/tests/Message.test.helpers';
import { setup } from './ViewEOMessage.test.helpers';
const blobURL = 'blobURL';
const embeddedCID = 'cid-embedded';
const embeddedAttachment = {
ID: 'id3',
Name: 'attachment-name-png.png',
Size: 300,
MIMEType: 'image/png',
// Allow to skip actual download of the file content
Preview: {
data: new Uint8Array([1, 2]),
filename: 'preview',
signatures: [],
verified: VERIFICATION_STATUS.NOT_SIGNED,
},
KeyPackets: [],
nameSplitStart: 'attachment-name-p',
nameSplitEnd: 'ng.png',
Headers: { 'content-id': embeddedCID, 'content-disposition': 'inline' },
};
describe('Encrypted Outside message images', () => {
beforeAll(async () => {
// mockWindowLocation(windowHostname);
await setupCryptoProxyForTesting();
});
afterAll(async () => {
await releaseCryptoProxy();
});
afterEach(() => {
EOClearAll();
// resetWindowLocation();
});
it('should load remote images', async () => {
const imageURL = 'imageURL';
const body = `<div>${EOBody}<img src="${imageURL}"/></div>`;
const { container } = await setup({ body });
// wait for the message to be fully loaded
await waitFor(() => screen.getByText(EOSubject));
const iframe = await getIframeRootDiv(container);
// Content is displayed
await findByText(iframe, EOBody);
// Check for image placeholder
const placeholder = iframe.querySelector('.proton-image-placeholder') as HTMLImageElement;
expect(placeholder).not.toBe(null);
// Click on load banner
screen.getByText('This message contains remote content.');
let loadButton = screen.getByTestId('remote-content:load');
fireEvent.click(loadButton);
// Check that image has been loaded
const image = await findByRole(iframe, 'img');
expect(image.getAttribute('src')).toEqual(imageURL);
});
it('should load embedded images', async () => {
const body = `<div>${EOBody}<img src="cid:${embeddedCID}"/></div>`;
// Need to mock this function to mock the blob url
window.URL.createObjectURL = jest.fn(() => blobURL);
const { container } = await setup({ body, attachments: [embeddedAttachment] });
// wait for the message to be fully loaded
await waitFor(() => screen.getByText(EOSubject));
const iframe = await getIframeRootDiv(container);
// Content is displayed
await findByText(iframe, EOBody);
// Check for image placeholder
const placeholder = iframe.querySelector('.proton-image-placeholder') as HTMLImageElement;
expect(placeholder).not.toBe(null);
// Click on load banner
const loadButton = screen.getByText('Load embedded images');
fireEvent.click(loadButton);
// Check that image has been loaded
const image = await findByRole(iframe, 'img');
expect(image.getAttribute('src')).toEqual(blobURL);
});
});
|
3,468 | 0 | petrpan-code/ProtonMail/WebClients/applications/mail/src/app/components/eo/message | petrpan-code/ProtonMail/WebClients/applications/mail/src/app/components/eo/message/tests/ViewEOMessage.reply.test.tsx | import { screen, waitFor } from '@testing-library/react';
import { releaseCryptoProxy, setupCryptoProxyForTesting } from '../../../../helpers/test/crypto';
import { EOClearAll, reply } from '../../../../helpers/test/eo/helpers';
import { EOMessageReply } from '../../../../logic/eo/eoType';
import { setup } from './ViewEOMessage.test.helpers';
describe('Encrypted Outside message reply', () => {
beforeAll(async () => {
await setupCryptoProxyForTesting();
});
afterAll(async () => {
await releaseCryptoProxy();
});
afterEach(EOClearAll);
it('should not be able to click on reply button if max replies has been reached', async () => {
await setup({ replies: [reply, reply, reply, reply, reply] as EOMessageReply[] });
const replyButton = await waitFor(() => screen.findByTestId('eoreply:button'));
expect(replyButton).toHaveAttribute('disabled');
});
it('should be able to click on reply button if max replies has not been reached', async () => {
await setup({ replies: [reply, reply, reply, reply] as EOMessageReply[] });
const replyButton = await waitFor(() => screen.findByTestId('eoreply:button'));
expect(replyButton).not.toHaveAttribute('disabled');
});
});
|
3,475 | 0 | petrpan-code/ProtonMail/WebClients/applications/mail/src/app/components/eo/reply | petrpan-code/ProtonMail/WebClients/applications/mail/src/app/components/eo/reply/tests/EOReply.attachments.test.tsx | import { act, fireEvent, waitFor } from '@testing-library/react';
import { wait } from '@proton/shared/lib/helpers/promise';
import { EO_REPLY_NUM_ATTACHMENTS_LIMIT } from '@proton/shared/lib/mail/eo/constants';
import { releaseCryptoProxy, setupCryptoProxyForTesting } from '../../../../helpers/test/crypto';
import { EOClearAll, EOSubject } from '../../../../helpers/test/eo/helpers';
import { waitForNotification } from '../../../../helpers/test/helper';
import { tick } from '../../../../helpers/test/render';
import { setup } from './EOReply.test.helpers';
describe('EO Reply attachments', () => {
beforeAll(async () => {
await setupCryptoProxyForTesting();
});
afterAll(async () => {
await releaseCryptoProxy();
});
afterEach(EOClearAll);
const fileName = 'file.txt';
const fileType = 'text/plain';
const fileContent = 'File content';
const blob = new Blob([fileContent], { type: fileType });
const file = new File([blob], fileName, { type: fileType });
it('should add attachments to a EO message and be able to preview them', async () => {
const { getByText, getByTestId } = await setup();
await waitFor(() => getByText(EOSubject));
const inputAttachment = getByTestId('composer-attachments-button') as HTMLInputElement;
await act(async () => {
fireEvent.change(inputAttachment, { target: { files: [file] } });
await wait(100);
});
const toggleList = await waitFor(() => getByTestId('attachment-list:toggle'));
fireEvent.click(toggleList);
await tick();
const item = getByTestId('attachment-item').querySelectorAll('button')[1];
fireEvent.click(item);
await tick();
const preview = document.querySelector('.file-preview');
expect(preview).toBeDefined();
expect(preview?.textContent).toMatch(new RegExp(fileName));
getByText(fileContent);
});
it('should not be possible to add 10+ attachments', async () => {
const { getByText, getByTestId } = await setup();
await waitFor(() => getByText(EOSubject));
// Add 11 files
const inputAttachment = getByTestId('composer-attachments-button') as HTMLInputElement;
await act(async () => {
fireEvent.change(inputAttachment, {
target: { files: [file, file, file, file, file, file, file, file, file, file, file] },
});
await wait(100);
});
await waitForNotification(`Maximum number of attachments (${EO_REPLY_NUM_ATTACHMENTS_LIMIT}) exceeded`);
});
});
|
3,476 | 0 | petrpan-code/ProtonMail/WebClients/applications/mail/src/app/components/eo/reply | petrpan-code/ProtonMail/WebClients/applications/mail/src/app/components/eo/reply/tests/EOReply.reply.test.tsx | import { waitFor } from '@testing-library/react';
import { releaseCryptoProxy, setupCryptoProxyForTesting } from '../../../../helpers/test/crypto';
import { EOClearAll, reply } from '../../../../helpers/test/eo/helpers';
import { setup } from './EOReply.test.helpers';
describe('EO Reply if max replies has been reached', function () {
beforeAll(async () => {
await setupCryptoProxyForTesting();
});
afterAll(async () => {
await releaseCryptoProxy();
});
afterEach(EOClearAll);
it('should have the sending button disabled if max replies has been reached', async () => {
const { getByTestId } = await setup({ replies: [reply, reply, reply, reply, reply] });
const sendButton = await waitFor(() => getByTestId('send-eo'));
expect(sendButton).toHaveAttribute('disabled');
});
it('should have the sending button enabled if max replies has not been reached', async () => {
const { getByTestId } = await setup({ replies: [reply, reply, reply] });
const sendButton = await waitFor(() => getByTestId('send-eo'));
expect(sendButton).not.toHaveAttribute('disabled');
});
});
|
3,477 | 0 | petrpan-code/ProtonMail/WebClients/applications/mail/src/app/components/eo/reply | petrpan-code/ProtonMail/WebClients/applications/mail/src/app/components/eo/reply/tests/EOReply.sending.test.tsx | import { CryptoProxy } from '@proton/crypto';
import { releaseCryptoProxy, setupCryptoProxyForTesting } from '../../../../helpers/test/crypto';
import { EOGetHistory } from '../../../../helpers/test/eo/EORender';
import { EOClearAll, EOPassword, validID } from '../../../../helpers/test/eo/helpers';
import { send } from './EOReply.test.helpers';
jest.setTimeout(20000);
describe('EO Reply send', () => {
beforeAll(async () => {
await setupCryptoProxyForTesting();
});
afterAll(async () => {
await releaseCryptoProxy();
});
afterEach(EOClearAll);
it('should send a text/html reply', async () => {
const expectedBlockquote = `
<blockquote class="protonmail_quote" type="cite">
Test EO body
</blockquote>`;
const sendRequest = await send();
const { data: decryptedReplyBody } = await CryptoProxy.decryptMessage({
armoredMessage: sendRequest.data.ReplyBody,
passwords: [EOPassword],
});
// Format the reply to remove all \n and spaces to check if they are equal
const formattedReplyBody = decryptedReplyBody.replaceAll(/[ \n]/g, '');
const formattedExpectedBody = expectedBlockquote.replaceAll(/[ \n]/g, '');
expect(formattedReplyBody).toContain(formattedExpectedBody);
const history = EOGetHistory();
expect(history.location.pathname).toBe(`/eo/message/${validID}`);
});
});
|
3,479 | 0 | petrpan-code/ProtonMail/WebClients/applications/mail/src/app/components/eo | petrpan-code/ProtonMail/WebClients/applications/mail/src/app/components/eo/unlock/EOUnlock.test.tsx | import { act, fireEvent } from '@testing-library/react';
import { wait } from '@proton/shared/lib/helpers/promise';
import { addApiMock } from '../../../helpers/test/api';
import { releaseCryptoProxy, setupCryptoProxyForTesting } from '../../../helpers/test/crypto';
import { EOGetHistory, EORender, EOResetHistory } from '../../../helpers/test/eo/EORender';
import {
EOClearAll,
EODecryptedToken,
EOInvalidPassword,
EOPassword,
getEOEncryptedMessage,
mockConsole,
validID,
} from '../../../helpers/test/eo/helpers';
import { waitForNotification } from '../../../helpers/test/helper';
import { init } from '../../../logic/eo/eoActions';
import { store } from '../../../logic/eo/eoStore';
import { EOMessage } from '../../../logic/eo/eoType';
import EOUnlock from './EOUnlock';
const props = {
setSessionStorage: jest.fn(),
};
describe('Encrypted Outside Unlock', () => {
beforeAll(async () => {
await setupCryptoProxyForTesting();
});
afterAll(async () => {
await releaseCryptoProxy();
});
beforeEach(async () => {
await store.dispatch(init({ get: jest.fn() }));
});
afterEach(EOClearAll);
it('should display an error if the EO id is not present', async () => {
const { getByText } = await EORender(<EOUnlock {...props} />);
getByText('Error');
getByText('Sorry, this message does not exist or has already expired.');
});
it('should display an error if the EO id is invalid', async () => {
addApiMock('mail/v4/eo/token/invalidID', () => ({}));
EOResetHistory(['/eo/invalidID']);
const { getByText } = await EORender(<EOUnlock {...props} />, '/eo/:id');
getByText('Error');
getByText('Sorry, this message does not exist or has already expired.');
});
it('should see the form if the EO id is valid and an error if password is invalid', async () => {
mockConsole();
EOResetHistory([`/eo/${validID}`]);
// Get token from id mock
addApiMock(`mail/v4/eo/token/${validID}`, () => ({ Token: 'token' }));
const { getByText, getByTestId } = await EORender(<EOUnlock {...props} />, '/eo/:id');
// Unlock form is displayed
getByText('Unlock message');
const unlockInput = getByTestId('unlock:input');
// Type the password
fireEvent.change(unlockInput, { target: { value: EOInvalidPassword } });
fireEvent.keyDown(unlockInput, { key: 'Enter' });
await waitForNotification('Wrong mailbox password');
});
it('should see the form if the EO id is valid and redirect if password is valid', async () => {
mockConsole('log');
const token = await getEOEncryptedMessage(EODecryptedToken, EOPassword);
EOResetHistory([`/eo/${validID}`]);
// Get token from id mock
addApiMock(`mail/v4/eo/token/${validID}`, () => ({ Token: token }));
// Get EO message from decryptedToken and password
addApiMock('mail/v4/eo/message', () => ({
Message: {} as EOMessage,
PublicKey: '',
}));
const { getByText, getByTestId } = await EORender(<EOUnlock {...props} />, '/eo/:id');
// Unlock form is displayed
getByText('Unlock message');
const unlockInput = getByTestId('unlock:input');
// Type the password
fireEvent.change(unlockInput, { target: { value: EOPassword } });
fireEvent.keyDown(unlockInput, { key: 'Enter' });
// Wait for redirection
await act(async () => {
await wait(2000);
});
// Redirects to /eo/message/validID
const history = EOGetHistory();
expect(history.location.pathname).toBe(`/eo/message/${validID}`);
});
});
|
3,484 | 0 | petrpan-code/ProtonMail/WebClients/applications/mail/src/app/components | petrpan-code/ProtonMail/WebClients/applications/mail/src/app/components/header/MailHeader.test.tsx | import { fireEvent } from '@testing-library/react';
import { screen } from '@testing-library/react';
import loudRejection from 'loud-rejection';
import { MAILBOX_LABEL_IDS } from '@proton/shared/lib/constants';
import {
addApiMock,
addToCache,
clearAll,
getDropdown,
getHistory,
minimalCache,
render,
tick,
} from '../../helpers/test/helper';
import { Breakpoints } from '../../models/utils';
import MailHeader from './MailHeader';
loudRejection();
const getProps = () => ({
labelID: 'labelID',
elementID: undefined,
selectedIDs: [],
location: getHistory().location,
history: getHistory(),
breakpoints: {} as Breakpoints,
onSearch: jest.fn(),
expanded: true,
onToggleExpand: jest.fn(),
onOpenShortcutsModal: jest.fn(),
});
const user = {
Email: 'Email',
DisplayName: 'DisplayName',
Name: 'Name',
isFree: true,
UsedSpace: 10,
MaxSpace: 100,
};
describe('MailHeader', () => {
let props: ReturnType<typeof getProps>;
const setup = async () => {
minimalCache();
addToCache('User', user);
addApiMock('payments/v4/plans', () => ({}));
addApiMock('contacts/v4/contacts', () => ({ Contacts: [] }));
addApiMock('payments/v4/subscription/latest', () => ({}));
addApiMock('core/v4/experiments', () => ({}));
props = getProps();
const result = await render(<MailHeader {...props} />, false);
const search = result.getByTitle('Search');
const openSearch = async () => {
fireEvent.click(search);
await tick();
const overlay = document.querySelector('div[role="dialog"].overlay') as HTMLDivElement;
const submitButton = overlay.querySelector('button[type="submit"]') as HTMLButtonElement;
const submit = () => fireEvent.click(submitButton);
return { overlay, submitButton, submit };
};
return { ...result, openSearch };
};
// Not found better to test
// It's hard to override sso mode constant
const assertAppLink = (element: HTMLElement, href: string) => {
const link = element.closest('a');
expect(link?.getAttribute('href')).toBe(href);
};
afterEach(clearAll);
describe('Core features', () => {
it('should open user dropdown', async () => {
const { getByText: getByTextHeader } = await setup();
const userButton = getByTextHeader(user.DisplayName);
fireEvent.click(userButton);
const dropdown = await getDropdown();
const { textContent } = dropdown;
expect(textContent).toContain('Proton shop');
expect(textContent).toContain('Sign out');
});
it('should show upgrade button', async () => {
const { getByTestId } = await setup();
const upgradeLabel = getByTestId('cta:upgrade-plan');
assertAppLink(upgradeLabel, '/mail/upgrade?ref=upsell_mail-button-1');
});
});
describe('Search features', () => {
it('should search with keyword', async () => {
const searchTerm = 'test';
const { getByTestId, openSearch, rerender } = await setup();
const { submit } = await openSearch();
const keywordInput = document.getElementById('search-keyword') as HTMLInputElement;
fireEvent.change(keywordInput, { target: { value: searchTerm } });
submit();
const history = getHistory();
expect(history.length).toBe(2);
expect(history.location.pathname).toBe('/all-mail');
expect(history.location.hash).toBe(`#keyword=${searchTerm}`);
await rerender(<MailHeader {...props} />);
const searchKeyword = getByTestId('search-keyword') as HTMLInputElement;
expect(searchKeyword.value).toBe(searchTerm);
});
it('should search with keyword and location', async () => {
const searchTerm = 'test';
const { openSearch } = await setup();
const { submit } = await openSearch();
const keywordInput = document.getElementById('search-keyword') as HTMLInputElement;
fireEvent.change(keywordInput, { target: { value: searchTerm } });
const draftButton = screen.getByTestId(`location-${MAILBOX_LABEL_IDS.DRAFTS}`);
fireEvent.click(draftButton);
submit();
const history = getHistory();
expect(history.length).toBe(2);
expect(history.location.pathname).toBe('/drafts');
expect(history.location.hash).toBe(`#keyword=${searchTerm}`);
});
});
});
|
3,496 | 0 | petrpan-code/ProtonMail/WebClients/applications/mail/src/app/components/header/search | petrpan-code/ProtonMail/WebClients/applications/mail/src/app/components/header/search/AdvancedSearchFields/LocationField.test.tsx | import { render, screen, waitFor } from '@testing-library/react';
import userEvent from '@testing-library/user-event';
import { MAILBOX_LABEL_IDS } from '@proton/shared/lib/constants';
import { ALMOST_ALL_MAIL } from '@proton/shared/lib/mail/mailSettings';
import { mockUseFolders, mockUseMailSettings } from '@proton/testing/index';
import LocationField from './LocationField';
import { mockUseLocationFieldOptions } from './LocationField.test.utils';
describe('LocationField', () => {
beforeEach(() => {
mockUseMailSettings();
mockUseLocationFieldOptions();
mockUseFolders();
});
it('should correctly render main locations buttons', () => {
render(<LocationField value={MAILBOX_LABEL_IDS.ALL_MAIL} onChange={jest.fn()} />);
expect(screen.getByText('Search in'));
const allMailButton = screen.getByRole('button', { name: 'Search in All mail' });
expect(allMailButton).toBeInTheDocument();
expect(allMailButton).toHaveClass('button-solid-norm');
expect(screen.getByRole('button', { name: 'Search in Inbox' }));
expect(screen.getByRole('button', { name: 'Search in Drafts' }));
expect(screen.getByRole('button', { name: 'Search in Sent' }));
expect(screen.getByRole('button', { name: 'Other' }));
});
describe('when user click on another location', () => {
it('should correctly change location', async () => {
const onChange = jest.fn();
render(<LocationField value={MAILBOX_LABEL_IDS.INBOX} onChange={onChange} />);
const draftsButton = screen.getByRole('button', { name: 'Search in Drafts' });
await userEvent.click(draftsButton);
await waitFor(() => {
expect(onChange).toHaveBeenCalledTimes(1);
});
expect(onChange).toHaveBeenCalledWith(MAILBOX_LABEL_IDS.DRAFTS);
});
});
describe('when user click on Other button', () => {
it('should correctly change location', async () => {
const onChange = jest.fn();
render(<LocationField value={MAILBOX_LABEL_IDS.INBOX} onChange={onChange} />);
const otherButton = screen.getByRole('button', { name: 'Other' });
await userEvent.click(otherButton);
await waitFor(() => {
expect(screen.getByText('Labels')).toBeInTheDocument();
});
const customLabelButton = screen.getByRole('button', { name: 'Highlighted' });
await userEvent.click(customLabelButton);
await waitFor(() => {
expect(onChange).toHaveBeenCalledTimes(1);
});
expect(onChange).toHaveBeenCalledWith('36');
});
});
describe('when custom option is set', () => {
it('should correctly change location', async () => {
const onChange = jest.fn();
render(<LocationField value={'36'} onChange={onChange} />);
expect(screen.getByText('Highlighted')).toBeInTheDocument();
const customLabelButton = screen.getByRole('button', { name: 'Remove' });
expect(customLabelButton).toBeInTheDocument();
expect(customLabelButton).toHaveClass('button-solid-norm');
await userEvent.click(customLabelButton);
await waitFor(() => {
expect(onChange).toHaveBeenCalledTimes(1);
});
expect(onChange).toHaveBeenCalledWith(MAILBOX_LABEL_IDS.ALL_MAIL);
});
describe('when Almost All Mail is set', () => {
it('should correctly change location', async () => {
mockUseMailSettings([{ AlmostAllMail: ALMOST_ALL_MAIL.ENABLED }]);
const onChange = jest.fn();
render(<LocationField value={'36'} onChange={onChange} />);
expect(screen.getByText('Highlighted')).toBeInTheDocument();
const customLabelButton = screen.getByRole('button', { name: 'Remove' });
expect(customLabelButton).toBeInTheDocument();
expect(customLabelButton).toHaveClass('button-solid-norm');
await userEvent.click(customLabelButton);
await waitFor(() => {
expect(onChange).toHaveBeenCalledTimes(1);
});
expect(onChange).toHaveBeenCalledWith(MAILBOX_LABEL_IDS.ALMOST_ALL_MAIL);
});
});
});
});
|
3,502 | 0 | petrpan-code/ProtonMail/WebClients/applications/mail/src/app/components/header/search | petrpan-code/ProtonMail/WebClients/applications/mail/src/app/components/header/search/AdvancedSearchFields/useLocationFieldOptions.test.ts | import { ALMOST_ALL_MAIL } from '@proton/shared/lib/mail/mailSettings';
import { mockUseFolders, mockUseLabels, mockUseMailSettings } from '@proton/testing/index';
import { mockUseScheduleSendFeature } from 'proton-mail/helpers/test/mockUseScheduleSendFeature';
import { useLocationFieldOptions } from './useLocationFieldOptions';
import { expectedAll, expectedGrouped } from './useLocationFieldOptions.test.data';
jest.mock('proton-mail/hooks/actions/useSnooze', () => ({
__esModule: true,
default: jest.fn().mockReturnValue({
canSnooze: true,
canUnsnooze: true,
isSnoozeEnabled: true,
snooze: jest.fn(),
unsnooze: jest.fn(),
handleClose: jest.fn(),
handleCustomClick: jest.fn(),
snoozeState: 'snooze-selection',
}),
}));
describe('useLocationFieldOptions', () => {
beforeEach(() => {
mockUseMailSettings();
mockUseScheduleSendFeature();
mockUseLabels([
[
{
ID: 'highlighted',
Name: 'highlighted',
Path: 'highlighted',
Type: 1,
Color: '#EC3E7C',
Order: 2,
Display: 1,
},
],
]);
mockUseFolders([
[
{
ID: '31dixxUc6tNkpKrI-abC_IQcnG4_K2brHumXkQb_Ib4-FEl5Q3n27dbhIkfBTnYrNonJ8DsySBbUM0RtQdhYhA==',
Name: 'news',
Path: 'news',
Type: 3,
Color: '#54473f',
Order: 1,
Notify: 1,
Expanded: 0,
},
],
]);
});
it('should return correct helper', () => {
const [defaults, customs, labels] = expectedGrouped;
const helper = useLocationFieldOptions();
expect(helper.all).toStrictEqual(expectedAll);
expect(helper.grouped).toStrictEqual(expectedGrouped);
expect(helper.findItemByValue('highlighted')).toStrictEqual(labels.items[0]);
expect(helper.isDefaultFolder(defaults.items[0])).toBe(true);
expect(helper.isDefaultFolder(customs.items[0])).toBe(false);
expect(helper.isCustomFolder(customs.items[0])).toBe(true);
expect(helper.isCustomFolder(defaults.items[0])).toBe(false);
expect(helper.isLabel(labels.items[0])).toBe(true);
expect(helper.isLabel(customs.items[0])).toBe(false);
});
describe('when Almost All Mail is true', () => {
beforeEach(() => {
mockUseMailSettings([{ AlmostAllMail: ALMOST_ALL_MAIL.ENABLED }]);
});
it('should return specific helper', () => {
const helper = useLocationFieldOptions();
expect(helper.all).toStrictEqual([
{
value: '15',
text: 'All mail',
url: '/almost-all-mail',
icon: 'envelopes',
},
...expectedAll.slice(1),
]);
});
});
});
|
3,511 | 0 | petrpan-code/ProtonMail/WebClients/applications/mail/src/app/components | petrpan-code/ProtonMail/WebClients/applications/mail/src/app/components/list/ItemAttachmentThumbnails.test.tsx | import { fireEvent, screen } from '@testing-library/react';
import { useFlag } from '@proton/components/index';
import { WorkerDecryptionResult } from '@proton/crypto';
import { MAILBOX_LABEL_IDS } from '@proton/shared/lib/constants';
import downloadFile from '@proton/shared/lib/helpers/downloadFile';
import { AttachmentsMetadata } from '@proton/shared/lib/interfaces/mail/Message';
import { ATTACHMENT_DISPOSITION } from '@proton/shared/lib/mail/constants';
import { encryptAttachment } from '@proton/shared/lib/mail/send/attachments';
import isTruthy from '@proton/utils/isTruthy';
import mergeUint8Arrays from '@proton/utils/mergeUint8Arrays';
import ItemColumnLayout from 'proton-mail/components/list/ItemColumnLayout';
import { MAX_COLUMN_ATTACHMENT_THUMBNAILS } from 'proton-mail/constants';
import { filterAttachmentToPreview } from 'proton-mail/helpers/attachment/attachmentThumbnails';
import { arrayToBase64 } from 'proton-mail/helpers/base64';
import { addApiMock } from 'proton-mail/helpers/test/api';
import {
GeneratedKey,
addApiKeys,
addKeysToAddressKeysCache,
assertIcon,
clearAll,
createAttachment,
generateKeys,
releaseCryptoProxy,
setupCryptoProxyForTesting,
tick,
} from 'proton-mail/helpers/test/helper';
import { render } from 'proton-mail/helpers/test/render';
import { addAttachment } from 'proton-mail/logic/attachments/attachmentsActions';
import { store } from 'proton-mail/logic/store';
import { Conversation } from 'proton-mail/models/conversation';
import { Breakpoints } from 'proton-mail/models/utils';
jest.mock('@proton/shared/lib/helpers/downloadFile', () => {
return jest.fn();
});
const mockUseFlag = useFlag as unknown as jest.MockedFunction<any>;
const fileContent = `test-content`;
const generateAttachmentsMetadata = (numberOfAttachments: number, extension = 'png', mimeType = 'image/png') => {
const attachmentsMetadata: AttachmentsMetadata[] = [];
for (let i = 0; i < numberOfAttachments; i++) {
const metadata: AttachmentsMetadata = {
ID: i.toString(),
Disposition: ATTACHMENT_DISPOSITION.ATTACHMENT,
MIMEType: mimeType,
Size: 200000,
Name: `Attachment-${i}.${extension}`,
};
attachmentsMetadata.push(metadata);
}
return attachmentsMetadata;
};
const setup = async (attachmentsMetadata: AttachmentsMetadata[], numAttachments: number) => {
const element = {
ID: 'conversationID',
Subject: 'Conversation thumbnails',
Time: Date.now(),
Senders: [{ Address: '[email protected]', Name: 'Sender' }],
Recipients: [{ Address: '[email protected]', Name: 'Recipient' }],
Labels: [{ ID: MAILBOX_LABEL_IDS.INBOX }],
NumAttachments: numAttachments,
AttachmentsMetadata: attachmentsMetadata,
} as Conversation;
await render(
<ItemColumnLayout
labelID={MAILBOX_LABEL_IDS.INBOX}
element={element}
conversationMode={true}
showIcon={true}
senders={<>Sender</>}
breakpoints={{} as Breakpoints}
unread={false}
onBack={jest.fn()}
isSelected={false}
attachmentsMetadata={filterAttachmentToPreview(attachmentsMetadata)}
/>
);
};
describe('ItemAttachmentThumbnails', () => {
beforeAll(() => {
// Mock feature flag
// TODO update when we'll have a better solution
mockUseFlag.mockReturnValue(true);
});
afterEach(() => clearAll());
it('should not display attachment thumbnails', async () => {
const elementTotalAttachments = 0;
// The conversation has no attachments.
await setup([], elementTotalAttachments);
// No attachment thumbnail displayed
expect(screen.queryByText(`Attachment-`)).toBeNull();
// +X should not be displayed
expect(screen.queryByTestId('attachment-thumbnail:other-attachment-number')).toBeNull();
// Paper clip icon is not displayed
expect(screen.queryByTestId('item-attachment-icon-paper-clip')).toBeNull();
});
it('should display attachment thumbnails', async () => {
const numberOfReceivedMetadata = 5;
const attachmentsMetadata = generateAttachmentsMetadata(numberOfReceivedMetadata);
// We received the metadata for 5 attachments, and we can display 2 thumbnails
await setup(attachmentsMetadata, numberOfReceivedMetadata);
const items = screen.getAllByTestId('attachment-thumbnail');
// 2 first attachments are displayed
for (let i = 0; i < MAX_COLUMN_ATTACHMENT_THUMBNAILS; i++) {
expect(items[i].textContent).toEqual(`Attachment-${i}.png`);
}
// Other received attachments are not displayed since we cannot display them
for (let i = MAX_COLUMN_ATTACHMENT_THUMBNAILS; i < numberOfReceivedMetadata; i++) {
// use title because text is split in multiple elements
expect(screen.queryByTitle(`Attachment-${i}.png`)).toBeNull();
}
// Since we have 5 attachment metadata, and we display 2 of them. So we should see +3
screen.getByText(`+${numberOfReceivedMetadata - MAX_COLUMN_ATTACHMENT_THUMBNAILS}`);
// Paper clip icon is displayed (in row mode paper clip can be rendered twice because of responsive)
screen.getAllByTestId('item-attachment-icon-paper-clip');
});
it('should not display +X attachment', async () => {
const numberOfReceivedMetadata = 1;
const attachmentsMetadata = generateAttachmentsMetadata(numberOfReceivedMetadata);
// The conversation has 1 attachment in total.
// We received the metadata for 1 of them, which will display 1 thumbnail
await setup(attachmentsMetadata, numberOfReceivedMetadata);
const items = screen.getAllByTestId('attachment-thumbnail');
// 2 first attachments are displayed
for (let i = 0; i < numberOfReceivedMetadata; i++) {
// use title because text is split in multiple elements
expect(items[i].textContent).toEqual(`Attachment-${i}.png`);
}
// No other thumbnail element is displayed
for (let i = numberOfReceivedMetadata; i < MAX_COLUMN_ATTACHMENT_THUMBNAILS; i++) {
expect(screen.queryByTitle(`Attachment-${i}.png`)).toBeNull();
}
// +X should not be displayed
expect(screen.queryByTestId('attachment-thumbnail:other-attachment-number')).toBeNull();
// Paper clip icon is displayed (in row mode paper clip can be rendered twice because of responsive)
screen.getAllByTestId('item-attachment-icon-paper-clip');
});
it('should should display paper clip icon and no thumbnails when no attachment can be previewed', async () => {
const elementTotalAttachments = 10;
// The conversation has 10 attachment in total.
// We received no metadata, so no thumbnail will be displayed
await setup([], elementTotalAttachments);
// No attachment thumbnail displayed
expect(screen.queryByText(`Attachment-`)).toBeNull();
// +X should not be displayed
expect(screen.queryByTestId('attachment-thumbnail:other-attachment-number')).toBeNull();
// Paper clip icons are displayed
expect(screen.getAllByTestId('item-attachment-icon-paper-clip').length).toBe(2);
});
it('should display the expected attachment icon', async () => {
const numAttachments = 2;
const attachmentsMetadata: AttachmentsMetadata[] = [
{
ID: '0',
Disposition: ATTACHMENT_DISPOSITION.ATTACHMENT,
MIMEType: 'image/png',
Size: 200000,
Name: `Attachment-0.png`,
},
{
ID: '1',
Disposition: ATTACHMENT_DISPOSITION.ATTACHMENT,
MIMEType: 'application/pdf',
Size: 200000,
Name: `Attachment-1.pdf`,
},
];
const icons = ['sm-image', 'sm-pdf'];
const extensions = ['png', 'pdf'];
await setup(attachmentsMetadata, numAttachments);
const items = screen.getAllByTestId('attachment-thumbnail');
for (let i = 0; i < 2; i++) {
expect(items[i].textContent).toEqual(`Attachment-${i}.${extensions[i]}`);
assertIcon(items[i].querySelector('svg'), icons[i], undefined, 'mime');
}
});
});
describe('ItemAttachmentThumbnails - Preview', () => {
const AddressID = 'AddressID';
const fromAddress = '[email protected]';
let fromKeys: GeneratedKey;
beforeAll(async () => {
// Mock feature flag
// TODO update when we'll have a better solution
mockUseFlag.mockReturnValue(true);
addApiKeys(false, fromAddress, []);
});
beforeEach(async () => {
await setupCryptoProxyForTesting();
clearAll();
fromKeys = await generateKeys('me', fromAddress);
addKeysToAddressKeysCache(AddressID, fromKeys);
});
afterEach(async () => {
clearAll();
await releaseCryptoProxy();
});
const mockAttachmentThumbnailsAPICalls = async (
attachmentsMetadata: AttachmentsMetadata[],
keys: GeneratedKey,
decryptShouldFail = false
) => {
addApiMock('core/v4/keys/all', () => ({ Address: { Keys: [] } }));
return Promise.all(
attachmentsMetadata.map(async (metadata) => {
const { ID, Name, MIMEType } = metadata;
const attachmentID = ID;
const attachmentName = Name;
const attachmentType = MIMEType;
const file = new File([new Blob([fileContent])], attachmentName, { type: attachmentType });
const attachmentPackets = await encryptAttachment(fileContent, file, false, keys.publicKeys, []);
// Trigger a fail during decrypt (when necessary) to test some scenarios (e.g. decryption failed)
const concatenatedPackets = decryptShouldFail
? []
: mergeUint8Arrays(
[attachmentPackets.data, attachmentPackets.keys, attachmentPackets.signature].filter(isTruthy)
);
const attachmentSpy = jest.fn(() => concatenatedPackets);
const attachmentMetadataSpy = jest.fn(() => ({
Attachment: {
KeyPackets: arrayToBase64(attachmentPackets.keys),
Sender: { Address: fromAddress },
AddressID,
},
}));
addApiMock(`mail/v4/attachments/${attachmentID}`, attachmentSpy);
addApiMock(`mail/v4/attachments/${attachmentID}/metadata`, attachmentMetadataSpy);
return {
attachmentSpy,
attachmentMetadataSpy,
attachmentPackets,
};
})
);
};
it('should preview an attachment that was already in Redux state', async () => {
window.URL.createObjectURL = jest.fn();
const numAttachments = 1;
const attachmentsMetadata = generateAttachmentsMetadata(numAttachments, 'txt', 'text/plain');
const { attachment } = await createAttachment(
{
ID: attachmentsMetadata[0].ID,
Name: attachmentsMetadata[0].Name,
MIMEType: attachmentsMetadata[0].MIMEType,
data: new Uint8Array(),
},
fromKeys.publicKeys
);
store.dispatch(
addAttachment({
ID: attachment.ID as string,
attachment: {
data: attachment.data,
} as WorkerDecryptionResult<Uint8Array>,
})
);
// Mock to check that if attachment is in the state, no api call is done
const mocks = await mockAttachmentThumbnailsAPICalls(attachmentsMetadata, fromKeys);
await setup(attachmentsMetadata, numAttachments);
const item = screen.getByTestId('attachment-thumbnail');
fireEvent.click(item);
await tick();
const preview = screen.getByTestId('file-preview');
expect(preview?.textContent).toMatch(new RegExp(attachmentsMetadata[0].Name));
expect(mocks[0].attachmentSpy).not.toHaveBeenCalled();
expect(mocks[0].attachmentMetadataSpy).not.toHaveBeenCalled();
});
it('should preview an attachment that was not in Redux state', async () => {
window.URL.createObjectURL = jest.fn();
const numAttachments = 1;
const attachmentsMetadata = generateAttachmentsMetadata(numAttachments, 'txt', 'text/plain');
const mocks = await mockAttachmentThumbnailsAPICalls(attachmentsMetadata, fromKeys);
await setup(attachmentsMetadata, numAttachments);
const item = screen.getByTestId('attachment-thumbnail');
fireEvent.click(item);
await tick();
expect(mocks[0].attachmentSpy).toHaveBeenCalled();
expect(mocks[0].attachmentMetadataSpy).toHaveBeenCalled();
const preview = screen.getByTestId('file-preview');
expect(preview?.textContent).toMatch(new RegExp(attachmentsMetadata[0].Name));
// File content is visible
expect(preview?.textContent).toMatch(new RegExp(fileContent));
});
it('should be possible to switch between attachments when Redux state is filled', async () => {
window.URL.createObjectURL = jest.fn();
const numAttachments = 2;
const attachmentsMetadata = generateAttachmentsMetadata(numAttachments, 'txt', 'text/plain');
const { attachment: attachment1 } = await createAttachment(
{
ID: attachmentsMetadata[0].ID,
Name: attachmentsMetadata[0].Name,
MIMEType: attachmentsMetadata[0].MIMEType,
data: new Uint8Array(),
},
fromKeys.publicKeys
);
const { attachment: attachment2 } = await createAttachment(
{
ID: attachmentsMetadata[1].ID,
Name: attachmentsMetadata[1].Name,
MIMEType: attachmentsMetadata[1].MIMEType,
data: new Uint8Array(),
},
fromKeys.publicKeys
);
store.dispatch(
addAttachment({
ID: attachment1.ID as string,
attachment: {
data: attachment1.data,
} as WorkerDecryptionResult<Uint8Array>,
})
);
store.dispatch(
addAttachment({
ID: attachment2.ID as string,
attachment: {
data: attachment2.data,
} as WorkerDecryptionResult<Uint8Array>,
})
);
await setup(attachmentsMetadata, numAttachments);
const item = screen.getAllByTestId('attachment-thumbnail');
// Preview first item
fireEvent.click(item[0]);
await tick();
const preview = screen.getByTestId('file-preview');
expect(preview?.textContent).toMatch(new RegExp(attachmentsMetadata[0].Name));
// Switch to next item
const nextButton = screen.getByTestId('file-preview:navigation:next');
fireEvent.click(nextButton);
await tick();
expect(preview?.textContent).toMatch(new RegExp(attachmentsMetadata[1].Name));
});
it('should show a message instead of preview when attachment decryption failed', async () => {
window.URL.createObjectURL = jest.fn();
const numAttachments = 1;
const attachmentsMetadata = generateAttachmentsMetadata(numAttachments, 'txt', 'text/plain');
const mocks = await mockAttachmentThumbnailsAPICalls(attachmentsMetadata, fromKeys, true);
await setup(attachmentsMetadata, numAttachments);
const item = screen.getByTestId('attachment-thumbnail');
fireEvent.click(item);
await tick();
expect(mocks[0].attachmentSpy).toHaveBeenCalled();
expect(mocks[0].attachmentMetadataSpy).toHaveBeenCalled();
const preview = screen.getByTestId('file-preview');
expect(preview?.textContent).toMatch(new RegExp(attachmentsMetadata[0].Name));
// File preview cannot be displayed because decryption failed
expect(preview?.textContent).toMatch(new RegExp('Preview for this file type is not supported'));
});
it('should be possible to switch between attachments when not present in Redux state', async () => {
window.URL.createObjectURL = jest.fn();
const numAttachments = 2;
const attachmentsMetadata = generateAttachmentsMetadata(numAttachments, 'txt', 'text/plain');
const mocks = await mockAttachmentThumbnailsAPICalls(attachmentsMetadata, fromKeys);
await setup(attachmentsMetadata, numAttachments);
const item = screen.getAllByTestId('attachment-thumbnail');
// Preview first item
fireEvent.click(item[0]);
await tick();
expect(mocks[0].attachmentSpy).toHaveBeenCalled();
expect(mocks[0].attachmentMetadataSpy).toHaveBeenCalled();
const preview = screen.getByTestId('file-preview');
expect(preview?.textContent).toMatch(new RegExp(attachmentsMetadata[0].Name));
// Switch to next item
const nextButton = screen.getByTestId('file-preview:navigation:next');
fireEvent.click(nextButton);
await tick();
expect(mocks[1].attachmentSpy).toHaveBeenCalled();
expect(mocks[1].attachmentMetadataSpy).toHaveBeenCalled();
expect(preview?.textContent).toMatch(new RegExp(attachmentsMetadata[1].Name));
});
it('should download the attachment', async () => {
window.URL.createObjectURL = jest.fn();
const numAttachments = 1;
const attachmentsMetadata = generateAttachmentsMetadata(numAttachments, 'txt', 'text/plain');
const { attachment } = await createAttachment(
{
ID: attachmentsMetadata[0].ID,
Name: attachmentsMetadata[0].Name,
MIMEType: attachmentsMetadata[0].MIMEType,
data: new Uint8Array(),
},
fromKeys.publicKeys
);
store.dispatch(
addAttachment({
ID: attachment.ID as string,
attachment: {
data: attachment.data,
} as WorkerDecryptionResult<Uint8Array>,
})
);
await setup(attachmentsMetadata, numAttachments);
const item = screen.getByTestId('attachment-thumbnail');
fireEvent.click(item);
await tick();
const preview = screen.getByTestId('file-preview');
expect(preview?.textContent).toMatch(new RegExp(attachmentsMetadata[0].Name));
const downloadButton = screen.getByTestId('file-preview:actions:download');
fireEvent.click(downloadButton);
await tick();
expect(downloadFile).toHaveBeenCalled();
});
it('should download a pgp attachment when decryption failed', async () => {
window.URL.createObjectURL = jest.fn();
const numAttachments = 1;
const attachmentsMetadata = generateAttachmentsMetadata(numAttachments, 'txt', 'text/plain');
const mocks = await mockAttachmentThumbnailsAPICalls(attachmentsMetadata, fromKeys, true);
await setup(attachmentsMetadata, numAttachments);
const item = screen.getByTestId('attachment-thumbnail');
fireEvent.click(item);
await tick();
expect(mocks[0].attachmentSpy).toHaveBeenCalled();
expect(mocks[0].attachmentMetadataSpy).toHaveBeenCalled();
const preview = screen.getByTestId('file-preview');
expect(preview?.textContent).toMatch(new RegExp(attachmentsMetadata[0].Name));
// File preview cannot be displayed because decryption failed
expect(preview?.textContent).toMatch(new RegExp('Preview for this file type is not supported'));
// Download the encrypted attachment
const downloadButton = screen.getByTestId('file-preview:actions:download');
fireEvent.click(downloadButton);
await tick();
const blob = new Blob([mocks[0].attachmentPackets.data], {
type: 'application/pgp-encrypted',
});
expect(downloadFile).toHaveBeenCalledWith(blob, 'Attachment-0.txt.pgp');
});
});
|
3,515 | 0 | petrpan-code/ProtonMail/WebClients/applications/mail/src/app/components | petrpan-code/ProtonMail/WebClients/applications/mail/src/app/components/list/ItemDate.test.tsx | import { render } from '../../helpers/test/render';
import { Conversation } from '../../models/conversation';
import { Element } from '../../models/element';
import ItemDate from './ItemDate';
const element = {
ID: 'elementID',
Time: 1672531200,
} as Element;
const snoozedElement = {
ID: 'elementID',
Time: 1672531200,
Labels: [
{
ID: '16',
ContextSnoozeTime: 1704067200,
},
],
} as Conversation;
describe('ItemDate', () => {
it('Should display regular date with simple mode', async () => {
const { getByTestId } = await render(<ItemDate element={element} labelID="1" />);
expect(getByTestId('item-date-simple'));
});
it('Should display regular date with distance mode', async () => {
const { getByTestId } = await render(<ItemDate element={element} labelID="1" mode="distance" />);
expect(getByTestId('item-date-distance'));
});
it('Should display the snooze time when snooze time and in list view while in snooze folder', async () => {
const { getByTestId } = await render(<ItemDate element={snoozedElement} labelID="16" isInListView />);
expect(getByTestId('item-date-snoozed'));
});
it('Should not display the snooze time when snooze time and in list view and in inbox', async () => {
const { queryByTestId } = await render(<ItemDate element={snoozedElement} labelID="0" isInListView />);
expect(queryByTestId('item-date-snoozed')).toBeNull();
});
it('Should display regular date with simple mode when not in list', async () => {
const { getByTestId } = await render(<ItemDate element={snoozedElement} labelID="1" />);
expect(getByTestId('item-date-simple'));
});
it('Should display regular date with distance mode when not in list', async () => {
const { getByTestId } = await render(<ItemDate element={snoozedElement} labelID="1" mode="distance" />);
expect(getByTestId('item-date-distance'));
});
});
|
3,519 | 0 | petrpan-code/ProtonMail/WebClients/applications/mail/src/app/components | petrpan-code/ProtonMail/WebClients/applications/mail/src/app/components/list/ItemDateSnoozedMessage.test.tsx | import { render } from '@testing-library/react';
import { addDays, addYears, getUnixTime } from 'date-fns';
import { MAILBOX_LABEL_IDS } from '@proton/shared/lib/constants';
import { Message } from '@proton/shared/lib/interfaces/mail/Message';
import { formatFullDate, formatScheduledTimeString } from '../../helpers/date';
import { Conversation } from '../../models/conversation';
import ItemDateSnoozedMessage from './ItemDateSnoozedMessage';
const snoozedMessage = {
ID: '1',
ConversationID: '1',
SnoozeTime: 1672531200,
} as Message;
const remindedConversation = {
ID: '1',
DisplaySnoozedReminder: true,
} as Conversation;
describe('ItemDateSnoozedMessage', () => {
it('Should display the snooze time when user is in Snooze folder', () => {
const { getByTestId } = render(
<ItemDateSnoozedMessage
snoozeTime={snoozedMessage.SnoozeTime}
element={snoozedMessage}
labelID={MAILBOX_LABEL_IDS.SNOOZED}
useTooltip={false}
/>
);
expect(getByTestId('item-date-snoozed'));
});
it('Should display today when the snooze time is today', () => {
const today = new Date();
const formattedDate = formatScheduledTimeString(today);
const snoozeTime = getUnixTime(today);
const { getByText } = render(
<ItemDateSnoozedMessage
snoozeTime={snoozeTime}
element={{ ...snoozedMessage, SnoozeTime: snoozeTime }}
labelID={MAILBOX_LABEL_IDS.SNOOZED}
useTooltip={false}
/>
);
expect(getByText(`${formattedDate}`));
});
it('Should display tomorrow when the snooze time is tomorrow', () => {
const tomorrow = addDays(new Date(), 1);
const formattedDate = formatScheduledTimeString(tomorrow);
const snoozeTime = getUnixTime(tomorrow);
const { getByText } = render(
<ItemDateSnoozedMessage
snoozeTime={snoozeTime}
element={{ ...snoozedMessage, SnoozeTime: snoozeTime }}
labelID={MAILBOX_LABEL_IDS.SNOOZED}
useTooltip={false}
/>
);
expect(getByText(`Tomorrow, ${formattedDate}`));
});
it('Should display the full date when the snooze time is not today or tomorrow', () => {
const date = addYears(new Date(), 1);
const formattedDate = formatFullDate(date);
const snoozeTime = getUnixTime(date);
const { getByText } = render(
<ItemDateSnoozedMessage
snoozeTime={snoozeTime}
element={{ ...snoozedMessage, SnoozeTime: snoozeTime }}
labelID={MAILBOX_LABEL_IDS.SNOOZED}
useTooltip={false}
/>
);
expect(getByText(formattedDate));
});
it('Should not display the snooze time when user is in Inbox folder', () => {
const { queryByTestId } = render(
<ItemDateSnoozedMessage
snoozeTime={snoozedMessage.SnoozeTime}
element={snoozedMessage}
labelID={MAILBOX_LABEL_IDS.INBOX}
useTooltip={false}
/>
);
expect(queryByTestId('item-date-snooze')).toBeNull();
});
it('Should display reminded when message is a reminded conversation and user is in Inbox folder', () => {
const { getByTestId } = render(
<ItemDateSnoozedMessage
snoozeTime={snoozedMessage.SnoozeTime}
element={remindedConversation}
labelID={MAILBOX_LABEL_IDS.INBOX}
useTooltip={false}
/>
);
expect(getByTestId('item-date-reminded'));
});
it('Should not display reminded when message is a not a reminded conversation and user is in Inbox folder', () => {
const { queryByTestId } = render(
<ItemDateSnoozedMessage
snoozeTime={snoozedMessage.SnoozeTime}
element={{ ...remindedConversation, DisplaySnoozedReminder: false }}
labelID={MAILBOX_LABEL_IDS.INBOX}
useTooltip={false}
/>
);
expect(queryByTestId('item-date-reminded')).toBeNull();
});
});
|
3,530 | 0 | petrpan-code/ProtonMail/WebClients/applications/mail/src/app/components | petrpan-code/ProtonMail/WebClients/applications/mail/src/app/components/list/ListBanners.test.tsx | import { render, screen, waitFor } from '@testing-library/react';
import userEvent from '@testing-library/user-event';
import { DENSITY, MAILBOX_LABEL_IDS } from '@proton/shared/lib/constants';
import { UserSettings } from '@proton/shared/lib/interfaces';
import { mockUseApi, mockUseEventManager, mockUseHistory, mockUseSelector, mockUseUser } from '@proton/testing/index';
import { mockUseEncryptedSearchContext } from 'proton-mail/helpers/test/mockUseEncryptedSearchContext';
import ListBanners from './ListBanners';
import { mockUseAutoDeleteBanner, mockUseShowUpsellBanner } from './ListBanners.test.utils';
const baseProps = {
labelID: MAILBOX_LABEL_IDS.INBOX,
columnLayout: false,
userSettings: { Density: DENSITY.COMFORTABLE } as UserSettings,
esState: {
isESLoading: false,
isSearch: false,
showESSlowToolbar: false,
},
};
describe('ListBanners', () => {
beforeEach(() => {
mockUseEncryptedSearchContext();
mockUseAutoDeleteBanner();
mockUseSelector();
mockUseShowUpsellBanner();
mockUseUser();
});
it('should display no banner', () => {
const { container } = render(<ListBanners {...baseProps} />);
expect(container).toBeEmptyDOMElement();
});
describe('when showESSlowToolbar is true', () => {
let mockedOpenDropdown = jest.fn();
let mockedSetTemporaryToggleOff = jest.fn();
beforeEach(() => {
mockUseEncryptedSearchContext({
openDropdown: mockedOpenDropdown,
setTemporaryToggleOff: mockedSetTemporaryToggleOff,
});
});
it('should display es slow banner', async () => {
render(
<ListBanners
{...baseProps}
esState={{
isESLoading: false,
isSearch: false,
showESSlowToolbar: true,
}}
/>
);
expect(screen.getByText(/Search taking too long\?/i)).toBeInTheDocument();
const refineButton = screen.getByRole('button', { name: /Refine it/ });
await userEvent.click(refineButton);
await waitFor(() => {
expect(mockedOpenDropdown).toHaveBeenCalledTimes(1);
});
const excludeButton = screen.getByRole('button', { name: /exclude message content/ });
await userEvent.click(excludeButton);
await waitFor(() => {
expect(mockedSetTemporaryToggleOff).toHaveBeenCalledTimes(1);
});
expect(screen.getByText(/from this search session./i)).toBeInTheDocument();
});
});
describe('when user is in almost all mail and using es', () => {
const mockedPush = jest.fn();
beforeEach(() => {
mockUseHistory({ push: mockedPush });
});
it('should display almost all mail banner', async () => {
render(
<ListBanners
{...baseProps}
labelID={MAILBOX_LABEL_IDS.ALMOST_ALL_MAIL}
esState={{
isESLoading: false,
isSearch: false,
showESSlowToolbar: false,
}}
/>
);
expect(screen.getByText(/Can't find what you're looking for\?/i)).toBeInTheDocument();
const includeButton = screen.getByRole('button', { name: /Include Spam\/Trash/i });
await userEvent.click(includeButton);
await waitFor(() => {
expect(mockedPush).toHaveBeenCalledTimes(1);
});
expect(mockedPush).toHaveBeenCalledWith('/all-mail');
});
});
describe('when canDisplayUpsellBanner is true', () => {
beforeEach(() => {
mockUseShowUpsellBanner({ canDisplayUpsellBanner: true });
jest.spyOn(global.Math, 'random').mockReturnValue(0.349);
});
it('should render upsell banner', () => {
render(<ListBanners {...baseProps} />);
expect(screen.getByText(/Use keyboard shortcuts to manage your email faster./i)).toBeInTheDocument();
expect(screen.getByText(/Learn more/i)).toBeInTheDocument();
});
});
describe('when canDisplayTaskRunningBanner is true', () => {
it('should display task running banner', async () => {
mockUseSelector(true);
render(<ListBanners {...baseProps} />);
expect(screen.getByText(/Moving messages. This may take a while./i)).toBeInTheDocument();
});
});
describe('when condition for auto delete is true', () => {
beforeEach(() => {
mockUseApi();
mockUseEventManager();
mockUseAutoDeleteBanner('paid-banner');
});
it('should display auto delete banner', async () => {
render(<ListBanners {...baseProps} labelID={MAILBOX_LABEL_IDS.TRASH} />);
expect(
screen.getByText(
/Automatically delete messages that have been in trash and spam for more than 30 days./i
)
).toBeInTheDocument();
});
});
});
|
3,537 | 0 | petrpan-code/ProtonMail/WebClients/applications/mail/src/app/components | petrpan-code/ProtonMail/WebClients/applications/mail/src/app/components/list/useScrollToTop.test.ts | import { useState } from 'react';
import { renderHook } from '@testing-library/react-hooks';
import useScrollToTop from './useScrollToTop';
describe('useScrollToTop', () => {
it('should scroll to top', () => {
renderHook(() => {
const ref = { current: { scrollTop: 10 } } as React.RefObject<HTMLElement>;
useScrollToTop(ref, []);
if (!ref.current) {
throw new Error('ref.current is undefined');
}
expect(ref.current.scrollTop).toBe(0);
});
});
it('should scroll to top if dependencies are changing', () => {
renderHook(() => {
const ref = { current: { scrollTop: 10 } } as React.RefObject<HTMLElement>;
const [dependencies, setDependencies] = useState([1]);
if (!ref.current) {
throw new Error('ref.current is undefined');
}
useScrollToTop(ref, dependencies);
expect(ref.current.scrollTop).toBe(0);
ref.current.scrollTop = 10;
expect(ref.current.scrollTop).toBe(10);
setDependencies([2]);
expect(ref.current.scrollTop).toBe(0);
});
});
});
|
3,540 | 0 | petrpan-code/ProtonMail/WebClients/applications/mail/src/app/components/list/banners | petrpan-code/ProtonMail/WebClients/applications/mail/src/app/components/list/banners/almost-all-mail/AlmostAllMailBanner.test.tsx | import { render, screen, waitFor } from '@testing-library/react';
import userEvent from '@testing-library/user-event';
import { MAILBOX_LABEL_IDS } from '@proton/shared/lib/constants';
import { mockUseHistory } from '@proton/testing/index';
import { getHumanLabelID } from 'proton-mail/helpers/labels';
import AlmostAllMailBanner from './AlmostAllMailBanner';
describe('AlmostAllMailBanner', () => {
beforeEach(() => {
mockUseHistory({
location: {
pathname: `/${getHumanLabelID(MAILBOX_LABEL_IDS.INBOX)}`,
search: '',
state: {},
hash: '',
},
});
});
describe('when use is in AlmostAllMail location', () => {
let mockedPush: jest.Mock;
beforeEach(() => {
mockedPush = jest.fn();
mockUseHistory({
push: mockedPush,
});
});
it('should render banner', () => {
render(<AlmostAllMailBanner />);
expect(screen.getByText("Can't find what you're looking for?")).toBeInTheDocument();
const button = screen.getByRole('button', { name: /Include Spam\/Trash/ });
expect(button).toBeInTheDocument();
});
describe('when user click on banner button', () => {
it('should push new route to history', async () => {
render(<AlmostAllMailBanner />);
const button = screen.getByRole('button', { name: /Include Spam\/Trash/ });
expect(button).toBeInTheDocument();
await userEvent.click(button);
await waitFor(() => {
expect(mockedPush).toHaveBeenCalledTimes(1);
});
expect(mockedPush).toHaveBeenCalledWith('/all-mail');
});
});
});
});
|
3,542 | 0 | petrpan-code/ProtonMail/WebClients/applications/mail/src/app/components/list/banners | petrpan-code/ProtonMail/WebClients/applications/mail/src/app/components/list/banners/auto-delete/AutoDeleteBanner.test.tsx | import { render, screen } from '@testing-library/react';
import AutoDeleteBanner from './AutoDeleteBanner';
describe('AutoDeleteBanner', () => {
describe('when bannerType is paid', () => {
it('should render correct banner', () => {
render(<AutoDeleteBanner bannerType="paid-banner" />);
expect(
screen.getByText(
/Automatically delete messages that have been in trash and spam for more than 30 days./i
)
).toBeInTheDocument();
});
});
describe('when bannerType is free', () => {
it('should render correct banner', () => {
render(<AutoDeleteBanner bannerType="free-banner" />);
expect(
screen.getByText(
/Upgrade to automatically delete messages that have been in trash and spam for more than 30 days./i
)
).toBeInTheDocument();
});
});
describe('when bannerType is enabled', () => {
it('should render correct banner', () => {
render(<AutoDeleteBanner bannerType="enabled" />);
expect(
screen.getByText(
/Messages that have been in trash and spam more than 30 days will be automatically deleted./i
)
).toBeInTheDocument();
});
});
});
|
3,544 | 0 | petrpan-code/ProtonMail/WebClients/applications/mail/src/app/components/list/banners | petrpan-code/ProtonMail/WebClients/applications/mail/src/app/components/list/banners/auto-delete/useAutoDeleteBanner.test.ts | import { renderHook } from '@testing-library/react-hooks';
import { MAILBOX_LABEL_IDS as IDS } from '@proton/shared/lib/constants';
import { mockUseFeature, mockUseMailSettings, mockUseUser } from '@proton/testing/index';
import { LABEL_IDS_TO_HUMAN as TO_HUMAN } from '../../../../constants';
import useAutoDeleteBanner from './useAutodeleteBanner';
describe('AutoDeleteBanner', () => {
beforeEach(() => {
mockUseFeature({ feature: { Value: true } as any });
mockUseUser();
mockUseMailSettings();
});
describe('when feature is not active', () => {
it('should not render when', async () => {
mockUseFeature({ feature: { Value: false } as any });
mockUseUser([{ isFree: true }]);
const { result } = await renderHook(() => useAutoDeleteBanner(IDS.SPAM));
expect(result.current).toBe('hide');
});
});
describe('when setting is deactivated and user is paid', () => {
it('should not render banner', async () => {
mockUseFeature({ feature: { Value: true } as any });
mockUseUser([{ isPaid: true }]);
const { result } = await renderHook(() => useAutoDeleteBanner(IDS.SPAM));
expect(result.current).toBe('disabled');
});
});
describe('user is not in enabled location', () => {
it.each`
labelID | labelName
${IDS.ALL_DRAFTS} | ${TO_HUMAN[IDS.ALL_DRAFTS] + ' label'}
${IDS.ALL_MAIL} | ${TO_HUMAN[IDS.ALL_MAIL] + ' label'}
${IDS.ALL_SENT} | ${TO_HUMAN[IDS.ALL_SENT] + ' label'}
${IDS.ALMOST_ALL_MAIL} | ${TO_HUMAN[IDS.ALMOST_ALL_MAIL] + ' label'}
${IDS.ARCHIVE} | ${TO_HUMAN[IDS.ARCHIVE] + ' label'}
${IDS.DRAFTS} | ${TO_HUMAN[IDS.DRAFTS] + ' label'}
${IDS.INBOX} | ${TO_HUMAN[IDS.INBOX] + ' label'}
${IDS.OUTBOX} | ${TO_HUMAN[IDS.OUTBOX] + ' label'}
${IDS.SCHEDULED} | ${TO_HUMAN[IDS.SCHEDULED] + ' label'}
${IDS.SENT} | ${TO_HUMAN[IDS.SENT] + ' label'}
${IDS.STARRED} | ${TO_HUMAN[IDS.STARRED] + ' label'}
${'qwdiwfsdas'} | ${'random folder or label id'}
`('should not render banner inside $labelName', async ({ labelID }) => {
mockUseFeature({ feature: { Value: true } as any });
mockUseUser([{ isFree: true }]);
const { result } = await renderHook(() => useAutoDeleteBanner(labelID));
expect(result.current).toBe('hide');
});
});
describe('user is in enabled location', () => {
it.each`
labelID | labelName
${IDS.SPAM} | ${TO_HUMAN[IDS.SPAM]}
${IDS.TRASH} | ${TO_HUMAN[IDS.TRASH]}
`('should render banner inside $labelName', async ({ labelID }) => {
mockUseFeature({ feature: { Value: true } as any });
mockUseUser([{ hasPaidMail: false, isFree: true }]);
const { result } = await renderHook(() => useAutoDeleteBanner(labelID));
expect(result.current).toBe('free-banner');
});
});
describe('When user is free', () => {
const isFree = true;
describe('Setting is null', () => {
it('Should rneder free banner', async () => {
mockUseFeature({ feature: { Value: true } as any });
mockUseUser([{ hasPaidMail: !isFree, isFree }]);
const { result } = await renderHook(() => useAutoDeleteBanner(IDS.SPAM));
expect(result.current).toBe('free-banner');
});
});
describe('Setting is enabled (API should not allow this case)', () => {
it('should rneder free banner', async () => {
mockUseFeature({ feature: { Value: true } as any });
mockUseUser([{ hasPaidMail: !isFree, isFree }]);
mockUseMailSettings([{ AutoDeleteSpamAndTrashDays: 30 }]);
const { result } = await renderHook(() => useAutoDeleteBanner(IDS.SPAM));
expect(result.current).toBe('free-banner');
});
});
describe('Setting is explicitly deactivated (API should not allow this case)', () => {
it('Should rneder free banner', async () => {
mockUseFeature({ feature: { Value: true } as any });
mockUseUser([{ hasPaidMail: !isFree, isFree }]);
mockUseMailSettings([{ AutoDeleteSpamAndTrashDays: 0 }]);
const { result } = await renderHook(() => useAutoDeleteBanner(IDS.SPAM));
expect(result.current).toBe('free-banner');
});
});
});
describe('User is paid', () => {
const isFree = false;
describe('Setting is null and user is paid', () => {
it('Should render paid banner', async () => {
mockUseFeature({ feature: { Value: true } as any });
mockUseUser([{ hasPaidMail: !isFree, isFree }]);
mockUseMailSettings([{ AutoDeleteSpamAndTrashDays: null }]);
const { result } = await renderHook(() => useAutoDeleteBanner(IDS.SPAM));
expect(result.current).toBe('paid-banner');
});
});
describe('Setting is enabled and user is paid', () => {
it('Should render enabled banner', async () => {
mockUseUser([{ hasPaidMail: !isFree, isFree }]);
mockUseFeature({ feature: { Value: true } as any });
mockUseMailSettings([{ AutoDeleteSpamAndTrashDays: 30 }]);
const { result } = await renderHook(() => useAutoDeleteBanner(IDS.SPAM));
expect(result.current).toBe('enabled');
});
});
});
});
|
3,550 | 0 | petrpan-code/ProtonMail/WebClients/applications/mail/src/app/components/list/banners | petrpan-code/ProtonMail/WebClients/applications/mail/src/app/components/list/banners/mail-upsell/MailUpsellBanner.test.tsx | import { screen } from '@testing-library/react';
import { removeItem, setItem } from '@proton/shared/lib/helpers/storage';
import range from '@proton/utils/range';
import { render } from '../../../../helpers/test/render';
import MailUpsellBanner from './MailUpsellBanner';
const props = {
columnMode: true,
needToShowUpsellBanner: { current: true },
onClose: jest.fn(),
};
describe('Mail upsell banner', () => {
afterAll(() => {
removeItem('WelcomePaneEncounteredMessages');
});
it('should display a banner', async () => {
await render(<MailUpsellBanner {...props} />);
screen.getByTestId('promotion-banner');
});
it('should display the expected banner', async () => {
// Fake localStorage so that we can predict which banner will be displayed
// Added more ids in the array (1 to 100) in case we add more banners in the future
// Here we expect to see the banner with the id "2"
setItem('WelcomePaneEncounteredMessages', JSON.stringify([0, 1, ...range(3, 100)]));
await render(<MailUpsellBanner {...props} />);
screen.getByText('Upgrade to send email from @pm.me addresses.');
});
});
|
3,554 | 0 | petrpan-code/ProtonMail/WebClients/applications/mail/src/app/components/list | petrpan-code/ProtonMail/WebClients/applications/mail/src/app/components/list/item-expiration/ItemExpiration.test.tsx | import { screen } from '@testing-library/react';
import { addDays, addHours, addMinutes, getUnixTime } from 'date-fns';
import { MAILBOX_LABEL_IDS } from '@proton/shared/lib/constants';
import { MessageMetadata } from '@proton/shared/lib/interfaces/mail/Message';
import { AUTO_DELETE_SPAM_AND_TRASH_DAYS } from '@proton/shared/lib/mail/mailSettings';
import { addToCache } from '@proton/testing/index';
import { minimalCache } from '../../../helpers/test/cache';
import { render } from '../../../helpers/test/render';
import { Element } from '../../../models/element';
import ItemExpiration from './ItemExpiration';
const defaultLabelID = MAILBOX_LABEL_IDS.INBOX;
const getElement = (type: 'message' | 'conversation' = 'conversation', elementProps?: Partial<Element>) => {
const element =
type === 'message'
? ({
// We consider an element as a message if it has conversationID
ConversationID: '',
...elementProps,
} as MessageMetadata)
: ({ ...elementProps } as Element);
return element;
};
describe('ItemExpiration', () => {
it('should not render if expirationTime is not provided', async () => {
await render(<ItemExpiration labelID={defaultLabelID} element={getElement()} />);
expect(screen.queryByTestId('item-expiration')).not.toBeInTheDocument();
});
it('should have color-danger class if it is expiring in less than a day', async () => {
const date = addHours(new Date(), 1);
const expirationTime = getUnixTime(date);
await render(
<ItemExpiration labelID={defaultLabelID} element={getElement()} expirationTime={expirationTime} />
);
expect(screen.getByTestId('item-expiration')).toHaveClass('color-danger');
});
it('should not have color-danger class if it is expiring in more than a day', async () => {
const date = addHours(new Date(), 25);
const expirationTime = getUnixTime(date);
await render(
<ItemExpiration labelID={defaultLabelID} element={getElement()} expirationTime={expirationTime} />
);
expect(screen.getByTestId('item-expiration')).not.toHaveClass('color-danger');
});
it('should show a short remaining time', async () => {
const date = addMinutes(new Date(), 10);
const expirationTime = getUnixTime(date);
await render(
<ItemExpiration labelID={defaultLabelID} element={getElement()} expirationTime={expirationTime} />
);
expect(screen.getByText('<1 d')).toBeInTheDocument();
});
it('should diplay 30 days', async () => {
const date = addDays(new Date(), 30);
const expirationTime = getUnixTime(date);
await render(
<ItemExpiration labelID={defaultLabelID} element={getElement()} expirationTime={expirationTime} />
);
expect(screen.getByText('30 d')).toBeInTheDocument();
});
describe('Element is conversation', () => {
it('Should display Trash icon when label ID is valid and setting is not null', async () => {
const expirationTime = getUnixTime(addDays(new Date(), 30));
minimalCache();
addToCache('MailSettings', { AutoDeleteSpamAndTrashDays: AUTO_DELETE_SPAM_AND_TRASH_DAYS.ACTIVE });
await render(
<ItemExpiration
element={getElement()}
expirationTime={expirationTime}
labelID={MAILBOX_LABEL_IDS.TRASH}
/>,
false
);
expect(screen.getByTestId('item-expiration').querySelector('use')?.getAttribute('xlink:href')).toBe(
'#ic-trash-clock'
);
});
it('Should display Hourglass if label ID is not valid', async () => {
const expirationTime = getUnixTime(addDays(new Date(), 30));
minimalCache();
addToCache('MailSettings', { AutoDeleteSpamAndTrashDays: AUTO_DELETE_SPAM_AND_TRASH_DAYS.ACTIVE });
await render(
<ItemExpiration
labelID={MAILBOX_LABEL_IDS.INBOX}
element={getElement()}
expirationTime={expirationTime}
/>,
false
);
expect(screen.getByTestId('item-expiration').querySelector('use')?.getAttribute('xlink:href')).toBe(
'#ic-hourglass'
);
});
it('Should display Hourglass icon if label ID is valid and setting is null', async () => {
const expirationTime = getUnixTime(addDays(new Date(), 30));
minimalCache();
addToCache('MailSettings', { AutoDeleteSpamAndTrashDays: null });
await render(
<ItemExpiration
labelID={MAILBOX_LABEL_IDS.TRASH}
element={getElement()}
expirationTime={expirationTime}
/>,
false
);
expect(screen.getByTestId('item-expiration').querySelector('use')?.getAttribute('xlink:href')).toBe(
'#ic-hourglass'
);
});
});
describe('Element is message', () => {
it('Should display Trash icon if expire flag is not frozen', async () => {
const expirationTime = getUnixTime(addDays(new Date(), 30));
minimalCache();
addToCache('MailSettings', { AutoDeleteSpamAndTrashDays: AUTO_DELETE_SPAM_AND_TRASH_DAYS.ACTIVE });
await render(
<ItemExpiration
labelID={MAILBOX_LABEL_IDS.TRASH}
element={getElement('message')}
expirationTime={expirationTime}
/>,
false
);
expect(screen.getByTestId('item-expiration').querySelector('use')?.getAttribute('xlink:href')).toBe(
'#ic-trash-clock'
);
});
});
});
|
3,559 | 0 | petrpan-code/ProtonMail/WebClients/applications/mail/src/app/components/list/snooze | petrpan-code/ProtonMail/WebClients/applications/mail/src/app/components/list/snooze/components/SnoozeDurationSelection.test.tsx | import { render } from '@testing-library/react';
import { nextFriday, nextMonday, nextSaturday, nextSunday, nextThursday, nextTuesday, nextWednesday } from 'date-fns';
import { useUser, useUserSettings } from '@proton/components/hooks';
import { MAIL_APP_NAME } from '@proton/shared/lib/constants';
import { SETTINGS_WEEK_START } from '@proton/shared/lib/interfaces';
import SnoozeDurationSelection from './SnoozeDurationSelection';
jest.mock('@proton/components/hooks/useUser');
jest.mock('@proton/components/hooks/useUserSettings');
const renderComponent = (canUnsnooze: boolean) => {
return render(
<SnoozeDurationSelection
canUnsnooze={canUnsnooze}
handleCustomClick={jest.fn}
handleSnooze={jest.fn}
handleUnsnoozeClick={jest.fn}
/>
);
};
describe('SnoozeDurationSelection when start of week is Monday', () => {
const useUserMock = useUser as jest.Mock;
const useUserSettingsMock = useUserSettings as jest.Mock;
beforeAll(() => {
useUserMock.mockImplementation(() => [{ hasPaidMail: false }, jest.fn]);
useUserSettingsMock.mockImplementation(() => [{ WeekStart: 1 }]);
});
afterAll(() => {
useUserMock.mockReset();
useUserSettingsMock.mockReset();
});
it('should render all Monday options', () => {
const date = nextMonday(new Date());
jest.useFakeTimers({ now: date.getTime() });
const { getByTestId } = renderComponent(false);
expect(getByTestId('snooze-duration-tomorrow'));
expect(getByTestId('snooze-duration-later'));
expect(getByTestId('snooze-duration-weekend'));
expect(getByTestId('snooze-duration-nextweek'));
expect(getByTestId('snooze-duration-custom'));
});
it('should render all Tuesday options', () => {
const date = nextTuesday(new Date());
jest.useFakeTimers({ now: date.getTime() });
const { getByTestId } = renderComponent(false);
expect(getByTestId('snooze-duration-tomorrow'));
expect(getByTestId('snooze-duration-later'));
expect(getByTestId('snooze-duration-weekend'));
expect(getByTestId('snooze-duration-nextweek'));
expect(getByTestId('snooze-duration-custom'));
});
it('should render all Wednesday options', () => {
const date = nextWednesday(new Date());
jest.useFakeTimers({ now: date.getTime() });
const { getByTestId } = renderComponent(false);
expect(getByTestId('snooze-duration-tomorrow'));
expect(getByTestId('snooze-duration-later'));
expect(getByTestId('snooze-duration-weekend'));
expect(getByTestId('snooze-duration-nextweek'));
expect(getByTestId('snooze-duration-custom'));
});
it('should render all Thursday options', () => {
const date = nextThursday(new Date());
jest.useFakeTimers({ now: date.getTime() });
const { getByTestId, queryByTestId } = renderComponent(false);
expect(getByTestId('snooze-duration-tomorrow'));
expect(queryByTestId('snooze-duration-later')).toBeNull();
expect(getByTestId('snooze-duration-weekend'));
expect(getByTestId('snooze-duration-nextweek'));
expect(getByTestId('snooze-duration-custom'));
});
it('should render all Friday options', () => {
const date = nextFriday(new Date());
jest.useFakeTimers({ now: date.getTime() });
const { getByTestId, queryByTestId } = renderComponent(false);
expect(getByTestId('snooze-duration-tomorrow'));
expect(getByTestId('snooze-duration-later'));
expect(queryByTestId('snooze-duration-weekend')).toBeNull();
expect(getByTestId('snooze-duration-nextweek'));
expect(getByTestId('snooze-duration-custom'));
});
it('should render all Saturday options', () => {
const date = nextSaturday(new Date());
jest.useFakeTimers({ now: date.getTime() });
const { getByTestId, queryByTestId } = renderComponent(false);
expect(getByTestId('snooze-duration-tomorrow'));
expect(queryByTestId('snooze-duration-later')).toBeNull();
expect(queryByTestId('snooze-duration-weekend')).toBeNull();
expect(getByTestId('snooze-duration-nextweek'));
expect(getByTestId('snooze-duration-custom'));
});
it('should render all Sunday options', () => {
const date = nextSunday(new Date());
jest.useFakeTimers({ now: date.getTime() });
const { getByTestId, queryByTestId } = renderComponent(false);
expect(getByTestId('snooze-duration-tomorrow'));
expect(queryByTestId('snooze-duration-later')).toBeNull();
expect(queryByTestId('snooze-duration-weekend')).toBeNull();
expect(queryByTestId('snooze-duration-nextweek')).toBeNull();
expect(getByTestId('snooze-duration-custom'));
});
it('should render the unsnooze option', () => {
const { getByTestId } = renderComponent(true);
expect(getByTestId('snooze-duration-unsnooze'));
});
it('should render the upsell button for free users', () => {
const { getByAltText } = renderComponent(false);
expect(getByAltText(`Upgrade to ${MAIL_APP_NAME} Plus to unlock`));
});
it('should not render the upsell button for free users', () => {
useUserMock.mockImplementation(() => [{ hasPaidMail: true }, jest.fn]);
const { queryByAltText } = renderComponent(false);
expect(queryByAltText(`Upgrade to ${MAIL_APP_NAME} Plus to unlock`)).toBeNull();
});
});
describe('SnoozeDurationSelection when start of week is Saturday', () => {
const useUserMock = useUser as jest.Mock;
const useUserSettingsMock = useUserSettings as jest.Mock;
beforeAll(() => {
useUserMock.mockImplementation(() => [{ hasPaidMail: false }, jest.fn]);
useUserSettingsMock.mockImplementation(() => [{ WeekStart: SETTINGS_WEEK_START.SATURDAY }]);
});
afterAll(() => {
useUserMock.mockReset();
useUserSettingsMock.mockReset();
});
it('should render all Monday options', () => {
const date = nextMonday(new Date());
jest.useFakeTimers({ now: date.getTime() });
const { getByTestId, queryByTestId } = renderComponent(false);
expect(getByTestId('snooze-duration-tomorrow'));
expect(getByTestId('snooze-duration-later'));
expect(queryByTestId('snooze-duration-weekend')).toBeNull();
expect(getByTestId('snooze-duration-nextweek'));
});
it('should render all Tuesday options', () => {
const date = nextTuesday(new Date());
jest.useFakeTimers({ now: date.getTime() });
const { getByTestId, queryByTestId } = renderComponent(false);
expect(getByTestId('snooze-duration-tomorrow'));
expect(getByTestId('snooze-duration-later'));
expect(queryByTestId('snooze-duration-weekend')).toBeNull();
expect(getByTestId('snooze-duration-nextweek'));
});
it('should render all Wednesday options', () => {
const date = nextWednesday(new Date());
jest.useFakeTimers({ now: date.getTime() });
const { getByTestId, queryByTestId } = renderComponent(false);
expect(getByTestId('snooze-duration-tomorrow'));
expect(getByTestId('snooze-duration-later'));
expect(queryByTestId('snooze-duration-weekend')).toBeNull();
expect(getByTestId('snooze-duration-nextweek'));
expect(getByTestId('snooze-duration-custom'));
});
it('should render all Thursday options', () => {
const date = nextThursday(new Date());
jest.useFakeTimers({ now: date.getTime() });
const { getByTestId, queryByTestId } = renderComponent(false);
expect(getByTestId('snooze-duration-tomorrow'));
expect(queryByTestId('snooze-duration-later')).toBeNull();
expect(queryByTestId('snooze-duration-weekend')).toBeNull();
expect(getByTestId('snooze-duration-nextweek'));
expect(getByTestId('snooze-duration-custom'));
});
it('should render all Friday options', () => {
const date = nextFriday(new Date());
jest.useFakeTimers({ now: date.getTime() });
const { getByTestId, queryByTestId } = renderComponent(false);
expect(getByTestId('snooze-duration-tomorrow'));
expect(getByTestId('snooze-duration-later'));
expect(queryByTestId('snooze-duration-nextweek'));
expect(getByTestId('snooze-duration-nextweek'));
expect(getByTestId('snooze-duration-custom'));
});
it('should render all Saturday options', () => {
const date = nextSaturday(new Date());
jest.useFakeTimers({ now: date.getTime() });
const { getByTestId, queryByTestId } = renderComponent(false);
expect(getByTestId('snooze-duration-tomorrow'));
expect(queryByTestId('snooze-duration-later')).toBeNull();
expect(getByTestId('snooze-duration-nextweek'));
expect(getByTestId('snooze-duration-nextweek'));
expect(getByTestId('snooze-duration-custom'));
});
it('should render all Sunday options', () => {
const date = nextSunday(new Date());
jest.useFakeTimers({ now: date.getTime() });
const { getByTestId, queryByTestId } = renderComponent(false);
expect(getByTestId('snooze-duration-tomorrow'));
expect(queryByTestId('snooze-duration-later')).toBeNull();
expect(queryByTestId('snooze-duration-nextweek')).toBeNull();
expect(queryByTestId('snooze-duration-nextweek')).toBeNull();
expect(getByTestId('snooze-duration-custom'));
});
});
describe('SnoozeDurationSelection when start of week is Sunday', () => {
const useUserMock = useUser as jest.Mock;
const useUserSettingsMock = useUserSettings as jest.Mock;
beforeAll(() => {
useUserMock.mockImplementation(() => [{ hasPaidMail: false }, jest.fn]);
useUserSettingsMock.mockImplementation(() => [{ WeekStart: SETTINGS_WEEK_START.SUNDAY }]);
});
afterAll(() => {
useUserMock.mockReset();
useUserSettingsMock.mockReset();
});
it('should render all Monday options', () => {
const date = nextMonday(new Date());
jest.useFakeTimers({ now: date.getTime() });
const { getByTestId, queryByTestId } = renderComponent(false);
expect(getByTestId('snooze-duration-tomorrow'));
expect(getByTestId('snooze-duration-later'));
expect(queryByTestId('snooze-duration-weekend')).toBeNull();
expect(getByTestId('snooze-duration-nextweek'));
});
it('should render all Tuesday options', () => {
const date = nextTuesday(new Date());
jest.useFakeTimers({ now: date.getTime() });
const { getByTestId, queryByTestId } = renderComponent(false);
expect(getByTestId('snooze-duration-tomorrow'));
expect(getByTestId('snooze-duration-later'));
expect(queryByTestId('snooze-duration-weekend')).toBeNull();
expect(getByTestId('snooze-duration-nextweek'));
});
it('should render all Wednesday options', () => {
const date = nextWednesday(new Date());
jest.useFakeTimers({ now: date.getTime() });
const { getByTestId, queryByTestId } = renderComponent(false);
expect(getByTestId('snooze-duration-tomorrow'));
expect(getByTestId('snooze-duration-later'));
expect(queryByTestId('snooze-duration-weekend')).toBeNull();
expect(getByTestId('snooze-duration-nextweek'));
expect(getByTestId('snooze-duration-custom'));
});
it('should render all Thursday options', () => {
const date = nextThursday(new Date());
jest.useFakeTimers({ now: date.getTime() });
const { getByTestId, queryByTestId } = renderComponent(false);
expect(getByTestId('snooze-duration-tomorrow'));
expect(queryByTestId('snooze-duration-later')).toBeNull();
expect(queryByTestId('snooze-duration-weekend')).toBeNull();
expect(getByTestId('snooze-duration-nextweek'));
expect(getByTestId('snooze-duration-custom'));
});
it('should render all Friday options', () => {
const date = nextFriday(new Date());
jest.useFakeTimers({ now: date.getTime() });
const { getByTestId, queryByTestId } = renderComponent(false);
expect(getByTestId('snooze-duration-tomorrow'));
expect(getByTestId('snooze-duration-later'));
expect(queryByTestId('snooze-duration-nextweek'));
expect(getByTestId('snooze-duration-nextweek'));
expect(getByTestId('snooze-duration-custom'));
});
it('should render all Saturday options', () => {
const date = nextSaturday(new Date());
jest.useFakeTimers({ now: date.getTime() });
const { getByTestId, queryByTestId } = renderComponent(false);
expect(getByTestId('snooze-duration-tomorrow'));
expect(queryByTestId('snooze-duration-later')).toBeNull();
expect(getByTestId('snooze-duration-nextweek'));
expect(getByTestId('snooze-duration-nextweek'));
expect(getByTestId('snooze-duration-custom'));
});
it('should render all Sunday options', () => {
const date = nextSunday(new Date());
jest.useFakeTimers({ now: date.getTime() });
const { getByTestId, queryByTestId } = renderComponent(false);
expect(getByTestId('snooze-duration-tomorrow'));
expect(queryByTestId('snooze-duration-later')).toBeNull();
expect(queryByTestId('snooze-duration-nextweek')).toBeNull();
expect(queryByTestId('snooze-duration-nextweek')).toBeNull();
expect(getByTestId('snooze-duration-custom'));
});
});
|
3,564 | 0 | petrpan-code/ProtonMail/WebClients/applications/mail/src/app/components/list/snooze | petrpan-code/ProtonMail/WebClients/applications/mail/src/app/components/list/snooze/containers/SnoozeDropdown.test.tsx | import { fireEvent, render } from '@testing-library/react';
import { nextMonday } from 'date-fns';
import { useUser, useUserSettings } from '@proton/components/hooks';
import { MAILBOX_LABEL_IDS } from '@proton/shared/lib/constants';
import useSnooze from '../../../../hooks/actions/useSnooze';
import { useAppDispatch } from '../../../../logic/store';
import { Element } from '../../../../models/element';
import SnoozeDropdown from './SnoozeDropdown';
jest.mock('@proton/components/hooks/useUser');
jest.mock('@proton/components/hooks/useUserSettings');
jest.mock('@proton/components/components/link/useSettingsLink');
jest.mock('proton-mail/logic/store', () => ({
useAppDispatch: jest.fn().mockReturnValue(jest.fn()),
}));
jest.mock('proton-mail/hooks/actions/useSnooze', () => ({
__esModule: true,
default: jest.fn().mockReturnValue({
canSnooze: true,
canUnsnooze: true,
isSnoozeEnabled: true,
snooze: jest.fn(),
unsnooze: jest.fn(),
handleClose: jest.fn(),
handleCustomClick: jest.fn(),
snoozeState: 'snooze-selection',
}),
}));
const useSnoozeProps = {
canSnooze: true,
canUnsnooze: true,
isSnoozeEnabled: true,
snooze: jest.fn(),
unsnooze: jest.fn(),
handleClose: jest.fn(),
handleCustomClick: jest.fn(),
snoozeState: 'snooze-selection',
};
const element: Element = {
ID: 'id',
ConversationID: 'conversationId',
Subject: 'subject',
Unread: 0,
};
describe('Snooze dropdown', () => {
const useUserMock = useUser as jest.Mock;
const useSnoozeMock = useSnooze as jest.Mock;
const useAppDispatchMock = useAppDispatch as jest.Mock;
const useUserSettingsMock = useUserSettings as jest.Mock;
beforeAll(() => {
useUserMock.mockImplementation(() => [{ hasPaidMail: false }, jest.fn]);
useUserSettingsMock.mockImplementation(() => [{ WeekStart: 1 }, jest.fn]);
});
afterAll(() => {
useUserMock.mockClear();
useSnoozeMock.mockClear();
useAppDispatchMock.mockClear();
useUserSettingsMock.mockClear();
});
it('should not return anything when flag is disabled', async () => {
useSnoozeMock.mockReturnValue({ ...useSnoozeProps, isSnoozeEnabled: false });
const { queryByTestId } = render(<SnoozeDropdown labelID={MAILBOX_LABEL_IDS.INBOX} elements={[element]} />);
expect(queryByTestId('dropdown-button')).toBeNull();
});
it('should not return anything when cannot snooze or unsnooze', async () => {
useSnoozeMock.mockReturnValue({ ...useSnoozeProps, canSnooze: false, canUnsnooze: false });
const { queryByTestId } = render(<SnoozeDropdown labelID={MAILBOX_LABEL_IDS.INBOX} elements={[element]} />);
expect(queryByTestId('dropdown-button')).toBeNull();
});
it('should not return anything when element is an empty array', async () => {
useSnoozeMock.mockReturnValue({ ...useSnoozeProps });
const { queryByTestId } = render(<SnoozeDropdown labelID={MAILBOX_LABEL_IDS.INBOX} elements={[]} />);
expect(queryByTestId('dropdown-button')).toBeNull();
});
it('should open dropdown with all Monday options', async () => {
jest.useFakeTimers({ now: nextMonday(new Date()).getTime() });
const { getByTestId } = render(<SnoozeDropdown labelID={MAILBOX_LABEL_IDS.INBOX} elements={[element]} />);
const button = getByTestId('dropdown-button');
fireEvent.click(button);
expect(useAppDispatchMock).toHaveBeenCalled();
expect(getByTestId('snooze-duration-tomorrow'));
expect(getByTestId('snooze-duration-later'));
expect(getByTestId('snooze-duration-weekend'));
expect(getByTestId('snooze-duration-nextweek'));
});
it('should open dropdown with all Monday options and unsnooze', async () => {
jest.useFakeTimers({ now: nextMonday(new Date()).getTime() });
useSnoozeMock.mockReturnValue({ ...useSnoozeProps, canUnsnooze: true });
const { getByTestId } = render(<SnoozeDropdown labelID={MAILBOX_LABEL_IDS.INBOX} elements={[element]} />);
const button = getByTestId('dropdown-button');
fireEvent.click(button);
expect(useAppDispatchMock).toHaveBeenCalled();
expect(getByTestId('snooze-duration-tomorrow'));
expect(getByTestId('snooze-duration-later'));
expect(getByTestId('snooze-duration-weekend'));
expect(getByTestId('snooze-duration-nextweek'));
expect(getByTestId('snooze-duration-unsnooze'));
});
it('should call snooze method when pressing any option', async () => {
const spySnooze = jest.fn();
useUserMock.mockImplementation(() => [{ hasPaidMail: true }, jest.fn]);
useSnoozeMock.mockReturnValue({ ...useSnoozeProps, snooze: spySnooze });
const { getByTestId } = render(<SnoozeDropdown labelID={MAILBOX_LABEL_IDS.INBOX} elements={[element]} />);
const button = getByTestId('dropdown-button');
fireEvent.click(button);
fireEvent.click(getByTestId('snooze-duration-tomorrow'));
expect(spySnooze).toHaveBeenCalledTimes(1);
expect(spySnooze).toHaveBeenCalledWith({ elements: [element], duration: 'tomorrow', snoozeTime: undefined });
});
it('should call unsnooze method when pressing the button', async () => {
const spySnooze = jest.fn();
useUserMock.mockImplementation(() => [{ hasPaidMail: true }, jest.fn]);
useSnoozeMock.mockReturnValue({ ...useSnoozeProps, unsnooze: spySnooze, canUnsnooze: true });
const { getByTestId } = render(<SnoozeDropdown labelID={MAILBOX_LABEL_IDS.INBOX} elements={[element]} />);
const button = getByTestId('dropdown-button');
fireEvent.click(button);
fireEvent.click(getByTestId('snooze-duration-unsnooze'));
expect(spySnooze).toHaveBeenCalledTimes(1);
expect(spySnooze).toHaveBeenCalledWith([element]);
});
it('should call custom click method when pressing button', async () => {
const spyCustom = jest.fn();
useUserMock.mockImplementation(() => [{ hasPaidMail: true }, jest.fn]);
useSnoozeMock.mockReturnValue({ ...useSnoozeProps, handleCustomClick: spyCustom });
const { getByTestId } = render(<SnoozeDropdown labelID={MAILBOX_LABEL_IDS.INBOX} elements={[element]} />);
const button = getByTestId('dropdown-button');
fireEvent.click(button);
const customButton = getByTestId('snooze-duration-custom');
fireEvent.click(customButton);
expect(spyCustom).toHaveBeenCalledTimes(1);
});
it('should open upsell modal when free user press the custom button', async () => {
const { getByTestId } = render(<SnoozeDropdown labelID={MAILBOX_LABEL_IDS.INBOX} elements={[element]} />);
const button = getByTestId('dropdown-button');
fireEvent.click(button);
const customButton = getByTestId('snooze-duration-custom');
fireEvent.click(customButton);
setTimeout(() => {
getByTestId('composer:snooze-message:upsell-modal');
}, 1);
});
});
|
3,568 | 0 | petrpan-code/ProtonMail/WebClients/applications/mail/src/app/components/list | petrpan-code/ProtonMail/WebClients/applications/mail/src/app/components/list/spy-tracker/ItemSpyTrackerIcon.test.tsx | import { fireEvent, getByText, screen } from '@testing-library/react';
import { IMAGE_PROXY_FLAGS } from '@proton/shared/lib/mail/mailSettings';
import { MessageUTMTracker } from '@proton/shared/lib/models/mailUtmTrackers';
import { addToCache, minimalCache } from '../../../helpers/test/cache';
import { clearAll } from '../../../helpers/test/helper';
import { render } from '../../../helpers/test/render';
import { MessageState } from '../../../logic/messages/messagesTypes';
import ItemSpyTrackerIcon from './ItemSpyTrackerIcon';
jest.mock('@proton/components/hooks/useProgressiveRollout', () => {
return {
__esModule: true,
default: jest.fn(() => true),
};
});
const messageWithTrackers: MessageState = {
localID: 'messageWithTrackerId',
messageImages: {
hasEmbeddedImages: true,
hasRemoteImages: false,
showEmbeddedImages: true,
showRemoteImages: true,
trackersStatus: 'loaded',
images: [
{
type: 'embedded',
id: 'imageID',
status: 'loaded',
tracker: 'Tracker 1',
cid: 'cid',
cloc: 'cloc',
attachment: {},
},
{
type: 'embedded',
id: 'imageID',
status: 'loaded',
tracker: 'Tracker 2',
cid: 'cid',
cloc: 'cloc',
attachment: {},
},
],
},
messageUTMTrackers: [
{
originalURL: 'http://tracker.com/utm_content=tracker',
cleanedURL: 'http://tracker.com',
removed: [{ key: 'utm_source', value: 'tracker' }],
},
] as MessageUTMTracker[],
};
const messageWithoutTrackers: MessageState = {
localID: 'messageWithoutTrackerId',
messageImages: {
hasEmbeddedImages: true,
hasRemoteImages: false,
showEmbeddedImages: true,
showRemoteImages: true,
trackersStatus: 'loaded',
images: [
{
type: 'embedded',
id: 'imageID',
status: 'loaded',
tracker: undefined,
cid: 'cid',
cloc: 'cloc',
attachment: {},
},
],
},
};
describe('ItemSpyTrackerIcon', () => {
afterEach(() => {
clearAll();
});
it.each`
imageProxy | message | isIconDisplayed | isNumberDisplayed | expectedTooltip
${IMAGE_PROXY_FLAGS.ALL} | ${messageWithTrackers} | ${true} | ${true} | ${'2 email trackers blocked'}
${IMAGE_PROXY_FLAGS.ALL} | ${messageWithoutTrackers} | ${true} | ${false} | ${'No email trackers found'}
${IMAGE_PROXY_FLAGS.NONE} | ${messageWithTrackers} | ${true} | ${true} | ${'Email tracker protection is disabled'}
${IMAGE_PROXY_FLAGS.NONE} | ${messageWithoutTrackers} | ${true} | ${false} | ${'Email tracker protection is disabled'}
`(
'should display the icon [$isIconDisplayed] with number [$isNumberDisplayed] when proxy is [$imageProxy]',
async ({ imageProxy, message, isIconDisplayed, isNumberDisplayed }) => {
minimalCache();
addToCache('MailSettings', { ImageProxy: imageProxy });
const { queryByTestId } = await render(<ItemSpyTrackerIcon message={message} />, false);
const icon = queryByTestId('privacy:tracker-icon');
if (!isIconDisplayed) {
// When icon is not displayed, we don't have a tooltip or the number either
expect(icon).toBeNull();
} else {
// In every other cases, the icon should be displayed
expect(icon).toBeTruthy();
// Check that the number of trackers is displayed when we want to display it
const numberOfTrackers = queryByTestId('privacy:icon-number-of-trackers');
if (isNumberDisplayed) {
expect(numberOfTrackers).toBeTruthy();
expect(numberOfTrackers?.innerHTML).toEqual('3');
} else {
expect(numberOfTrackers).toBeNull();
}
}
}
);
it('should open the privacy dropdown with trackers info', async () => {
minimalCache();
addToCache('MailSettings', { ImageProxy: IMAGE_PROXY_FLAGS.ALL });
await render(<ItemSpyTrackerIcon message={messageWithTrackers} />, false);
const icon = await screen.findByTestId('privacy:tracker-icon');
fireEvent.click(icon);
// Dropdown title
const title = screen.getByTestId('privacy:title');
getByText(title, 'We protected you from 3 trackers');
const imageTrackerRow = screen.getByTestId('privacy:image-row');
const utmTrackerRow = screen.getByTestId('privacy:utm-row');
getByText(imageTrackerRow, '2 trackers blocked');
getByText(utmTrackerRow, '1 link cleaned');
});
it('should open the privacy dropdown with no trackers found', async () => {
minimalCache();
addToCache('MailSettings', { ImageProxy: IMAGE_PROXY_FLAGS.ALL });
await render(<ItemSpyTrackerIcon message={messageWithoutTrackers} />, false);
const icon = await screen.findByTestId('privacy:tracker-icon');
fireEvent.click(icon);
// Dropdown title
const title = screen.getByTestId('privacy:title');
getByText(title, 'No trackers found');
// Description is displayed
screen.getByText("We didn't find any known trackers and tracking URLs in this email.");
});
it('should open the privacy dropdown with no protection', async () => {
minimalCache();
addToCache('MailSettings', { ImageProxy: IMAGE_PROXY_FLAGS.NONE });
await render(<ItemSpyTrackerIcon message={messageWithTrackers} />, false);
const icon = await screen.findByTestId('privacy:tracker-icon');
fireEvent.click(icon);
// Dropdown title
const title = screen.getByTestId('privacy:title');
getByText(title, 'Protect yourself from trackers');
screen.getByTestId('privacy:prevent-tracking-toggle');
// Description is displayed
screen.getByText(
'Turn on email tracker protection to prevent advertisers and others from tracking your location and online activity.'
);
});
it('should open the image tracker modal and list expected info', async () => {
minimalCache();
addToCache('MailSettings', { ImageProxy: IMAGE_PROXY_FLAGS.ALL });
await render(<ItemSpyTrackerIcon message={messageWithTrackers} />, false);
const icon = await screen.findByTestId('privacy:tracker-icon');
fireEvent.click(icon);
const imageTrackerRow = screen.getByTestId('privacy:image-row');
// Open the image tracker modal
fireEvent.click(imageTrackerRow);
const modal = screen.getByTestId('spyTrackerModal:trackers');
getByText(
modal,
'We blocked the following advertisers and organizations from seeing when you open this email, what device you’re using, and where you’re located.'
);
// Trackers are visible
getByText(modal, 'Tracker 1');
getByText(modal, 'Tracker 2');
});
it('should open the utm tracker modal and list expected info', async () => {
minimalCache();
addToCache('MailSettings', { ImageProxy: IMAGE_PROXY_FLAGS.ALL });
await render(<ItemSpyTrackerIcon message={messageWithTrackers} />, false);
const icon = await screen.findByTestId('privacy:tracker-icon');
fireEvent.click(icon);
const utmTrackerRow = screen.getByTestId('privacy:utm-row');
// Open the utm tracker modal
fireEvent.click(utmTrackerRow);
const modal = screen.getByTestId('utmTrackerModal:trackers');
getByText(
modal,
'We removed tracking information from the following links to help protect you from advertisers and others trying to track your online activity.'
);
// Trackers are visible
getByText(modal, 'http://tracker.com/utm_content=tracker');
});
});
|
3,576 | 0 | petrpan-code/ProtonMail/WebClients/applications/mail/src/app/components | petrpan-code/ProtonMail/WebClients/applications/mail/src/app/components/message/EncryptionStatusIcon.test.tsx | import { render, within } from '@testing-library/react';
import EncryptionStatusIcon from './EncryptionStatusIcon';
describe('EncryptionStatusIcon', () => {
describe('when loading is true', () => {
it('should render loader', () => {
const { getByTestId, getByText } = render(<EncryptionStatusIcon loading />);
getByTestId('circle-loader');
getByText('Loading');
});
});
describe('when fill or encrypted is undefined', () => {
it('should not render anything', () => {
const { container } = render(<EncryptionStatusIcon fill={undefined} loading={false} />);
expect(container.firstChild).toBeNull();
});
it('should not render anything', () => {
const { container } = render(<EncryptionStatusIcon isEncrypted={undefined} loading={false} />);
expect(container.firstChild).toBeNull();
});
});
describe('when isDetailsModal is true', () => {
it('should not render icon in span', () => {
const props = {
isEncrypted: true,
fill: 2,
text: 'End to End encrypted',
loading: false,
isDetailsModal: true,
};
const { queryByTestId, getByTestId, getByText } = render(<EncryptionStatusIcon {...props} />);
getByTestId('encryption-icon');
getByText('End to End encrypted');
expect(queryByTestId('encryption-icon-tooltip')).toBeNull();
});
});
describe('when there is a href', () => {
it('should render inside <a> tag and tooltip', () => {
const props = {
isEncrypted: false,
fill: 2,
loading: false,
text: 'This email adress is invalid',
};
const { getByTestId } = render(<EncryptionStatusIcon {...props} />);
const tooltip = getByTestId('encryption-icon-tooltip');
// workaround to be able to get by tag
const href = within(tooltip).getByText((_, el) => el?.tagName.toLowerCase() === 'a');
within(href).getByText('This email adress is invalid');
within(href).getByTestId('encryption-icon');
});
});
describe('when shouldHaveHref is false', () => {
it('should render only inside tooltip', () => {
const props = {
isEncrypted: false,
fill: 2,
loading: false,
text: 'This email adress is invalid',
shouldHaveHref: false,
};
const { getByTestId } = render(<EncryptionStatusIcon {...props} />);
const tooltip = getByTestId('encryption-icon-tooltip');
within(tooltip).getByText('This email adress is invalid');
within(tooltip).getByTestId('encryption-icon');
expect(within(tooltip).queryByText((_, el) => el?.tagName.toLowerCase() === 'a')).toBeNull();
});
});
});
|
3,591 | 0 | petrpan-code/ProtonMail/WebClients/applications/mail/src/app/components/message | petrpan-code/ProtonMail/WebClients/applications/mail/src/app/components/message/extras/ExtraAskResign.test.tsx | import { fireEvent } from '@testing-library/react';
import { PublicKeyReference } from '@proton/crypto';
import { releaseCryptoProxy, setupCryptoProxyForTesting } from '../../../helpers/test/crypto';
import { addApiMock, clearAll, generateKeys, render, tick } from '../../../helpers/test/helper';
import { contactEmails, message, setupContactsForPinKeys } from '../../../helpers/test/pinKeys';
import { refresh } from '../../../logic/contacts/contactsActions';
import { MessageVerification } from '../../../logic/messages/messagesTypes';
import { store } from '../../../logic/store';
import ExtraAskResign from './ExtraAskResign';
const getMessageVerification = (pinnedKeysVerified: boolean, pinnedKeys?: PublicKeyReference[]) => {
return {
pinnedKeysVerified,
senderPinnedKeys: pinnedKeys,
} as MessageVerification;
};
const setup = async (messageVerification: MessageVerification) => {
const onResignContact = jest.fn();
const component = await render(
<ExtraAskResign message={message} messageVerification={messageVerification} onResignContact={onResignContact} />
);
return component;
};
describe('Extra ask resign banner', () => {
beforeAll(async () => {
await setupCryptoProxyForTesting();
});
afterAll(async () => {
await releaseCryptoProxy();
});
beforeEach(clearAll);
it('should not display the extra ask resign banner when sender is verified and keys are pinned', async () => {
const senderKey = await generateKeys('sender', message.Sender.Address);
const messageVerification = getMessageVerification(true, [senderKey.publicKeys[0]]);
const { queryByTestId } = await setup(messageVerification);
const banner = queryByTestId('extra-ask-resign:banner');
expect(banner).toBeNull();
});
it('should not display the extra ask resign banner when sender is verified and no keys are pinned', async () => {
const messageVerification = getMessageVerification(true);
const { queryByTestId } = await setup(messageVerification);
const banner = queryByTestId('extra-ask-resign:banner');
expect(banner).toBeNull();
});
it('should not display the extra ask resign banner when sender is not verified and no keys are pinned', async () => {
const messageVerification = getMessageVerification(false);
const { queryByTestId } = await setup(messageVerification);
const banner = queryByTestId('extra-ask-resign:banner');
expect(banner).toBeNull();
});
it('should display the extra ask resign banner when sender is not verified and keys are pinned', async () => {
const { senderKeys } = await setupContactsForPinKeys();
addApiMock('core/v4/keys/all', () => ({ Address: { Keys: [{ PublicKey: senderKeys.publicKeyArmored }] } }));
// Initialize contactsMap
store.dispatch(refresh({ contacts: [...contactEmails], contactGroups: [] }));
const messageVerification = getMessageVerification(false, [senderKeys.publicKeys[0]]);
const { getByTestId, getByText } = await setup(messageVerification);
// Banner is displayed
getByTestId('extra-ask-resign:banner');
// Modal is opened
const trustKeyButton = getByText('Verify');
fireEvent.click(trustKeyButton);
await tick();
getByText('Trust pinned keys?');
});
});
|
3,597 | 0 | petrpan-code/ProtonMail/WebClients/applications/mail/src/app/components/message | petrpan-code/ProtonMail/WebClients/applications/mail/src/app/components/message/extras/ExtraErrors.test.tsx | import { render } from '../../../helpers/test/helper';
import { MessageErrors, MessageState } from '../../../logic/messages/messagesTypes';
import ExtraErrors from './ExtraErrors';
describe('Errors banner', () => {
const setup = async (errors: MessageErrors) => {
const message = { localID: 'localID', errors } as MessageState;
const { getByTestId } = await render(<ExtraErrors message={message} />);
return getByTestId('errors-banner');
};
it('should show error banner for network error', async () => {
const banner = await setup({ network: [new Error('test')] });
expect(banner.textContent).toMatch(/Network error/);
});
it('should show error banner for decryption error', async () => {
const banner = await setup({ decryption: [new Error('test')] });
expect(banner.textContent).toMatch(/Decryption error/);
});
it('should show error banner for processing error', async () => {
const banner = await setup({ processing: [new Error('test')] });
expect(banner.textContent).toMatch(/processing error/);
});
it('should show error banner for signature error', async () => {
const banner = await setup({ signature: [new Error('test')] });
expect(banner.textContent).toMatch(/Signature verification error/);
});
});
|
3,599 | 0 | petrpan-code/ProtonMail/WebClients/applications/mail/src/app/components/message | petrpan-code/ProtonMail/WebClients/applications/mail/src/app/components/message/extras/ExtraEvents.test.tsx | import { screen, waitFor } from '@testing-library/react';
import userEvent from '@testing-library/user-event';
import { useCalendarUserSettings } from '@proton/components/hooks/useCalendarUserSettings';
import { useGetVtimezonesMap } from '@proton/components/hooks/useGetVtimezonesMap';
import { getAppName } from '@proton/shared/lib/apps/helper';
import { generateAttendeeToken } from '@proton/shared/lib/calendar/attendees';
import {
CALENDAR_DISPLAY,
CALENDAR_FLAGS,
CALENDAR_TYPE,
ICAL_ATTENDEE_RSVP,
ICAL_ATTENDEE_STATUS,
ICAL_METHOD,
SETTINGS_VIEW,
} from '@proton/shared/lib/calendar/constants';
import { MEMBER_PERMISSIONS } from '@proton/shared/lib/calendar/permissions';
import { ACCENT_COLORS } from '@proton/shared/lib/colors';
import { ADDRESS_STATUS, API_CODES, APPS, BRAND_NAME } from '@proton/shared/lib/constants';
import { canonicalizeInternalEmail } from '@proton/shared/lib/helpers/email';
import { uint8ArrayToBase64String } from '@proton/shared/lib/helpers/encoding';
import { SETTINGS_WEEK_START } from '@proton/shared/lib/interfaces';
import {
CalendarKeyFlags,
CalendarUserSettings,
CalendarWithOwnMembers,
VcalVeventComponent,
} from '@proton/shared/lib/interfaces/calendar';
import { encryptAttachment } from '@proton/shared/lib/mail/send/attachments';
import isTruthy from '@proton/utils/isTruthy';
import mergeUint8Arrays from '@proton/utils/mergeUint8Arrays';
import * as inviteApi from '../../../helpers/calendar/inviteApi';
import { generateApiCalendarEvent } from '../../../helpers/test/calendar';
import { releaseCryptoProxy, setupCryptoProxyForTesting } from '../../../helpers/test/crypto';
import {
GeneratedKey,
addAddressToCache,
addApiMock,
addKeysToAddressKeysCache,
clearAll,
generateKeys as generateAddressKeys,
generateCalendarKeysAndPassphrase,
minimalCache,
render,
} from '../../../helpers/test/helper';
import { MessageStateWithData } from '../../../logic/messages/messagesTypes';
import ExtraEvents from './ExtraEvents';
jest.setTimeout(20000);
jest.mock('@proton/components/hooks/useSendIcs', () => {
return {
__esModule: true,
default: jest.fn(() => () => Promise.resolve(undefined)),
};
});
jest.mock('@proton/components/hooks/useCalendarUserSettings', () => ({
...jest.requireActual('@proton/components/hooks/useCalendarUserSettings'),
useCalendarUserSettings: jest.fn(),
}));
jest.mock('@proton/components/hooks/useGetVtimezonesMap');
const nextYear = new Date().getFullYear() + 1;
const dummyUserName = 'test';
const dummyUserEmailAddress = '[email protected]';
const dummySenderEmailAddress = '[email protected]';
const dummySenderExternalEmailAddress = '[email protected]';
const dummyRecipientExternalEmailAddress = '[email protected]';
const dummyUserPrimaryAddressID = 'default-address-id';
const dummyCalendarID = 'default-calendar-id';
const dummyCalendarName = 'My calendar';
const dummyCalendarUserSettings = {
WeekLength: 7,
WeekStart: SETTINGS_WEEK_START.MONDAY,
DisplayWeekNumber: 1,
DefaultCalendarID: dummyCalendarID,
AutoDetectPrimaryTimezone: 1,
PrimaryTimezone: 'America/New_York',
DisplaySecondaryTimezone: 0,
SecondaryTimezone: null,
ViewPreference: SETTINGS_VIEW.WEEK,
InviteLocale: null,
AutoImportInvite: 0,
};
const dummyMemberID = 'member-id';
const dummyCalendar = {
ID: dummyCalendarID,
Name: dummyCalendarName,
Description: '',
Type: CALENDAR_TYPE.PERSONAL,
Owner: { Email: dummyUserEmailAddress },
Members: [
{
ID: dummyMemberID,
AddressID: dummyUserPrimaryAddressID,
Flags: CALENDAR_FLAGS.ACTIVE,
Permissions: MEMBER_PERMISSIONS.OWNS,
Email: dummyUserEmailAddress,
CalendarID: dummyCalendarID,
Color: ACCENT_COLORS[1],
Display: CALENDAR_DISPLAY.HIDDEN,
Name: dummyCalendarName,
Description: '',
Priority: 1,
},
],
};
const dummyAttachmentID = 'attachment-id';
const dummyCalendarKeyID = 'calendar-key-id';
const dummyEventID = 'event-id';
const dummySharedEventID = 'shared-event-id';
const dummyPassphraseID = 'passphrase-id';
const dummyFileName = 'invite.ics';
const generateCalendars = (numberOfCalendars: number, disableCalendars = false) => {
const calendars: CalendarWithOwnMembers[] = [];
for (let i = 0; i < numberOfCalendars; i++) {
const calendar = {
ID: `${dummyCalendarID}-${i}`,
Name: `${dummyCalendarName}-${i}`,
Description: '',
Type: CALENDAR_TYPE.PERSONAL,
Owner: { Email: dummyUserEmailAddress },
Members: [
{
ID: dummyMemberID,
AddressID: dummyUserPrimaryAddressID,
Flags: disableCalendars ? CALENDAR_FLAGS.SELF_DISABLED : CALENDAR_FLAGS.ACTIVE,
Permissions: MEMBER_PERMISSIONS.OWNS,
Email: dummyUserEmailAddress,
CalendarID: `${dummyCalendarID}-${i}`,
Color: ACCENT_COLORS[1],
Display: CALENDAR_DISPLAY.HIDDEN,
Name: dummyCalendarName,
Description: '',
Priority: 1,
},
],
};
calendars.push(calendar);
}
return calendars;
};
let dummyAddressKey: GeneratedKey;
let dummyCalendarKeysAndPassphrasePromise: ReturnType<typeof generateCalendarKeysAndPassphrase>;
const getSetup = async ({
userEmailAddress = dummyUserEmailAddress,
senderEmailAddress = dummySenderEmailAddress,
attachments,
methodInMimeType,
emailSubject = 'A new invitation',
userAddressKey,
userPrimaryAddressID = dummyUserPrimaryAddressID,
userCalendars = [dummyCalendar],
userCalendarSettings = dummyCalendarUserSettings,
defaultCalendarID = dummyCalendarID,
eventCalendarID,
eventID = dummyEventID,
sharedEventID = dummySharedEventID,
veventsApi = [],
memberID = dummyMemberID,
alternativeCalendarKeysAndPassphrasePromise,
alternativeAddressKeyPromise,
userAddressEnabled = true,
isSimpleLogin = false,
}: {
userEmailAddress?: string;
senderEmailAddress?: string;
attachments: { filename: string; ics: string; attachmentID: string }[];
methodInMimeType?: ICAL_METHOD;
emailSubject?: string;
userAddressKey?: GeneratedKey;
userPrimaryAddressID?: string;
userCalendars?: CalendarWithOwnMembers[];
userCalendarSettings?: CalendarUserSettings;
defaultCalendarID?: string | null;
eventCalendarID?: string;
eventID?: string;
sharedEventID?: string;
veventsApi?: VcalVeventComponent[];
memberID?: string;
alternativeCalendarKeysAndPassphrasePromise?: ReturnType<typeof generateCalendarKeysAndPassphrase>;
alternativeAddressKeyPromise?: ReturnType<typeof generateAddressKeys>;
userAddressEnabled?: boolean;
isSimpleLogin?: boolean;
}) => {
const addressKey = userAddressKey || dummyAddressKey;
const alternativeAddressKey = await alternativeAddressKeyPromise;
const { calendarKey, passphrase } = await dummyCalendarKeysAndPassphrasePromise;
const { calendarKey: alternativeCalendarKey } = (await alternativeCalendarKeysAndPassphrasePromise) || {};
const encryptedAttachments = await Promise.all(
attachments.map(async ({ attachmentID, filename, ics }) => {
let mimeType = 'text/calendar';
if (methodInMimeType) {
mimeType += `; method=${methodInMimeType}`;
}
const inviteAttachment = new File([new Blob([ics])], filename, { type: mimeType });
const attachmentPackets = await encryptAttachment(ics, inviteAttachment, false, addressKey.publicKeys, []);
const concatenatedPackets = mergeUint8Arrays(
[attachmentPackets.data, attachmentPackets.keys, attachmentPackets.signature].filter(isTruthy)
);
// Mock API calls to get attachment
addApiMock(`mail/v4/attachments/${attachmentID}`, () => concatenatedPackets);
return {
attachmentID,
filename,
ics,
attachmentPackets,
};
})
);
// Mock calendar API calls
addApiMock('calendar/v1', () => ({
Calendars: userCalendars,
}));
addApiMock('settings/calendar', () => ({
CalendarUserSettings: userCalendarSettings,
}));
const bootstrapCalendarID = eventCalendarID || defaultCalendarID;
if (bootstrapCalendarID) {
addApiMock(`calendar/v1/${bootstrapCalendarID}/events/${eventID}/upgrade`, () => ({
Calendars: userCalendars,
}));
addApiMock(`calendar/v1/${bootstrapCalendarID}/bootstrap`, () => ({
Keys: [
{
ID: dummyCalendarKeyID,
CalendarID: defaultCalendarID,
PrivateKey: calendarKey.privateKeyArmored,
PassphraseID: dummyPassphraseID,
Flags: CalendarKeyFlags.PRIMARY + CalendarKeyFlags.ACTIVE,
},
],
Passphrase: {
ID: dummyPassphraseID,
Flags: 1,
MemberPassphrases: [
{
MemberID: memberID,
Passphrase: passphrase.armored,
Signature: passphrase.signature,
},
],
Invitations: [],
},
Members: [
{
ID: memberID,
Email: userEmailAddress,
Permissions: 1,
},
],
CalendarSettings: {
CalendarID: dummyCalendarKeyID,
DefaultEventDuration: 30,
DefaultFullDayNotifications: [
{ Trigger: '-PT17H', Type: 1 },
{ Trigger: '-PT17H', Type: 0 },
],
DefaultPartDayNotifications: [
{ Trigger: '-PT17M', Type: 1 },
{ Trigger: '-PT17M', Type: 0 },
],
ID: dummyCalendarKeyID,
},
}));
}
// mock call to get calendar events
const events = await Promise.all(
veventsApi.map((eventComponent) =>
generateApiCalendarEvent({
eventComponent,
author: userEmailAddress,
publicKey: alternativeCalendarKey?.publicKeys[0] || calendarKey.publicKeys[0],
privateKey: alternativeAddressKey?.privateKeys[0] || addressKey.privateKeys[0],
eventID,
sharedEventID,
calendarID: dummyCalendarID,
})
)
);
addApiMock('calendar/v1/events', () => ({
Code: API_CODES.SINGLE_SUCCESS,
Events: events,
}));
// mock address keys to encrypt ICS attachment
minimalCache();
addAddressToCache({
ID: userPrimaryAddressID,
Email: userEmailAddress,
Status: userAddressEnabled ? ADDRESS_STATUS.STATUS_ENABLED : ADDRESS_STATUS.STATUS_DISABLED,
});
addKeysToAddressKeysCache(userPrimaryAddressID, addressKey);
return {
localID: '1',
data: {
ID: '1',
Sender: { Name: senderEmailAddress, Address: senderEmailAddress, IsSimpleLogin: isSimpleLogin ? 1 : 0 },
AddressID: userPrimaryAddressID,
Subject: emailSubject,
Time: new Date().getTime() / 1000,
Attachments: encryptedAttachments.map(({ attachmentID, filename, attachmentPackets }) => ({
ID: attachmentID,
Name: filename,
KeyPackets: uint8ArrayToBase64String(attachmentPackets.keys),
MIMEType: 'text/calendar',
})),
ParsedHeaders: {
'X-Original-To': userEmailAddress,
},
},
} as unknown as MessageStateWithData;
};
describe('ICS widget', () => {
beforeAll(async () => {
await setupCryptoProxyForTesting();
dummyAddressKey = await generateAddressKeys(dummyUserName, dummyUserEmailAddress);
dummyCalendarKeysAndPassphrasePromise = generateCalendarKeysAndPassphrase(dummyAddressKey);
});
afterAll(async () => {
await releaseCryptoProxy();
});
beforeEach(() => {
jest.spyOn(inviteApi, 'createCalendarEventFromInvitation');
// @ts-ignore
useCalendarUserSettings.mockReturnValue([{}, false]);
});
afterEach(clearAll);
it('should not duplicate error banners', async () => {
// constants
const dummyUID = '[email protected]';
const dummyToken = await generateAttendeeToken(canonicalizeInternalEmail(dummyUserEmailAddress), dummyUID);
// ics with unsupported time zone
const ics = `BEGIN:VCALENDAR
PRODID:-//Proton AG//WebCalendar 4.5.0//EN
VERSION:2.0
METHOD:REQUEST
CALSCALE:GREGORIAN
BEGIN:VEVENT
SEQUENCE:1
STATUS:CONFIRMED
SUMMARY:Walk on Mars
UID:${dummyUID}
DTSTART;TZID=Mars/Olympus:20220310T114500
ORGANIZER;CN=ORGO:mailto:${dummySenderEmailAddress}
ATTENDEE;ROLE=REQ-PARTICIPANT;RSVP=TRUE;PARTSTAT=NEEDS-ACTION;X-PM-TOKEN=${dummyToken}:mailto:${dummyUserEmailAddress}
DTSTAMP:20210917T133417Z
END:VEVENT
END:VCALENDAR`;
const message = await getSetup({
attachments: [
{ attachmentID: 'attachment-id-1', filename: 'invite.ics', ics },
{ attachmentID: 'attachment-id-2', filename: 'calendar.ics', ics },
],
veventsApi: [],
eventCalendarID: dummyCalendarID,
});
await render(<ExtraEvents message={message} />, false);
// test single banner
expect(screen.getAllByText('Unsupported invitation')).toHaveLength(1);
});
describe('organizer mode', () => {
it('method=reply: displays the correct UI for the case with no calendars', async () => {
const dummyUID = '[email protected]';
const dummyToken = await generateAttendeeToken(canonicalizeInternalEmail(dummyUserEmailAddress), dummyUID);
const ics = `BEGIN:VCALENDAR
PRODID:-//Proton AG//WebCalendar 4.5.0//EN
VERSION:2.0
METHOD:REPLY
CALSCALE:GREGORIAN
BEGIN:VEVENT
SEQUENCE:1
STATUS:CONFIRMED
SUMMARY:Walk on Mars
UID:${dummyUID}
DTSTART;VALUE=DATE:${nextYear}0920
ORGANIZER;CN=ORGO:mailto:${dummyUserEmailAddress}
ATTENDEE;ROLE=REQ-PARTICIPANT;RSVP=TRUE;PARTSTAT=NEEDS-ACTION;X-PM-TOKEN=${dummyToken}:mailto:${dummyUserEmailAddress}
DTSTAMP:20100917T133417Z
END:VEVENT
END:VCALENDAR`;
const message = await getSetup({
attachments: [{ attachmentID: dummyAttachmentID, filename: dummyFileName, ics }],
userCalendars: [],
veventsApi: [],
eventCalendarID: dummyCalendarID,
userEmailAddress: dummyUserEmailAddress,
senderEmailAddress: dummyUserEmailAddress,
});
await render(<ExtraEvents message={message} />, false);
expect(screen.getByText(/This response is out of date. You have no calendars./)).toBeInTheDocument();
});
it('method=counter: decryption error', async () => {
const alternativeCalendarKeysAndPassphrasePromise = generateCalendarKeysAndPassphrase(dummyAddressKey);
const dummyUID = '[email protected]';
const dummyToken = await generateAttendeeToken(
canonicalizeInternalEmail(dummySenderEmailAddress),
dummyUID
);
const ics = `BEGIN:VCALENDAR
PRODID:-//Proton AG//WebCalendar 4.5.0//EN
VERSION:2.0
METHOD:COUNTER
CALSCALE:GREGORIAN
BEGIN:VEVENT
SEQUENCE:1
STATUS:CONFIRMED
SUMMARY:Walk on Mars
UID:${dummyUID}
DTSTART;VALUE=DATE:${nextYear}0920
ORGANIZER;CN=ORGO:mailto:${dummyUserEmailAddress}
ATTENDEE;ROLE=REQ-PARTICIPANT;RSVP=TRUE;PARTSTAT=ACCEPTED;X-PM-TOKEN=${dummyToken}:mailto:${dummySenderEmailAddress}
DTSTAMP:20211013T144456Z
DTSTAMP:20210917T133417Z
END:VEVENT
END:VCALENDAR`;
// random event not matching ICS (doesn't matter for the decryption error case)
const eventComponent: VcalVeventComponent = {
component: 'vevent',
uid: { value: dummyUID },
sequence: { value: 1 },
dtstart: {
value: { year: 2021, month: 9, day: 20 },
parameters: { type: 'date' },
},
dtstamp: {
value: { year: 2021, month: 9, day: 17, hours: 13, minutes: 34, seconds: 17, isUTC: true },
},
organizer: {
value: `mailto:${dummyUserEmailAddress}`,
parameters: {
cn: 'ORGO',
},
},
attendee: [
{
value: `mailto:${dummySenderEmailAddress}`,
parameters: {
'x-pm-token': dummyToken,
partstat: ICAL_ATTENDEE_STATUS.ACCEPTED,
rsvp: ICAL_ATTENDEE_RSVP.TRUE,
},
},
],
};
const message = await getSetup({
attachments: [{ attachmentID: dummyAttachmentID, filename: dummyFileName, ics }],
methodInMimeType: ICAL_METHOD.REQUEST,
veventsApi: [eventComponent],
eventCalendarID: dummyCalendarID,
alternativeCalendarKeysAndPassphrasePromise,
});
await render(<ExtraEvents message={message} />, false);
expect(
await screen.findByText(
`${dummySenderEmailAddress} accepted your invitation and proposed a new time for this event.`
)
).toBeInTheDocument();
});
it('no event in db already exists', async () => {
const dummyUID = '[email protected]';
const dummyToken = await generateAttendeeToken(canonicalizeInternalEmail(dummyUserEmailAddress), dummyUID);
const ics = `BEGIN:VCALENDAR
PRODID:-//Proton AG//WebCalendar 4.5.0//EN
VERSION:2.0
METHOD:REPLY
CALSCALE:GREGORIAN
BEGIN:VEVENT
SEQUENCE:1
STATUS:CONFIRMED
SUMMARY:Walk on Mars
UID:${dummyUID}
DTSTART;VALUE=DATE:${nextYear}0920
ORGANIZER;CN=ORGO:mailto:${dummyUserEmailAddress}
ATTENDEE;ROLE=REQ-PARTICIPANT;RSVP=TRUE;PARTSTAT=NEEDS-ACTION;X-PM-TOKEN=${dummyToken}:mailto:${dummyUserEmailAddress}
DTSTAMP:20211013T144456Z
DTSTAMP:20210917T133417Z
END:VEVENT
END:VCALENDAR`;
const message = await getSetup({
attachments: [{ attachmentID: dummyAttachmentID, filename: dummyFileName, ics }],
veventsApi: [],
eventCalendarID: dummyCalendarID,
userEmailAddress: dummyUserEmailAddress,
senderEmailAddress: dummyUserEmailAddress,
});
await render(<ExtraEvents message={message} />, false);
expect(
await screen.findByText(
/This response is out of date. The event does not exist in your calendar anymore./
)
).toBeInTheDocument();
});
it('method=refresh from future', async () => {
const dummyUID = '[email protected]';
const dummyToken = await generateAttendeeToken(
canonicalizeInternalEmail(dummySenderEmailAddress),
dummyUID
);
const ics = `BEGIN:VCALENDAR
PRODID:-//Proton AG//WebCalendar 4.5.0//EN
VERSION:2.0
METHOD:REFRESH
CALSCALE:GREGORIAN
BEGIN:VEVENT
SEQUENCE:3
STATUS:CONFIRMED
SUMMARY:Walk on Mars
UID:${dummyUID}
DTSTART;VALUE=DATE:${nextYear}0920
ORGANIZER;CN=ORGO:mailto:${dummyUserEmailAddress}
ATTENDEE;ROLE=REQ-PARTICIPANT;RSVP=TRUE;PARTSTAT=NEEDS-ACTION;X-PM-TOKEN=${dummyToken}:mailto:${dummySenderEmailAddress}
DTSTAMP:${nextYear}1013T144456Z
END:VEVENT
END:VCALENDAR`;
const eventComponent: VcalVeventComponent = {
component: 'vevent',
uid: { value: dummyUID },
sequence: { value: 1 },
dtstart: {
value: { year: nextYear, month: 9, day: 20 },
parameters: { type: 'date' },
},
dtstamp: {
value: { year: nextYear, month: 9, day: 17, hours: 13, minutes: 34, seconds: 17, isUTC: true },
},
organizer: {
value: `mailto:${dummySenderEmailAddress}`,
parameters: {
cn: 'ORGO',
},
},
attendee: [
{
value: `mailto:${dummyUserEmailAddress}`,
parameters: {
'x-pm-token': dummyToken,
partstat: ICAL_ATTENDEE_STATUS.ACCEPTED,
rsvp: ICAL_ATTENDEE_RSVP.TRUE,
},
},
],
};
const message = await getSetup({
attachments: [{ attachmentID: dummyAttachmentID, filename: dummyFileName, ics }],
veventsApi: [eventComponent],
eventCalendarID: dummyCalendarID,
});
await render(<ExtraEvents message={message} />, false);
expect(
await screen.findByText(
`${dummySenderEmailAddress} asked for the latest updates to an event which doesn't match your invitation details. Please verify the invitation details in your calendar.`
)
).toBeInTheDocument();
});
it('method=reply outdated', async () => {
const dummyUID = '[email protected]';
const dummyToken = await generateAttendeeToken(
canonicalizeInternalEmail(dummySenderEmailAddress),
dummyUID
);
const ics = `BEGIN:VCALENDAR
PRODID:-//Proton AG//WebCalendar 4.5.0//EN
VERSION:2.0
METHOD:REPLY
CALSCALE:GREGORIAN
BEGIN:VEVENT
SEQUENCE:1
STATUS:CONFIRMED
SUMMARY:Walk on Mars
UID:${dummyUID}
DTSTART;VALUE=DATE:${nextYear}0920
ORGANIZER;CN=ORGO:mailto:${dummyUserEmailAddress}
ATTENDEE;ROLE=REQ-PARTICIPANT;RSVP=TRUE;PARTSTAT=ACCEPTED;X-PM-TOKEN=${dummyToken}:mailto:${dummySenderEmailAddress}
DTSTAMP:${nextYear}1013T144456Z
END:VEVENT
END:VCALENDAR`;
const eventComponent: VcalVeventComponent = {
component: 'vevent',
uid: { value: dummyUID },
sequence: { value: 2 },
dtstart: {
value: { year: nextYear, month: 9, day: 20 },
parameters: { type: 'date' },
},
dtstamp: {
value: { year: nextYear, month: 9, day: 17, hours: 13, minutes: 34, seconds: 17, isUTC: true },
},
organizer: {
value: `mailto:${dummyUserEmailAddress}`,
parameters: {
cn: 'ORGO',
},
},
attendee: [
{
value: `mailto:${dummySenderEmailAddress}`,
parameters: {
'x-pm-token': dummyToken,
partstat: ICAL_ATTENDEE_STATUS.ACCEPTED,
rsvp: ICAL_ATTENDEE_RSVP.TRUE,
},
},
],
};
const message = await getSetup({
attachments: [{ attachmentID: dummyAttachmentID, filename: dummyFileName, ics }],
veventsApi: [eventComponent],
eventCalendarID: dummyCalendarID,
});
await render(<ExtraEvents message={message} />, false);
expect(
await screen.findByText(`${dummySenderEmailAddress} had previously accepted your invitation.`)
).toBeInTheDocument();
});
});
describe('attendee mode', () => {
it('should display the expected fields for the "new invitation" happy case', async () => {
// constants
const anotherEmailAddress = '[email protected]';
const ics = `BEGIN:VCALENDAR
PRODID:-//Proton AG//WebCalendar 4.6.1//EN
VERSION:2.0
METHOD:REQUEST
CALSCALE:GREGORIAN
BEGIN:VTIMEZONE
TZID:Europe/Zurich
LAST-MODIFIED:20210410T122212Z
X-LIC-LOCATION:Europe/Zurich
BEGIN:DAYLIGHT
TZNAME:CEST
TZOFFSETFROM:+0100
TZOFFSETTO:+0200
DTSTART:19700329T020000
RRULE:FREQ=YEARLY;BYMONTH=3;BYDAY=-1SU
END:DAYLIGHT
BEGIN:STANDARD
TZNAME:CET
TZOFFSETFROM:+0200
TZOFFSETTO:+0100
DTSTART:19701025T030000
RRULE:FREQ=YEARLY;BYMONTH=10;BYDAY=-1SU
END:STANDARD
END:VTIMEZONE
BEGIN:VEVENT
SEQUENCE:0
STATUS:CONFIRMED
SUMMARY:Walk on the moon
UID:[email protected]
DESCRIPTION:Recommended by Matthieu
DTSTART;TZID=Europe/Zurich:20211018T110000
DTEND;TZID=Europe/Zurich:20211018T120000
ORGANIZER;CN=${dummySenderEmailAddress}:mailto:${dummySenderEmailAddress}
ATTENDEE;CN=TEST;ROLE=REQ-PARTICIPANT;RSVP=TRUE;PARTSTAT=NEEDS-ACTION;X-PM-
TOKEN=8c1a8462577e2be791f3a0286436e89c70d428f7:mailto:${dummyUserEmailAddress}
ATTENDEE;ROLE=REQ-PARTICIPANT;RSVP=TRUE;PARTSTAT=NEEDS-ACTION;X-PM-TOKEN=32
f76161336da5e2c44e4d58c40e5015bba1da9d:mailto:${anotherEmailAddress}
DTSTAMP:20211013T144456Z
X-PM-SHARED-EVENT-ID:CDr63-NYMQl8L_dbp9qzbaSXmb9e6L8shmaxZfF3hWz9vVD3FX0j4l
kmct4zKnoOX7KgYBPbcZFccjIsD34lAZXTuO99T1XXd7WE8B36T7s=
X-PM-SESSION-KEY:IAhhZBd+KXKPm95M2QRJK7WgGHovpnVdJZb2mMoiwMM=
END:VEVENT
END:VCALENDAR`;
const message = await getSetup({
attachments: [{ attachmentID: dummyAttachmentID, filename: dummyFileName, ics }],
methodInMimeType: ICAL_METHOD.REQUEST,
userCalendarSettings: dummyCalendarUserSettings,
});
await render(<ExtraEvents message={message} />, false);
// test event title
await screen.findByText('Walk on the moon');
// test event date
/**
* The exact text displayed in the event date field depends on the timezone and locale of the
* machine that runs the code. So here we just check that the date header is present. See
* dedicated tests of the date header component for tests of the text displayed.
*/
expect(screen.getByTestId('extra-event-date-header')).toBeInTheDocument();
// test event warning
expect(screen.getByText('Event already ended')).toBeInTheDocument();
// test link
expect(screen.queryByText(`Open in ${getAppName(APPS.PROTONCALENDAR)}`)).not.toBeInTheDocument();
// test buttons
expect(screen.getByText(/Attending?/)).toBeInTheDocument();
expect(screen.getByText(/Yes/, { selector: 'button' })).toBeInTheDocument();
expect(screen.getByText(/Maybe/, { selector: 'button' })).toBeInTheDocument();
expect(screen.getByText(/No/, { selector: 'button' })).toBeInTheDocument();
// test calendar
expect(screen.getByText(dummyCalendarName)).toBeInTheDocument();
// test organizer
expect(screen.getByText('Organizer:')).toBeInTheDocument();
const organizerElement = screen.getByTitle(dummySenderEmailAddress);
expect(organizerElement).toHaveAttribute(
'href',
expect.stringMatching(`mailto:${dummySenderEmailAddress}`)
);
expect(organizerElement).toHaveTextContent(dummySenderEmailAddress);
// test collapsed attendees
const showAttendeesButton = screen.getByText('Show');
expect(screen.queryByText(new RegExp(dummyUserEmailAddress))).not.toBeInTheDocument();
await userEvent.click(showAttendeesButton);
expect(screen.getByText('Show less')).toBeInTheDocument();
expect(screen.getByText(new RegExp(anotherEmailAddress))).toBeInTheDocument();
const selfAttendeeElement = screen.getByTitle(`You <${dummyUserEmailAddress}>`);
expect(selfAttendeeElement).toHaveTextContent(`You <${dummyUserEmailAddress}>`);
expect(selfAttendeeElement).toHaveAttribute(
'href',
expect.stringMatching(`mailto:${dummyUserEmailAddress}`)
);
});
it('should display the expected fields for the "already accepted invitation" happy case', async () => {
// constants
const dummyUID = '[email protected]';
const dummyToken = await generateAttendeeToken(canonicalizeInternalEmail(dummyUserEmailAddress), dummyUID);
const ics = `BEGIN:VCALENDAR
PRODID:-//Proton AG//WebCalendar 4.5.0//EN
VERSION:2.0
METHOD:REQUEST
CALSCALE:GREGORIAN
BEGIN:VEVENT
SEQUENCE:1
STATUS:CONFIRMED
SUMMARY:Walk on Mars
UID:${dummyUID}
DTSTART;VALUE=DATE:20210920
ORGANIZER;CN=ORGO:mailto:${dummySenderEmailAddress}
ATTENDEE;ROLE=REQ-PARTICIPANT;RSVP=TRUE;PARTSTAT=NEEDS-ACTION;X-PM-TOKEN=${dummyToken}:mailto:${dummyUserEmailAddress}
DTSTAMP:20210917T133417Z
END:VEVENT
END:VCALENDAR`;
const eventComponent: VcalVeventComponent = {
component: 'vevent',
uid: { value: dummyUID },
sequence: { value: 1 },
dtstart: {
value: { year: 2021, month: 9, day: 20 },
parameters: { type: 'date' },
},
dtstamp: {
value: { year: 2021, month: 9, day: 17, hours: 13, minutes: 34, seconds: 17, isUTC: true },
},
organizer: {
value: `mailto:${dummySenderEmailAddress}`,
parameters: {
cn: 'ORGO',
},
},
attendee: [
{
value: `mailto:${dummyUserEmailAddress}`,
parameters: {
'x-pm-token': dummyToken,
partstat: ICAL_ATTENDEE_STATUS.ACCEPTED,
rsvp: ICAL_ATTENDEE_RSVP.TRUE,
},
},
],
};
const message = await getSetup({
attachments: [{ attachmentID: dummyAttachmentID, filename: dummyFileName, ics }],
methodInMimeType: ICAL_METHOD.REQUEST,
veventsApi: [eventComponent],
eventCalendarID: dummyCalendarID,
});
await render(<ExtraEvents message={message} />, false);
// test event title
await screen.findByText('Walk on Mars');
// test event warning
expect(screen.getByText('Event already ended')).toBeInTheDocument();
// test link
expect(screen.getByText(`Open in ${getAppName(APPS.PROTONCALENDAR)}`)).toBeInTheDocument();
// test buttons
expect(screen.getByText('Attending?')).toBeInTheDocument();
expect(screen.getByTitle('Change my answer')).toHaveTextContent("Yes, I'll attend");
// test summary
expect(screen.getByText(/You already accepted this invitation./)).toBeInTheDocument();
});
it('shows the correct UI for an outdated invitation', async () => {
const dummyUID = '[email protected]';
const dummyToken = await generateAttendeeToken(canonicalizeInternalEmail(dummyUserEmailAddress), dummyUID);
const ics = `BEGIN:VCALENDAR
PRODID:-//Proton AG//WebCalendar 4.5.0//EN
VERSION:2.0
METHOD:REQUEST
CALSCALE:GREGORIAN
BEGIN:VEVENT
SEQUENCE:1
STATUS:CONFIRMED
SUMMARY:Walk on Mars
UID:${dummyUID}
DTSTART;VALUE=DATE:20100920
ORGANIZER;CN=ORGO:mailto:${dummySenderEmailAddress}
ATTENDEE;ROLE=REQ-PARTICIPANT;RSVP=TRUE;PARTSTAT=NEEDS-ACTION;X-PM-TOKEN=${dummyToken}:mailto:${dummyUserEmailAddress}
DTSTAMP:20100917T133417Z
END:VEVENT
END:VCALENDAR`;
const eventComponent: VcalVeventComponent = {
component: 'vevent',
uid: { value: dummyUID },
sequence: { value: 1 },
dtstart: {
value: { year: 2021, month: 9, day: 20 },
parameters: { type: 'date' },
},
dtstamp: {
// The event was updated in the DB with respect to the invite. Notice DTSTAMP has changed with respect to the ics.
value: { year: 2021, month: 9, day: 17, hours: 13, minutes: 34, seconds: 17, isUTC: true },
},
organizer: {
value: `mailto:${dummySenderEmailAddress}`,
parameters: {
cn: 'ORGO',
},
},
attendee: [
{
value: `mailto:${dummyUserEmailAddress}`,
parameters: {
'x-pm-token': dummyToken,
partstat: ICAL_ATTENDEE_STATUS.ACCEPTED,
rsvp: ICAL_ATTENDEE_RSVP.TRUE,
},
},
],
};
const defaultCalendar = {
ID: dummyCalendarID,
Name: dummyCalendarName,
Description: '',
Type: CALENDAR_TYPE.PERSONAL,
Owner: { Email: dummyUserEmailAddress },
Members: [
{
ID: dummyMemberID,
AddressID: dummyUserPrimaryAddressID,
Permissions: 127 as const,
Email: dummyUserEmailAddress,
Flags: CALENDAR_FLAGS.ACTIVE,
CalendarID: dummyCalendarID,
Color: '#f00',
Display: CALENDAR_DISPLAY.HIDDEN,
Name: dummyCalendarName,
Description: '',
Priority: 1,
},
],
};
const message = await getSetup({
attachments: [{ attachmentID: dummyAttachmentID, filename: dummyFileName, ics }],
userCalendars: [defaultCalendar],
userCalendarSettings: dummyCalendarUserSettings,
veventsApi: [eventComponent],
eventCalendarID: dummyCalendarID,
});
await render(<ExtraEvents message={message} />, false);
expect(
await screen.findByText(/This invitation is out of date. The event has been updated./)
).toBeInTheDocument();
});
it('does not display a summary when responding to an invitation', async () => {
const dummyUID = '[email protected]';
const anotherEmailAddress = '[email protected]';
const [dummyToken, anotherToken] = await Promise.all(
[dummyUserEmailAddress, anotherEmailAddress].map((address) =>
generateAttendeeToken(canonicalizeInternalEmail(address), dummyUID)
)
);
const ics = `BEGIN:VCALENDAR
PRODID:-//Proton AG//WebCalendar 4.6.1//EN
VERSION:2.0
METHOD:REQUEST
CALSCALE:GREGORIAN
BEGIN:VTIMEZONE
TZID:Europe/Zurich
LAST-MODIFIED:20210410T122212Z
X-LIC-LOCATION:Europe/Zurich
BEGIN:DAYLIGHT
TZNAME:CEST
TZOFFSETFROM:+0100
TZOFFSETTO:+0200
DTSTART:19700329T020000
RRULE:FREQ=YEARLY;BYMONTH=3;BYDAY=-1SU
END:DAYLIGHT
BEGIN:STANDARD
TZNAME:CET
TZOFFSETFROM:+0200
TZOFFSETTO:+0100
DTSTART:19701025T030000
RRULE:FREQ=YEARLY;BYMONTH=10;BYDAY=-1SU
END:STANDARD
END:VTIMEZONE
BEGIN:VEVENT
SEQUENCE:0
STATUS:CONFIRMED
SUMMARY:Walk on the moon
UID:${dummyUID}
DESCRIPTION:Recommended by Matthieu
DTSTART;TZID=Europe/Zurich:20221018T110000
DTEND;TZID=Europe/Zurich:20221018T120000
ORGANIZER;CN=${dummySenderEmailAddress}:mailto:${dummySenderEmailAddress}
ATTENDEE;CN=TEST;ROLE=REQ-PARTICIPANT;RSVP=TRUE;PARTSTAT=NEEDS-ACTION;X-PM-
TOKEN=${dummyToken}:mailto:${dummyUserEmailAddress}
ATTENDEE;ROLE=REQ-PARTICIPANT;RSVP=TRUE;PARTSTAT=NEEDS-ACTION;X-PM-TOKEN=
${anotherToken}:mailto:${anotherEmailAddress}
DTSTAMP:20211013T144456Z
X-PM-SHARED-EVENT-ID:CDr63-NYMQl8L_dbp9qzbaSXmb9e6L8shmaxZfF3hWz9vVD3FX0j4l
kmct4zKnoOX7KgYBPbcZFccjIsD34lAZXTuO99T1XXd7WE8B36T7s=
X-PM-SESSION-KEY:IAhhZBd+KXKPm95M2QRJK7WgGHovpnVdJZb2mMoiwMM=
END:VEVENT
END:VCALENDAR`;
const savedAttendee = {
value: `mailto:${dummyUserEmailAddress}`,
parameters: {
cn: 'test',
'x-pm-token': dummyToken,
partstat: ICAL_ATTENDEE_STATUS.ACCEPTED,
rsvp: ICAL_ATTENDEE_RSVP.TRUE,
},
};
const savedVevent: VcalVeventComponent = {
component: 'vevent',
uid: { value: dummyUID },
sequence: { value: 0 },
dtstart: {
value: { year: 2022, month: 10, day: 18, hours: 11, minutes: 0, seconds: 0, isUTC: false },
parameters: { tzid: 'Europe/Zurich' },
},
dtend: {
value: { year: 2022, month: 10, day: 18, hours: 12, minutes: 0, seconds: 0, isUTC: false },
parameters: { tzid: 'Europe/Zurich' },
},
dtstamp: {
value: { year: 2021, month: 10, day: 13, hours: 14, minutes: 44, seconds: 56, isUTC: true },
},
organizer: {
value: `mailto:${dummySenderEmailAddress}`,
parameters: {
cn: dummySenderEmailAddress,
},
},
attendee: [
savedAttendee,
{
value: `mailto:${anotherEmailAddress}`,
parameters: {
cn: anotherEmailAddress,
'x-pm-token': anotherToken,
partstat: ICAL_ATTENDEE_STATUS.NEEDS_ACTION,
rsvp: ICAL_ATTENDEE_RSVP.TRUE,
},
},
],
};
const savedEvent = await generateApiCalendarEvent({
eventComponent: savedVevent,
author: dummyUserEmailAddress,
publicKey: (await dummyCalendarKeysAndPassphrasePromise).calendarKey.publicKeys[0],
privateKey: dummyAddressKey.privateKeys[0],
eventID: dummyEventID,
sharedEventID:
'CDr63-NYMQl8L_dbp9qzbaSXmb9e6L8shmaxZfF3hWz9vVD3FX0j4lkmct4zKnoOX7KgYBPbcZFccjIsD34lAZXTuO99T1XXd7WE8B36T7s=',
calendarID: dummyCalendarID,
});
// @ts-ignore
inviteApi.createCalendarEventFromInvitation.mockReturnValueOnce(
Promise.resolve({ savedEvent, savedVevent, savedAttendee })
);
// @ts-ignore
useGetVtimezonesMap.mockReturnValueOnce(() =>
Promise.resolve({
'Europe/Zurich': { vtimezone: {}, vtimezoneString: '' },
})
);
const message = await getSetup({
attachments: [{ attachmentID: dummyAttachmentID, filename: dummyFileName, ics }],
});
await render(<ExtraEvents message={message} />, false);
await userEvent.click(await screen.findByTitle(`Yes, I'll attend`));
await waitFor(() => expect(screen.queryByTestId('ics-widget-summary')).not.toBeInTheDocument());
});
it('should show the correct UI for an unsupported ics with import PUBLISH', async () => {
// constants
const dummyUID = '[email protected]';
const dummyToken = await generateAttendeeToken(canonicalizeInternalEmail(dummyUserEmailAddress), dummyUID);
// ics with unsupported time zone
const ics = `BEGIN:VCALENDAR
PRODID:-//Proton AG//WebCalendar 4.5.0//EN
VERSION:2.0
METHOD:PUBLISH
CALSCALE:GREGORIAN
BEGIN:VEVENT
SEQUENCE:1
STATUS:CONFIRMED
SUMMARY:Walk on Mars
UID:${dummyUID}
DTSTART;TZID=Mars/Olympus:20220310T114500
ORGANIZER;CN=ORGO:mailto:${dummySenderEmailAddress}
ATTENDEE;ROLE=REQ-PARTICIPANT;RSVP=TRUE;PARTSTAT=NEEDS-ACTION;X-PM-TOKEN=${dummyToken}:mailto:${dummyUserEmailAddress}
DTSTAMP:20210917T133417Z
END:VEVENT
END:VCALENDAR`;
const message = await getSetup({
attachments: [{ attachmentID: dummyAttachmentID, filename: dummyFileName, ics }],
veventsApi: [],
eventCalendarID: dummyCalendarID,
});
await render(<ExtraEvents message={message} />, false);
expect(screen.queryByTestId('ics-widget-summary')).not.toBeInTheDocument();
await screen.findByText('Unsupported event');
});
it('should show the correct UI for a supported ics with import PUBLISH', async () => {
// constants
const dummyUID = '[email protected]';
const dummyToken = await generateAttendeeToken(canonicalizeInternalEmail(dummyUserEmailAddress), dummyUID);
const ics = `BEGIN:VCALENDAR
PRODID:-//Proton AG//WebCalendar 4.5.0//EN
VERSION:2.0
METHOD:PUBLISH
CALSCALE:GREGORIAN
BEGIN:VEVENT
SEQUENCE:1
STATUS:CONFIRMED
SUMMARY:Walk on Mars
UID:${dummyUID}
DTSTART;TZID=Europe/Zurich:20220310T114500
ORGANIZER;CN=ORGO:mailto:${dummySenderEmailAddress}
ATTENDEE;ROLE=REQ-PARTICIPANT;RSVP=TRUE;PARTSTAT=NEEDS-ACTION;X-PM-TOKEN=${dummyToken}:mailto:${dummyUserEmailAddress}
DTSTAMP:20210917T133417Z
END:VEVENT
END:VCALENDAR`;
const message = await getSetup({
attachments: [{ attachmentID: dummyAttachmentID, filename: dummyFileName, ics }],
veventsApi: [],
eventCalendarID: dummyCalendarID,
});
await render(<ExtraEvents message={message} />, false);
expect(screen.queryByTestId('ics-widget-summary')).not.toBeInTheDocument();
});
describe('Party crasher ICS widget', () => {
describe('Internal organizer', () => {
it('should not be possible to accept the event when the attendee is a party crasher and the organizer is internal', async () => {
const ics = `BEGIN:VCALENDAR
PRODID:-//Proton AG//WebCalendar 4.5.0//EN
VERSION:2.0
METHOD:REQUEST
CALSCALE:GREGORIAN
BEGIN:VTIMEZONE
TZID:Europe/Zurich
LAST-MODIFIED:20210410T122212Z
X-LIC-LOCATION:Europe/Zurich
BEGIN:DAYLIGHT
TZNAME:CEST
TZOFFSETFROM:+0100
TZOFFSETTO:+0200
DTSTART:19700329T020000
RRULE:FREQ=YEARLY;BYMONTH=3;BYDAY=-1SU
END:DAYLIGHT
BEGIN:STANDARD
TZNAME:CET
TZOFFSETFROM:+0200
TZOFFSETTO:+0100
DTSTART:19701025T030000
RRULE:FREQ=YEARLY;BYMONTH=10;BYDAY=-1SU
END:STANDARD
END:VTIMEZONE
BEGIN:VEVENT
SEQUENCE:0
STATUS:CONFIRMED
SUMMARY:Walk on the moon
UID:[email protected]
DESCRIPTION:Recommended by Matthieu
DTSTART;TZID=Europe/Zurich:20211018T110000
DTEND;TZID=Europe/Zurich:20211018T120000
ORGANIZER;CN=${dummySenderEmailAddress}:mailto:${dummySenderEmailAddress}
ATTENDEE;CN=${dummyRecipientExternalEmailAddress};ROLE=REQ-PARTICIPANT;RSVP=TRUE;PARTSTAT=ACCEPTED:mailto:${dummyRecipientExternalEmailAddress}
END:VEVENT
END:VCALENDAR`;
// dummySenderEmailAddress sends an invitation to dummyRecipientExternalEmailAddress
// Then dummyRecipientExternalEmailAddress forwards the invite to dummyUserEmailAddress.
// => dummyUserEmailAddress is now a party crasher
const message = await getSetup({
attachments: [{ attachmentID: dummyAttachmentID, filename: dummyFileName, ics }],
methodInMimeType: ICAL_METHOD.REQUEST,
userCalendarSettings: dummyCalendarUserSettings,
senderEmailAddress: dummyRecipientExternalEmailAddress,
});
await render(<ExtraEvents message={message} />, false);
// Alert is displayed
expect(
await screen.findByText(
`You cannot respond to ${BRAND_NAME} invites if you're not on the participants list at the moment.`
)
).toBeInTheDocument();
// test buttons
expect(screen.queryByText(/Attending?/)).not.toBeInTheDocument();
expect(screen.queryByText(/Yes/, { selector: 'button' })).not.toBeInTheDocument();
expect(screen.queryByText(/Maybe/, { selector: 'button' })).not.toBeInTheDocument();
expect(screen.queryByText(/No/, { selector: 'button' })).not.toBeInTheDocument();
});
});
describe('External organizer', () => {
const partyCrasherExternalICS = `BEGIN:VCALENDAR
PRODID:-//Google Inc//Google Calendar 70.9054//EN
VERSION:2.0
METHOD:REQUEST
CALSCALE:GREGORIAN
BEGIN:VTIMEZONE
TZID:Europe/Zurich
LAST-MODIFIED:20210410T122212Z
X-LIC-LOCATION:Europe/Zurich
BEGIN:DAYLIGHT
TZNAME:CEST
TZOFFSETFROM:+0100
TZOFFSETTO:+0200
DTSTART:19700329T020000
RRULE:FREQ=YEARLY;BYMONTH=3;BYDAY=-1SU
END:DAYLIGHT
BEGIN:STANDARD
TZNAME:CET
TZOFFSETFROM:+0200
TZOFFSETTO:+0100
DTSTART:19701025T030000
RRULE:FREQ=YEARLY;BYMONTH=10;BYDAY=-1SU
END:STANDARD
END:VTIMEZONE
BEGIN:VEVENT
SEQUENCE:0
STATUS:CONFIRMED
SUMMARY:Walk on the moon
UID:[email protected]
DESCRIPTION:Recommended by Matthieu
DTSTART;TZID=Europe/Zurich:20211018T110000
DTEND;TZID=Europe/Zurich:20211018T120000
ORGANIZER;CN=${dummySenderExternalEmailAddress}:mailto:${dummySenderExternalEmailAddress}
ATTENDEE;CN=${dummyRecipientExternalEmailAddress};ROLE=REQ-PARTICIPANT;RSVP=TRUE;PARTSTAT=ACCEPTED:mailto:${dummyRecipientExternalEmailAddress}
END:VEVENT
END:VCALENDAR`;
it('should be possible to accept the event when the attendee is a party crasher and the organizer is external', async () => {
// dummySenderExternalEmailAddress sends an invitation to dummyRecipientExternalEmailAddress
// Then dummyRecipientExternalEmailAddress forwards the invite to dummyUserEmailAddress.
// => dummyUserEmailAddress is now a party crasher
const message = await getSetup({
attachments: [
{ attachmentID: dummyAttachmentID, filename: dummyFileName, ics: partyCrasherExternalICS },
],
methodInMimeType: ICAL_METHOD.REQUEST,
userCalendarSettings: dummyCalendarUserSettings,
senderEmailAddress: dummyRecipientExternalEmailAddress,
});
await render(<ExtraEvents message={message} />, false);
// Alert is displayed
expect(
await screen.findByText('Your email address is not in the original participants list.')
).toBeInTheDocument();
// test buttons
expect(screen.getByText(/Attending?/)).toBeInTheDocument();
expect(screen.getByText(/Yes/, { selector: 'button' })).toBeInTheDocument();
expect(screen.getByText(/Maybe/, { selector: 'button' })).toBeInTheDocument();
expect(screen.getByText(/No/, { selector: 'button' })).toBeInTheDocument();
});
it('should show widget when the attendee is a party crasher which accepted the invite, and the organizer is external', async () => {
const dummyUID = '[email protected]';
const dummyToken = await generateAttendeeToken(
canonicalizeInternalEmail(dummyUserEmailAddress),
dummyUID
);
const ics = `BEGIN:VCALENDAR
PRODID:-//Google Inc//Google Calendar 70.9054//EN
VERSION:2.0
METHOD:REQUEST
CALSCALE:GREGORIAN
BEGIN:VEVENT
DTSTART;VALUE=DATE:20210920
SEQUENCE:1
STATUS:CONFIRMED
SUMMARY:Walk on the moon
UID:${dummyUID}
DESCRIPTION:Recommended by Matthieu
ORGANIZER;CN=${dummySenderExternalEmailAddress}:mailto:${dummySenderExternalEmailAddress}
ATTENDEE;CN=${dummyRecipientExternalEmailAddress};ROLE=REQ-PARTICIPANT;RSVP=TRUE;PARTSTAT=ACCEPTED:mailto:${dummyRecipientExternalEmailAddress}
DTSTAMP:20210917T133417Z
END:VEVENT
END:VCALENDAR`;
const eventComponent: VcalVeventComponent = {
component: 'vevent',
uid: { value: dummyUID },
sequence: { value: 1 },
dtstart: {
value: { year: 2021, month: 9, day: 20 },
parameters: { type: 'date' },
},
dtstamp: {
value: { year: 2021, month: 9, day: 17, hours: 13, minutes: 34, seconds: 17, isUTC: true },
},
organizer: {
value: `mailto:${dummySenderExternalEmailAddress}`,
parameters: {
cn: 'ORGO',
},
},
attendee: [
{
value: `mailto:${dummyRecipientExternalEmailAddress}`,
parameters: {
partstat: ICAL_ATTENDEE_STATUS.ACCEPTED,
rsvp: ICAL_ATTENDEE_RSVP.TRUE,
},
},
{
value: `mailto:${dummyUserEmailAddress}`,
parameters: {
'x-pm-token': dummyToken,
partstat: ICAL_ATTENDEE_STATUS.ACCEPTED,
rsvp: ICAL_ATTENDEE_RSVP.TRUE,
},
},
],
};
// dummySenderExternalEmailAddress sends an invitation to dummyRecipientExternalEmailAddress
// Then dummyRecipientExternalEmailAddress forwards the invite to dummyUserEmailAddress.
// => dummyUserEmailAddress is now a party crasher, and he accepted the invite.
const message = await getSetup({
attachments: [{ attachmentID: dummyAttachmentID, filename: dummyFileName, ics }],
methodInMimeType: ICAL_METHOD.REQUEST,
userCalendarSettings: dummyCalendarUserSettings,
senderEmailAddress: dummyRecipientExternalEmailAddress,
veventsApi: [eventComponent],
});
await render(<ExtraEvents message={message} />, false);
await screen.findByText('Walk on the moon');
// Alert is displayed
expect(
screen.getByText('Your email address is not in the original participants list.')
).toBeInTheDocument();
// test buttons
expect(screen.getByText(/Attending?/)).toBeInTheDocument();
expect(screen.getByTitle('Change my answer')).toHaveTextContent("Yes, I'll attend");
});
it('should show widget when the attendee is a party crasher with disabled address, and organizer is external', async () => {
// dummySenderExternalEmailAddress sends an invitation to dummyRecipientExternalEmailAddress
// Then dummyRecipientExternalEmailAddress forwards the invite to dummyUserEmailAddress.
// => dummyUserEmailAddress is now a party crasher
const message = await getSetup({
attachments: [
{ attachmentID: dummyAttachmentID, filename: dummyFileName, ics: partyCrasherExternalICS },
],
methodInMimeType: ICAL_METHOD.REQUEST,
userCalendarSettings: dummyCalendarUserSettings,
senderEmailAddress: dummyRecipientExternalEmailAddress,
userAddressEnabled: false,
});
await render(<ExtraEvents message={message} />, false);
// Alert is displayed
expect(await screen.findByText('You cannot reply from the invited address.')).toBeInTheDocument();
// test buttons
expect(screen.queryByText(/Attending?/)).not.toBeInTheDocument();
expect(screen.queryByText(/Yes/, { selector: 'button' })).not.toBeInTheDocument();
expect(screen.queryByText(/Maybe/, { selector: 'button' })).not.toBeInTheDocument();
expect(screen.queryByText(/No/, { selector: 'button' })).not.toBeInTheDocument();
});
it('should show widget when the attendee is a party crasher with disabled calendars, and organizer is external', async () => {
// dummySenderExternalEmailAddress sends an invitation to dummyRecipientExternalEmailAddress
// Then dummyRecipientExternalEmailAddress forwards the invite to dummyUserEmailAddress.
// => dummyUserEmailAddress is now a party crasher
const message = await getSetup({
attachments: [
{ attachmentID: dummyAttachmentID, filename: dummyFileName, ics: partyCrasherExternalICS },
],
methodInMimeType: ICAL_METHOD.REQUEST,
userCalendarSettings: dummyCalendarUserSettings,
senderEmailAddress: dummyRecipientExternalEmailAddress,
defaultCalendarID: 'calendar-key-id-0',
userCalendars: generateCalendars(2, true),
});
await render(<ExtraEvents message={message} />, false);
// Alert is displayed
expect(await screen.findByText('All your calendars are disabled.')).toBeInTheDocument();
expect(
await screen.findByText('Create a calendar linked to an active email address.')
).toBeInTheDocument();
// test buttons
expect(screen.getByText(/Attending?/)).toBeInTheDocument();
expect(screen.getByText(/Yes/, { selector: 'button' })).toBeInTheDocument();
expect(screen.getByText(/Maybe/, { selector: 'button' })).toBeInTheDocument();
expect(screen.getByText(/No/, { selector: 'button' })).toBeInTheDocument();
});
it('should show widget when the attendee is a party crasher with disabled calendars, calendar limit reached, and organizer is external', async () => {
// dummySenderExternalEmailAddress sends an invitation to dummyRecipientExternalEmailAddress
// Then dummyRecipientExternalEmailAddress forwards the invite to dummyUserEmailAddress.
// => dummyUserEmailAddress is now a party crasher
const message = await getSetup({
attachments: [
{ attachmentID: dummyAttachmentID, filename: dummyFileName, ics: partyCrasherExternalICS },
],
methodInMimeType: ICAL_METHOD.REQUEST,
userCalendarSettings: dummyCalendarUserSettings,
senderEmailAddress: dummyRecipientExternalEmailAddress,
defaultCalendarID: 'calendar-key-id-0',
userCalendars: generateCalendars(25, true),
});
await render(<ExtraEvents message={message} />, false);
// Alert is displayed
expect(await screen.findByText('All your calendars are disabled.')).toBeInTheDocument();
expect(
await screen.findByText('Enable an email address linked to one of your calendars.')
).toBeInTheDocument();
expect(
await screen.findByText(
'Or you can delete one of your calendars and create a new one linked to an active email address.'
)
).toBeInTheDocument();
// test buttons
expect(screen.getByText(/Attending?/)).toBeInTheDocument();
expect(screen.getByText(/Yes/, { selector: 'button' })).toBeInTheDocument();
expect(screen.getByText(/Maybe/, { selector: 'button' })).toBeInTheDocument();
expect(screen.getByText(/No/, { selector: 'button' })).toBeInTheDocument();
});
it('should not be possible to accept party crasher events when the mail is coming from SimpleLogin', async () => {
const message = await getSetup({
attachments: [
{ attachmentID: dummyAttachmentID, filename: dummyFileName, ics: partyCrasherExternalICS },
],
methodInMimeType: ICAL_METHOD.REQUEST,
userCalendarSettings: dummyCalendarUserSettings,
senderEmailAddress: dummyRecipientExternalEmailAddress,
isSimpleLogin: true,
});
await render(<ExtraEvents message={message} />, false);
// Alert is displayed
expect(
await screen.findByText('Your email address is not in the original participants list.')
).toBeInTheDocument();
// test buttons
expect(screen.queryByText(/Attending?/)).not.toBeInTheDocument();
expect(screen.queryByText(/Yes/, { selector: 'button' })).not.toBeInTheDocument();
expect(screen.queryByText(/Maybe/, { selector: 'button' })).not.toBeInTheDocument();
expect(screen.queryByText(/No/, { selector: 'button' })).not.toBeInTheDocument();
});
});
});
});
});
|
3,602 | 0 | petrpan-code/ProtonMail/WebClients/applications/mail/src/app/components/message | petrpan-code/ProtonMail/WebClients/applications/mail/src/app/components/message/extras/ExtraPinKey.test.tsx | import { Matcher, fireEvent } from '@testing-library/react';
import { PublicKeyReference } from '@proton/crypto';
import { Address, MailSettings } from '@proton/shared/lib/interfaces';
import { Message } from '@proton/shared/lib/interfaces/mail/Message';
import { VERIFICATION_STATUS } from '@proton/shared/lib/mail/constants';
import { PROMPT_PIN } from '@proton/shared/lib/mail/mailSettings';
import { releaseCryptoProxy, setupCryptoProxyForTesting } from '../../../helpers/test/crypto';
import {
addApiMock,
addToCache,
clearAll,
generateKeys,
minimalCache,
render,
tick,
} from '../../../helpers/test/helper';
import { message } from '../../../helpers/test/pinKeys';
import { MessageVerification } from '../../../logic/messages/messagesTypes';
import ExtraPinKey from './ExtraPinKey';
const { SIGNED_AND_VALID, SIGNED_AND_INVALID, NOT_SIGNED, NOT_VERIFIED } = VERIFICATION_STATUS;
const setup = async (
message: Message,
messageVerification: MessageVerification,
isOwnAddress = false,
isAutoPrompt = false
) => {
minimalCache();
if (isOwnAddress) {
addToCache('Addresses', [{ Email: '[email protected]' } as Address]);
}
if (isAutoPrompt) {
addToCache('MailSettings', { PromptPin: PROMPT_PIN.ENABLED } as MailSettings);
}
const component = await render(<ExtraPinKey message={message} messageVerification={messageVerification} />, false);
return component;
};
describe('Extra pin key banner not displayed', () => {
beforeAll(async () => {
await setupCryptoProxyForTesting();
});
afterAll(async () => {
await releaseCryptoProxy();
});
afterEach(clearAll);
it('should not render the banner when sender has a PM address', async () => {
const senderKey = await generateKeys('sender', '[email protected]');
const signingKey = await generateKeys('signing', '[email protected]');
const messageVerification = {
signingPublicKey: signingKey.publicKeys[0],
senderPinnedKeys: [...senderKey.publicKeys] as PublicKeyReference[],
verificationStatus: SIGNED_AND_VALID,
} as MessageVerification;
const { queryByTestId } = await setup(message, messageVerification, true);
const banner = queryByTestId('extra-pin-key:banner');
expect(banner).toBeNull();
});
it.each`
verificationStatus
${NOT_SIGNED}
${NOT_VERIFIED}
${SIGNED_AND_INVALID}
`('should not render the banner when signing public key is already pinned', async ({ verificationStatus }) => {
const senderKey = await generateKeys('sender', message.Sender.Address);
const messageVerification = {
senderPinnedKeys: [...senderKey.publicKeys] as PublicKeyReference[],
attachedPublicKeys: [...senderKey.publicKeys] as PublicKeyReference[],
verificationStatus,
} as MessageVerification;
const { queryByTestId } = await setup(message, messageVerification);
const banner = queryByTestId('extra-pin-key:banner');
expect(banner).toBeNull();
});
});
describe('Extra pin key banner displayed', () => {
beforeAll(async () => {
await setupCryptoProxyForTesting();
});
afterAll(async () => {
await releaseCryptoProxy();
});
afterEach(clearAll);
const openTrustKeyModal = async (getByText: (text: Matcher) => HTMLElement) => {
const trustKeyButton = getByText('Trust key');
fireEvent.click(trustKeyButton);
await tick();
// Trust public key modal is open
getByText('Trust public key?');
};
// AUTOPROMPT
it.each`
verificationStatus | shouldDisablePrompt
${NOT_VERIFIED} | ${true}
${NOT_VERIFIED} | ${false}
${SIGNED_AND_INVALID} | ${true}
${SIGNED_AND_INVALID} | ${false}
`(
'should render the banner when prompt key pinning is AUTOPROMPT',
async ({ verificationStatus, shouldDisablePrompt }) => {
const signingKey = await generateKeys('signing', message.Sender.Address);
const messageVerification = {
signingPublicKey: signingKey.publicKeys[0],
verificationStatus,
} as MessageVerification;
const { getByTestId, getByText } = await setup(message, messageVerification, false, true);
getByTestId('extra-pin-key:banner');
// Expected text is displayed
getByText("This sender's public key has not been trusted yet.");
// Test disable prompt button
if (shouldDisablePrompt) {
const updateSpy = jest.fn(() => Promise.resolve({}));
addApiMock('mail/v4/settings/promptpin', updateSpy, 'put');
const disableAutopromtButton = getByText('Never show');
fireEvent.click(disableAutopromtButton);
await tick();
expect(updateSpy).toBeCalled();
} else {
// Open trust public key modal and trust the key
await openTrustKeyModal(getByText);
}
}
);
// PIN_UNSEEN
it('should render the banner when prompt key pinning is PIN_UNSEEN', async () => {
const senderKey = await generateKeys('sender', message.Sender.Address);
const signingKey = await generateKeys('signing', message.Sender.Address);
const messageVerification = {
signingPublicKey: signingKey.publicKeys[0],
senderPinnedKeys: [...senderKey.publicKeys] as PublicKeyReference[],
senderPinnableKeys: [...signingKey.publicKeys] as PublicKeyReference[],
verificationStatus: NOT_VERIFIED,
} as MessageVerification;
const { getByTestId, getByText } = await setup(message, messageVerification);
getByTestId('extra-pin-key:banner');
// Expected text is displayed
getByText('This message is signed by a key that has not been trusted yet.');
await openTrustKeyModal(getByText);
});
it('should not render the banner when prompt key pinning is PIN_UNSEEN but the signature is invalid', async () => {
const senderKey = await generateKeys('sender', message.Sender.Address);
const signingKey = await generateKeys('signing', message.Sender.Address);
const messageVerification = {
signingPublicKey: signingKey.publicKeys[0],
senderPinnedKeys: [...senderKey.publicKeys] as PublicKeyReference[],
verificationStatus: SIGNED_AND_INVALID,
} as MessageVerification;
const { queryByTestId } = await setup(message, messageVerification);
expect(queryByTestId('extra-pin-key:banner')).toBeNull();
});
// PIN_ATTACHED_SIGNING
it.each`
verificationStatus
${NOT_VERIFIED}
${SIGNED_AND_INVALID}
`('should render the banner when prompt key pinning is PIN_ATTACHED_SIGNING', async ({ verificationStatus }) => {
const signingKey = await generateKeys('signing', message.Sender.Address);
const messageVerification = {
signingPublicKey: signingKey.publicKeys[0],
attachedPublicKeys: [...signingKey.publicKeys] as PublicKeyReference[],
verificationStatus,
} as MessageVerification;
const { getByTestId, getByText } = await setup(message, messageVerification);
getByTestId('extra-pin-key:banner');
// Expected text is displayed
getByText('This message is signed by the key attached, that has not been trusted yet.');
await openTrustKeyModal(getByText);
});
// PIN_ATTACHED
it.each`
verificationStatus | hasSigningKey
${NOT_SIGNED} | ${false}
${NOT_SIGNED} | ${true}
${NOT_VERIFIED} | ${false}
${SIGNED_AND_INVALID} | ${false}
`(
'should render the banner when prompt key pinning is PIN_ATTACHED',
async ({ verificationStatus, hasSigningKey }) => {
const signingKey = await generateKeys('signing', message.Sender.Address);
const messageVerification = {
signingPublicKey: hasSigningKey ? signingKey.publicKeys[0] : undefined,
attachedPublicKeys: [...signingKey.publicKeys] as PublicKeyReference[],
verificationStatus,
} as MessageVerification;
const { getByTestId, getByText } = await setup(message, messageVerification, false, true);
getByTestId('extra-pin-key:banner');
// Expected text is displayed
getByText('An unknown public key has been detected for this recipient.');
await openTrustKeyModal(getByText);
}
);
});
|
3,605 | 0 | petrpan-code/ProtonMail/WebClients/applications/mail/src/app/components/message | petrpan-code/ProtonMail/WebClients/applications/mail/src/app/components/message/extras/ExtraScheduledMessage.test.tsx | import { act, fireEvent } from '@testing-library/react';
import { addHours, addSeconds } from 'date-fns';
import { MAILBOX_LABEL_IDS } from '@proton/shared/lib/constants';
import { addDays } from '@proton/shared/lib/date-fns-utc';
import { formatDateToHuman } from '../../../helpers/date';
import { addApiMock, clearAll } from '../../../helpers/test/helper';
import { render } from '../../../helpers/test/render';
import { MessageStateWithData } from '../../../logic/messages/messagesTypes';
import ExtraScheduledMessage from './ExtraScheduledMessage';
const getMessage = (sendingDate: Date) => {
return {
localID: '1',
data: {
ID: '1',
Subject: 'Scheduled message subject',
Time: sendingDate.getTime() / 1000,
LabelIDs: [MAILBOX_LABEL_IDS.SENT, MAILBOX_LABEL_IDS.SCHEDULED],
},
} as MessageStateWithData;
};
describe('Scheduled messages banner', () => {
afterEach(clearAll);
it('should show scheduled banner for scheduled messages', async () => {
const sendingDate = addDays(new Date(), 3);
const message = getMessage(sendingDate);
const { getByTestId, getByText } = await render(<ExtraScheduledMessage message={message} />);
const { dateString, formattedTime } = formatDateToHuman(sendingDate);
getByTestId('message:schedule-banner');
getByText(`This message will be sent on ${dateString} at ${formattedTime}`);
getByText('Edit');
});
it('should have text will be sent tomorrow', async () => {
const sendingDate = addDays(new Date(), 1);
const message = getMessage(sendingDate);
const { getByTestId, getByText } = await render(<ExtraScheduledMessage message={message} />);
const { formattedTime } = formatDateToHuman(sendingDate);
getByTestId('message:schedule-banner');
const scheduledBannerText = getByText(`This message will be sent tomorrow at ${formattedTime}`);
expect(scheduledBannerText.innerHTML).toContain('tomorrow');
getByText('Edit');
});
it('should have text will be sent in the morning', async () => {
const aDayInTheMorningDate = new Date(2020, 0, 1, 8, 0, 0);
const dateSpy = jest.spyOn(Date, 'now').mockImplementation(() => aDayInTheMorningDate.setHours(8).valueOf());
const sendingDate = addHours(aDayInTheMorningDate, 3);
const message = getMessage(sendingDate);
const { getByTestId, getByText } = await render(<ExtraScheduledMessage message={message} />);
const { formattedTime } = formatDateToHuman(sendingDate);
getByTestId('message:schedule-banner');
const scheduledBannerText = getByText(`This message will be sent in the morning at ${formattedTime}`);
expect(scheduledBannerText.innerHTML).toContain('in the morning');
getByText('Edit');
dateSpy.mockRestore();
});
it('should have text will be sent today', async () => {
const dateSpy = jest.spyOn(Date, 'now').mockImplementation(() => new Date().setHours(12).valueOf());
const sendingDate = addHours(new Date(Date.now()), 3);
const message = getMessage(sendingDate);
const { getByTestId, getByText } = await render(<ExtraScheduledMessage message={message} />);
const { formattedTime } = formatDateToHuman(sendingDate);
getByTestId('message:schedule-banner');
const scheduledBannerText = getByText(`This message will be sent today at ${formattedTime}`);
expect(scheduledBannerText.innerHTML).toContain('today');
getByText('Edit');
dateSpy.mockRestore();
});
it('should have text will be sent shortly', async () => {
const sendingDate = addSeconds(new Date(), 29);
const message = getMessage(sendingDate);
const { getByTestId, getByText, queryByTestId } = await render(<ExtraScheduledMessage message={message} />);
getByTestId('message:schedule-banner');
getByText(`This message will be sent shortly`);
expect(queryByTestId(`Edit`)).toBeNull();
});
it('should be able to edit the message', async () => {
const sendingDate = addDays(new Date(), 1);
const message = getMessage(sendingDate);
const unscheduleCall = jest.fn();
addApiMock(`mail/v4/messages/${message.data?.ID}/cancel_send`, unscheduleCall);
const { getByTestId, getByText } = await render(<ExtraScheduledMessage message={message} />);
const { formattedTime } = formatDateToHuman(sendingDate);
getByTestId('message:schedule-banner');
getByText(`This message will be sent tomorrow at ${formattedTime}`);
const editButton = getByText('Edit');
// Edit the scheduled message
fireEvent.click(editButton);
getByText('Edit and reschedule');
const editDraftButton = getByText('Edit draft');
await act(async () => {
// Unschedule the message
fireEvent.click(editDraftButton);
});
// Unschedule route is called
expect(unscheduleCall).toHaveBeenCalled();
});
});
|
3,607 | 0 | petrpan-code/ProtonMail/WebClients/applications/mail/src/app/components/message | petrpan-code/ProtonMail/WebClients/applications/mail/src/app/components/message/extras/ExtraSnoozedMessage.test.tsx | import { act, fireEvent } from '@testing-library/react';
import { addHours } from 'date-fns';
import { MAILBOX_LABEL_IDS } from '@proton/shared/lib/constants';
import { addDays } from '@proton/shared/lib/date-fns-utc';
import { formatDateToHuman } from '../../../helpers/date';
import { clearAll } from '../../../helpers/test/helper';
import { render } from '../../../helpers/test/render';
import useSnooze from '../../../hooks/actions/useSnooze';
import { MessageStateWithData } from '../../../logic/messages/messagesTypes';
import ExtraSnoozedMessage from './ExtraSnoozedMessage';
const mockUseGetElementsFromIDs = jest.fn();
jest.mock('../../../hooks/mailbox/useElements', () => ({
useGetElementsFromIDs: () => mockUseGetElementsFromIDs,
}));
jest.mock('../../../hooks/actions/useSnooze', () => ({
__esModule: true,
default: jest.fn().mockReturnValue({
canSnooze: true,
canUnsnooze: true,
isSnoozeEnabled: true,
snooze: jest.fn(),
unsnooze: jest.fn(),
handleClose: jest.fn(),
handleCustomClick: jest.fn(),
snoozeState: 'snooze-selection',
}),
}));
const getMessage = (sendingDate: Date) => {
return {
localID: '1',
data: {
ID: '1',
ConversationID: 'conversation',
Subject: 'Scheduled message subject',
SnoozeTime: sendingDate.getTime() / 1000,
LabelIDs: [MAILBOX_LABEL_IDS.SENT, MAILBOX_LABEL_IDS.SNOOZED],
},
} as MessageStateWithData;
};
describe('Scheduled messages banner', () => {
const useSnoozeMock = useSnooze as jest.Mock;
const useGetElementsFromIDsMock = jest.fn();
afterEach(clearAll);
it('should have text will be sent shortly, the unsnooze button must be hidden', async () => {
const sendingDate = new Date();
const message = getMessage(sendingDate);
const { getByTestId, getByText, queryByText } = await render(<ExtraSnoozedMessage message={message} />);
const { formattedTime } = formatDateToHuman(sendingDate);
getByTestId('message:snooze-banner');
getByText(`Snoozed until today, ${formattedTime}`);
expect(queryByText('Unsnooze')).toBeNull();
});
it('should have text will be sent today', async () => {
const sendingDate = addHours(new Date(), 1);
const message = getMessage(sendingDate);
const { getByTestId, getByText } = await render(<ExtraSnoozedMessage message={message} />);
const { formattedTime } = formatDateToHuman(sendingDate);
getByTestId('message:snooze-banner');
const text = `Snoozed until today, ${formattedTime}`;
getByText(text);
getByText('Unsnooze');
});
it('should have text will be sent tomorrow', async () => {
const sendingDate = addDays(new Date(), 1);
const message = getMessage(sendingDate);
const { getByTestId, getByText } = await render(<ExtraSnoozedMessage message={message} />);
const { formattedTime } = formatDateToHuman(sendingDate);
getByTestId('message:snooze-banner');
getByText(`Snoozed until tomorrow, ${formattedTime}`);
getByText('Unsnooze');
});
it('should have text will be sent in the future', async () => {
const sendingDate = addDays(new Date(), 100);
const message = getMessage(sendingDate);
const { getByTestId, getByText } = await render(<ExtraSnoozedMessage message={message} />);
const { formattedTime, dateString } = formatDateToHuman(sendingDate);
getByTestId('message:snooze-banner');
getByText(`Snoozed until ${dateString} at ${formattedTime}`);
getByText('Unsnooze');
});
it('should call the unsnooze method if has element', async () => {
const sendingDate = addDays(new Date(), 1);
const message = getMessage(sendingDate);
mockUseGetElementsFromIDs.mockReturnValue([{ ID: '1' }]);
const unsnoozeCall = jest.fn();
useSnoozeMock.mockReturnValue({
unsnooze: unsnoozeCall,
});
const { getByTestId, getByText } = await render(<ExtraSnoozedMessage message={message} />);
const { formattedTime } = formatDateToHuman(sendingDate);
getByTestId('message:snooze-banner');
getByText(`Snoozed until tomorrow, ${formattedTime}`);
const editButton = getByText('Unsnooze');
// Edit the snooze message
await act(async () => {
fireEvent.click(editButton);
});
// Unsnooze route is called
expect(unsnoozeCall).toHaveBeenCalled();
});
it('should not call the unsnooze method if has element', async () => {
const sendingDate = addDays(new Date(), 1);
const message = getMessage(sendingDate);
mockUseGetElementsFromIDs.mockReturnValue(undefined);
useGetElementsFromIDsMock.mockReturnValue(undefined);
const unsnoozeCall = jest.fn();
useSnoozeMock.mockReturnValue({
unsnooze: unsnoozeCall,
});
const { getByTestId, getByText } = await render(<ExtraSnoozedMessage message={message} />);
const { formattedTime } = formatDateToHuman(sendingDate);
getByTestId('message:snooze-banner');
getByText(`Snoozed until tomorrow, ${formattedTime}`);
const editButton = getByText('Unsnooze');
// Edit the snooze message
await act(async () => {
fireEvent.click(editButton);
});
// Unsnooze route is called
expect(unsnoozeCall).not.toHaveBeenCalled();
});
});
|
3,610 | 0 | petrpan-code/ProtonMail/WebClients/applications/mail/src/app/components/message | petrpan-code/ProtonMail/WebClients/applications/mail/src/app/components/message/extras/ExtraUnsubscribe.test.tsx | import { fireEvent, screen } from '@testing-library/react';
import loudRejection from 'loud-rejection';
import { openNewTab } from '@proton/shared/lib/helpers/browser';
import { mergeMessages } from '../../../helpers/message/messages';
import { addAddressToCache, minimalCache } from '../../../helpers/test/cache';
import { releaseCryptoProxy, setupCryptoProxyForTesting } from '../../../helpers/test/crypto';
import {
addApiKeys,
addApiMock,
addKeysToAddressKeysCache,
clearAll,
generateKeys,
render,
setFeatureFlags,
waitForEventManagerCall,
waitForNotification,
} from '../../../helpers/test/helper';
import * as useSimpleLoginExtension from '../../../hooks/simpleLogin/useSimpleLoginExtension';
import { MessageStateWithData } from '../../../logic/messages/messagesTypes';
import ExtraUnsubscribe from './ExtraUnsubscribe';
loudRejection();
jest.mock('@proton/shared/lib/helpers/browser', () => ({
isMac: jest.fn(() => false),
openNewTab: jest.fn(),
isMobile: jest.fn(),
isFirefoxLessThan55: jest.fn(),
getIsIframe: jest.fn(() => false),
}));
describe('Unsubscribe banner', () => {
const messageID = 'messageID';
const toAddressID = 'toAddressID';
const toAddress = '[email protected]';
const defaultMessage = {
localID: messageID,
data: { ID: messageID, Subject: 'test', ParsedHeaders: { 'X-Original-To': toAddress }, Attachments: [] } as any,
messageDocument: { initialized: true },
verification: {},
} as MessageStateWithData;
beforeAll(async () => {
await setupCryptoProxyForTesting();
});
afterAll(async () => {
await releaseCryptoProxy();
});
afterEach(clearAll);
it('should show the unsubscribe banner with one click method', async () => {
const unsubscribeCall = jest.fn();
const markUnsubscribedCall = jest.fn();
minimalCache();
addAddressToCache({ Email: toAddress });
addApiMock(`mail/v4/messages/${messageID}/unsubscribe`, unsubscribeCall);
addApiMock(`mail/v4/messages/mark/unsubscribed`, markUnsubscribedCall);
const message = mergeMessages(defaultMessage, {
data: {
UnsubscribeMethods: { OneClick: 'OneClick' },
},
}) as MessageStateWithData;
await render(<ExtraUnsubscribe message={message.data} />, false);
const button = screen.getByTestId('unsubscribe-banner');
expect(button.textContent).toMatch(/Unsubscribe/);
if (button) {
fireEvent.click(button);
}
const submitButton = screen.getByTestId('unsubscribe-banner:submit');
if (submitButton) {
fireEvent.click(submitButton);
}
await waitForEventManagerCall();
expect(unsubscribeCall).toHaveBeenCalled();
expect(markUnsubscribedCall).toHaveBeenCalled();
});
it('should show the unsubscribe banner with mailto method', async () => {
const mailto = '[email protected]';
const keys = await generateKeys('me', toAddress);
const createCall = jest.fn(() => ({ Message: { ID: messageID, Attachments: [] } }));
const sendCall = jest.fn(() => ({ Sent: {} }));
const markUnsubscribedCall = jest.fn();
minimalCache();
addAddressToCache({ ID: toAddressID, Email: toAddress });
addApiKeys(false, mailto, []);
addKeysToAddressKeysCache(toAddressID, keys);
addApiMock(`mail/v4/messages`, createCall);
addApiMock(`mail/v4/messages/messageID`, sendCall);
addApiMock(`mail/v4/messages/mark/unsubscribed`, markUnsubscribedCall);
const message = mergeMessages(defaultMessage, {
data: {
UnsubscribeMethods: { Mailto: { ToList: [mailto], Body: 'body', Subject: 'subject' } },
},
}) as MessageStateWithData;
await render(<ExtraUnsubscribe message={message.data} />, false);
const button = screen.getByTestId('unsubscribe-banner');
expect(button.textContent).toMatch(/Unsubscribe/);
if (button) {
fireEvent.click(button);
}
const submitButton = screen.getByTestId('unsubscribe-banner:submit');
if (submitButton) {
fireEvent.click(submitButton);
}
await waitForNotification('Mail list unsubscribed');
await waitForEventManagerCall();
expect(sendCall).toHaveBeenCalled();
expect(markUnsubscribedCall).toHaveBeenCalled();
});
it('should show the unsubscribe banner with http client method', async () => {
const markUnsubscribedCall = jest.fn();
const openNewTabMock = openNewTab as jest.Mock;
minimalCache();
addAddressToCache({ ID: toAddressID, Email: toAddress });
addApiMock(`mail/v4/messages/mark/unsubscribed`, markUnsubscribedCall);
const message = mergeMessages(defaultMessage, {
data: {
UnsubscribeMethods: { HttpClient: 'url' },
},
}) as MessageStateWithData;
await render(<ExtraUnsubscribe message={message.data} />, false);
const button = screen.getByTestId('unsubscribe-banner');
expect(button.textContent).toMatch(/Unsubscribe/);
if (button) {
fireEvent.click(button);
}
const submitButton = screen.getByTestId('unsubscribe-banner:submit');
if (submitButton) {
fireEvent.click(submitButton);
}
await waitForEventManagerCall();
expect(openNewTabMock).toHaveBeenCalled();
expect(markUnsubscribedCall).toHaveBeenCalled();
});
it('should show an extra modal when the user has no SimpleLogin extension', async () => {
setFeatureFlags('SLIntegration', true);
jest.spyOn(useSimpleLoginExtension, 'useSimpleLoginExtension').mockReturnValue({
hasSimpleLogin: false,
hasSLExtension: false,
canUseExtension: true,
hasAccountLinked: true,
isFetchingAccountLinked: true,
});
const unsubscribeCall = jest.fn();
const markUnsubscribedCall = jest.fn();
minimalCache();
addAddressToCache({ Email: toAddress });
addApiMock(`mail/v4/messages/${messageID}/unsubscribe`, unsubscribeCall);
addApiMock(`mail/v4/messages/mark/unsubscribed`, markUnsubscribedCall);
const message = mergeMessages(defaultMessage, {
data: {
UnsubscribeMethods: { OneClick: 'OneClick' },
},
}) as MessageStateWithData;
await render(<ExtraUnsubscribe message={message.data} />, false);
const button = screen.getByTestId('unsubscribe-banner');
expect(button.textContent).toMatch(/Unsubscribe/);
if (button) {
fireEvent.click(button);
}
// Submit first modal
const submitButton = screen.getByTestId('unsubscribe-banner:submit');
if (submitButton) {
fireEvent.click(submitButton);
}
// Second modal should be opened
screen.getByText('hide-my-email aliases');
});
it('should not show an extra modal when the user has SimpleLogin extension', async () => {
setFeatureFlags('SLIntegration', true);
jest.spyOn(useSimpleLoginExtension, 'useSimpleLoginExtension').mockReturnValue({
hasSimpleLogin: true,
hasSLExtension: true,
canUseExtension: true,
hasAccountLinked: true,
isFetchingAccountLinked: true,
});
const unsubscribeCall = jest.fn();
const markUnsubscribedCall = jest.fn();
minimalCache();
addAddressToCache({ Email: toAddress });
addApiMock(`mail/v4/messages/${messageID}/unsubscribe`, unsubscribeCall);
addApiMock(`mail/v4/messages/mark/unsubscribed`, markUnsubscribedCall);
const message = mergeMessages(defaultMessage, {
data: {
UnsubscribeMethods: { OneClick: 'OneClick' },
},
}) as MessageStateWithData;
await render(<ExtraUnsubscribe message={message.data} />, false);
const button = screen.getByTestId('unsubscribe-banner');
expect(button.textContent).toMatch(/Unsubscribe/);
if (button) {
fireEvent.click(button);
}
// Submit first modal
const submitButton = screen.getByTestId('unsubscribe-banner:submit');
if (submitButton) {
fireEvent.click(submitButton);
}
// Second modal should not be opened
expect(screen.queryByText('hide-my-email aliases')).toBeNull();
});
it('should not show an extra modal when the user has no SimpleLogin extension but the message is from SimpleLogin', async () => {
setFeatureFlags('SLIntegration', true);
jest.spyOn(useSimpleLoginExtension, 'useSimpleLoginExtension').mockReturnValue({
hasSimpleLogin: false,
hasSLExtension: false,
canUseExtension: true,
hasAccountLinked: true,
isFetchingAccountLinked: true,
});
const unsubscribeCall = jest.fn();
const markUnsubscribedCall = jest.fn();
minimalCache();
addAddressToCache({ Email: toAddress });
addApiMock(`mail/v4/messages/${messageID}/unsubscribe`, unsubscribeCall);
addApiMock(`mail/v4/messages/mark/unsubscribed`, markUnsubscribedCall);
const message = mergeMessages(defaultMessage, {
data: {
UnsubscribeMethods: { OneClick: 'OneClick' },
Sender: { Address: '[email protected]', Name: 'SimpleLoginAlias', IsSimpleLogin: 1 },
},
}) as MessageStateWithData;
await render(<ExtraUnsubscribe message={message.data} />, false);
const button = screen.getByTestId('unsubscribe-banner');
expect(button.textContent).toMatch(/Unsubscribe/);
if (button) {
fireEvent.click(button);
}
// Submit first modal
const submitButton = screen.getByTestId('unsubscribe-banner:submit');
if (submitButton) {
fireEvent.click(submitButton);
}
// Second modal should not be opened
expect(screen.queryByText('hide-my-email aliases')).toBeNull();
});
it('should not show an extra modal when the message was coming from an official Proton address', async () => {
const unsubscribeCall = jest.fn();
const markUnsubscribedCall = jest.fn();
minimalCache();
addAddressToCache({ Email: toAddress });
addApiMock(`mail/v4/messages/${messageID}/unsubscribe`, unsubscribeCall);
addApiMock(`mail/v4/messages/mark/unsubscribed`, markUnsubscribedCall);
const message = mergeMessages(defaultMessage, {
data: {
UnsubscribeMethods: { OneClick: 'OneClick' },
Sender: { Address: '[email protected]', Name: 'SimpleLoginAlias', IsProton: 1 },
},
}) as MessageStateWithData;
await render(<ExtraUnsubscribe message={message.data} />, false);
const button = screen.getByTestId('unsubscribe-banner');
expect(button.textContent).toMatch(/Unsubscribe/);
if (button) {
fireEvent.click(button);
}
// Submit first modal
const submitButton = screen.getByTestId('unsubscribe-banner:submit');
if (submitButton) {
fireEvent.click(submitButton);
}
// Second modal should not be opened
expect(screen.queryByText('hide-my-email aliases')).toBeNull();
});
});
|
3,613 | 0 | petrpan-code/ProtonMail/WebClients/applications/mail/src/app/components/message/extras | petrpan-code/ProtonMail/WebClients/applications/mail/src/app/components/message/extras/calendar/EmailReminderWidget.test.tsx | import { BrowserRouter } from 'react-router-dom';
import { fireEvent, render, screen, waitFor } from '@testing-library/react';
import { mocked } from 'jest-mock';
import { FeaturesProvider, useAddresses, useUserSettings } from '@proton/components';
import AuthenticationProvider from '@proton/components/containers/authentication/Provider';
import { CacheProvider } from '@proton/components/containers/cache';
import { DrawerProvider } from '@proton/components/hooks/drawer/useDrawer';
import useApi from '@proton/components/hooks/useApi';
import useGetCalendarEventRaw from '@proton/components/hooks/useGetCalendarEventRaw';
import useNotifications from '@proton/components/hooks/useNotifications';
import { CALENDAR_APP_NAME } from '@proton/shared/lib/constants';
import { addDays } from '@proton/shared/lib/date-fns-utc';
import { toUTCDate } from '@proton/shared/lib/date/timezone';
import createCache from '@proton/shared/lib/helpers/cache';
import { DRAWER_VISIBILITY, Nullable, UserSettings } from '@proton/shared/lib/interfaces';
import { VERIFICATION_STATUS } from '@proton/srp/lib/constants';
import {
addressBuilder,
calendarBuilder,
calendarEventBuilder,
messageBuilder,
mockApiWithServer,
mockNotifications,
rest,
server,
veventBuilder,
} from '@proton/testing';
import { refresh } from 'proton-mail/logic/contacts/contactsActions';
import { store } from 'proton-mail/logic/store';
import { ReduxProviderWrapper, authentication, tick } from '../../../../helpers/test/render';
import EmailReminderWidget from './EmailReminderWidget';
jest.mock('@proton/components/hooks/useNotifications');
jest.mock('@proton/components/hooks/useModals');
jest.mock('@proton/components/hooks/useApi');
jest.mock('@proton/components/hooks/useGetCalendarEventRaw');
jest.mock('@proton/components/hooks/useAddresses');
jest.mock('@proton/components/hooks/useUserSettings');
jest.mock('./EventReminderText', () => ({
__esModule: true,
default: jest.fn(() => <span>EventReminderText</span>),
}));
jest.mock('@proton/components/components/calendarEventDateHeader/CalendarEventDateHeader', () => ({
__esModule: true,
default: jest.fn(() => <span>DateHeader</span>),
}));
jest.mock('@proton/components/hooks/useConfig', () => () => ({ APP_NAME: 'proton-calendar', APP_VERSION: 'test' }));
// Force narrow mode for "renders the widget and the necessary information" so that we can see the link
// With the drawer we do not have a AppLink anymore, we will open Calendar in the drawer directly
jest.mock('@proton/components/hooks/useActiveBreakpoint', () => () => {
return {
isNarrow: true,
};
});
jest.mock('@proton/components/hooks/useUser', () => ({
__esModule: true,
default: jest.fn(() => [
[
{
ID: 'id',
},
],
]),
useGetUser: jest.fn(
() => () =>
Promise.resolve([
[
{
ID: 'id',
},
],
])
),
}));
jest.mock('@proton/components/hooks/useMailSettings', () => ({
useMailSettings: jest.fn(() => [{}, false]),
}));
const mockedUseApi = mocked(useApi);
const mockedUseNotifications = mocked(useNotifications);
const mockedUseGetCalendarEventRaw = mocked(useGetCalendarEventRaw);
const mockedUseAddresses = mocked(useAddresses);
const mockedUserSettings = mocked(useUserSettings);
function renderComponent(overrides?: any) {
window.history.pushState({}, 'Calendar', '/');
const Wrapper = ({ children }: any) => (
<AuthenticationProvider store={authentication}>
<CacheProvider cache={createCache()}>
<FeaturesProvider>
<DrawerProvider>
<ReduxProviderWrapper>
<BrowserRouter>{children}</BrowserRouter>
</ReduxProviderWrapper>
</DrawerProvider>
</FeaturesProvider>
</CacheProvider>
</AuthenticationProvider>
);
return {
...render(<EmailReminderWidget message={messageBuilder({ overrides })} />, { wrapper: Wrapper }),
skeleton: screen.queryByTestId('calendar-widget-widget-skeleton') as HTMLDivElement,
};
}
describe('EmailReminderWidget', () => {
beforeAll(() => {
// Initialize contactsMap
store.dispatch(refresh({ contacts: [], contactGroups: [] }));
server.listen();
});
afterAll(() => server.close());
beforeEach(() => {
mockedUseApi.mockImplementation(() => mockApiWithServer);
mockedUseNotifications.mockImplementation(() => mockNotifications);
});
afterEach(() => {
server.resetHandlers();
jest.clearAllMocks();
});
beforeEach(() => {
mockedUseGetCalendarEventRaw.mockImplementation(
() => () =>
Promise.resolve({
verificationStatus: VERIFICATION_STATUS.SIGNED_AND_VALID,
hasDefaultNotifications: true,
selfAddressData: { isOrganizer: false, isAttendee: false },
veventComponent: veventBuilder(),
encryptionData: {
encryptingAddressID: undefined,
sharedSessionKey: undefined,
calendarSessionKey: undefined,
},
})
);
mockedUseAddresses.mockImplementation(() => [[addressBuilder({})], false, null]);
mockedUserSettings.mockImplementation(() => [
{ HideSidePanel: DRAWER_VISIBILITY.HIDE } as UserSettings,
false,
{} as Error,
]);
server.use(
rest.get(`/core/v4/features`, (req, res, ctx) => {
return res.once(ctx.json({}));
})
);
});
it('does not render anything when necessary headers are not present', () => {
const { container } = renderComponent({ ParsedHeaders: {} });
expect(container).toBeEmptyDOMElement();
});
it('renders the widget and the necessary information', async () => {
const { skeleton } = renderComponent();
expect(skeleton).toBeInTheDocument();
await waitFor(() => {
expect(screen.getByText(/DateHeader/)).toBeInTheDocument();
});
await tick();
expect((screen.getByText(new RegExp(`Open in ${CALENDAR_APP_NAME}`)) as HTMLAnchorElement).href).toBe(
`http://localhost/event?Action=VIEW&EventID=${encodeURIComponent(
calendarEventBuilder().ID
)}&CalendarID=${encodeURIComponent(calendarBuilder().ID)}&RecurrenceID=${encodeURIComponent(
`${messageBuilder()?.ParsedHeaders['X-Pm-Calendar-Occurrence']}`
)}`
);
expect(screen.getByText(veventBuilder().summary!.value)).toBeInTheDocument();
expect(screen.getByText(veventBuilder().location!.value)).toBeInTheDocument();
expect(screen.getByText(/Organizer/)).toBeInTheDocument();
expect(screen.getByText(/EventReminderText/)).toBeInTheDocument();
fireEvent.click(screen.getByRole(/button/));
expect(screen.getByText(/[email protected]/)).toBeInTheDocument();
expect(screen.getByText(/[email protected]/)).toBeInTheDocument();
});
it('renders the widget when the event has been cancelled', async () => {
server.use(
rest.get(`/calendar/v1/:calendarId/events/:eventId`, (req, res, ctx) => {
return res.once(
ctx.json({
Event: calendarEventBuilder({
traits: 'canceled',
}),
})
);
})
);
const { skeleton } = renderComponent();
expect(skeleton).toBeInTheDocument();
await screen.findByText(/Event was canceled/);
await tick();
expect(screen.queryByText(new RegExp(`Open in ${CALENDAR_APP_NAME}`))).toBeInTheDocument();
});
it('displays an error instead of the widget when there has been a breaking change', async () => {
mockedUseGetCalendarEventRaw.mockImplementation(
() => () =>
Promise.resolve({
verificationStatus: VERIFICATION_STATUS.SIGNED_AND_VALID,
hasDefaultNotifications: true,
selfAddressData: { isOrganizer: false, isAttendee: false },
veventComponent: veventBuilder({ overrides: { sequence: { value: 2 } } }),
encryptionData: {
encryptingAddressID: undefined,
sharedSessionKey: undefined,
calendarSessionKey: undefined,
},
})
);
const { skeleton } = renderComponent();
expect(skeleton).toBeInTheDocument();
await screen.findByText(/Event was updated. This reminder is out-of-date./);
expect(screen.queryByText(new RegExp(`Open in ${CALENDAR_APP_NAME}`))).not.toBeInTheDocument();
});
it('displays an error instead of the widget when the event does not exist anymore', async () => {
server.use(
rest.get(`/calendar/v1/:calendarId/events/:eventId`, (req, res, ctx) => {
return res.once(ctx.status(404));
})
);
const { skeleton } = renderComponent();
expect(skeleton).toBeInTheDocument();
await screen.findByText(new RegExp('Event is no longer in your calendar'));
expect(screen.queryByText(new RegExp(`Open in ${CALENDAR_APP_NAME}`))).not.toBeInTheDocument();
});
describe('decryption error', () => {
beforeEach(() => {
mockedUseGetCalendarEventRaw.mockImplementation(
// eslint-disable-next-line prefer-promise-reject-errors
() => () => Promise.reject({ message: 'DECRYPTION_FAILED' })
);
});
describe('needs user action', () => {
async function displaysErrorWithoutButtonInsteadOfWidget() {
const { skeleton } = renderComponent();
expect(skeleton).toBeInTheDocument();
await screen.findByText(
/Event details are encrypted. Sign in again to restore Calendar and decrypt your data./
);
expect(screen.queryByText(new RegExp(`Open in ${CALENDAR_APP_NAME}`))).not.toBeInTheDocument();
expect(screen.queryByText(/Learn more/)).toBeInTheDocument();
expect(screen.queryByText(new RegExp(`Open ${CALENDAR_APP_NAME}`))).toBeInTheDocument();
}
it('displays an error instead of the widget when the calendar needs a reset', async () => {
server.use(
rest.get(`/calendar/v1`, (req, res, ctx) => {
return res.once(
ctx.json({
Calendars: [calendarBuilder({ traits: 'resetNeeded' })],
})
);
})
);
await displaysErrorWithoutButtonInsteadOfWidget();
});
it('displays an error instead of the widget when the calendar needs a passphrase update', async () => {
const calendar = calendarBuilder({ traits: 'updatePassphrase' });
server.use(
rest.get(`/calendar/v1`, (req, res, ctx) => {
return res.once(
ctx.json({
Calendars: [calendar],
})
);
}),
rest.get(`/calendar/v1/${calendar.ID}/keys/all`, (req, res, ctx) => {
return res.once(ctx.json({}));
}),
rest.get(`/calendar/v1/${calendar.ID}/passphrases`, (req, res, ctx) => {
return res.once(ctx.json({}));
}),
rest.get(`/calendar/v1/${calendar.ID}/members`, (req, res, ctx) => {
return res.once(ctx.json({}));
})
);
await displaysErrorWithoutButtonInsteadOfWidget();
});
});
describe('does not need user action', () => {
it('displays an error instead of the widget when the event cannot be decrypted', async () => {
const { skeleton } = renderComponent();
expect(skeleton).toBeInTheDocument();
await screen.findByText(new RegExp('Event details cannot be decrypted.'));
expect(screen.queryByText(new RegExp(`Open in ${CALENDAR_APP_NAME}`))).not.toBeInTheDocument();
expect(screen.queryByText(new RegExp('Why not?'))).toBeInTheDocument();
});
});
});
async function errorAndNoWidget(skeleton: Nullable<HTMLDivElement>) {
expect(skeleton).toBeInTheDocument();
await screen.findByText(/Event is no longer in your calendar/);
expect(screen.queryByText(/DateHeader/)).not.toBeInTheDocument();
}
it('displays an error and no widget if the `until` is expired', async () => {
mockedUseGetCalendarEventRaw.mockImplementation(
() => () =>
Promise.resolve({
hasDefaultNotifications: true,
verificationStatus: VERIFICATION_STATUS.SIGNED_AND_VALID,
selfAddressData: { isOrganizer: false, isAttendee: false },
veventComponent: {
...veventBuilder(),
// override manually as overrides does not work for undefined properties in the builder
rrule: {
value: {
freq: 'DAILY',
until: {
...veventBuilder().dtstart.value,
day: addDays(toUTCDate(veventBuilder().dtstart.value), -1).getDate(),
},
},
},
},
encryptionData: {
encryptingAddressID: undefined,
sharedSessionKey: undefined,
calendarSessionKey: undefined,
},
})
);
const { skeleton } = renderComponent();
await errorAndNoWidget(skeleton);
});
it('displays an error and no widget if the count is not matched', async () => {
mockedUseGetCalendarEventRaw.mockImplementation(
() => () =>
Promise.resolve({
hasDefaultNotifications: true,
verificationStatus: VERIFICATION_STATUS.SIGNED_AND_VALID,
selfAddressData: { isOrganizer: false, isAttendee: false },
veventComponent: {
...veventBuilder(),
// override manually as overrides does not work for undefined properties in the builder
rrule: {
value: {
freq: 'DAILY',
count: 1,
},
},
},
encryptionData: {
encryptingAddressID: undefined,
sharedSessionKey: undefined,
calendarSessionKey: undefined,
},
})
);
const { skeleton } = renderComponent({
ParsedHeaders: {
...messageBuilder().ParsedHeaders,
'X-Pm-Calendar-Occurrence': `${new Date(2050, 12, 12).getTime() / 1000}`,
},
});
await errorAndNoWidget(skeleton);
});
it('displays an error and no widget if the occurrence is in exdates (the occurrence has been removed from the chain)', async () => {
server.use(
rest.get(`/calendar/v1/events`, (req, res, ctx) => {
return res.once(
ctx.json({
Events: [calendarEventBuilder(), { Exdates: [123] }],
})
);
})
);
const { skeleton } = renderComponent({
ParsedHeaders: {
...messageBuilder().ParsedHeaders,
'X-Pm-Calendar-Eventisrecurring': '1',
'X-Pm-Calendar-Occurrence': '123',
'X-Pm-Calendar-Calendarid': '321',
},
});
await errorAndNoWidget(skeleton);
});
it('displays an error and no widget if there are no events found with recurring header', async () => {
server.use(
rest.get(`/calendar/v1/events`, (req, res, ctx) => {
return res.once(
ctx.json({
Events: [],
})
);
})
);
const { skeleton } = renderComponent({
ParsedHeaders: {
...messageBuilder().ParsedHeaders,
'X-Pm-Calendar-Eventisrecurring': '1',
},
});
await errorAndNoWidget(skeleton);
});
it('displays an error and no widget if there are no events found with the first event API call fails', async () => {
server.use(
rest.get(`/calendar/v1/:calendarId/events/:eventId`, () => {
throw new Error('Anything can happen');
})
);
server.use(
rest.get(`/calendar/v1/events`, (req, res, ctx) => {
return res.once(
ctx.json({
Events: [],
})
);
})
);
const { skeleton } = renderComponent();
await errorAndNoWidget(skeleton);
});
it('falls back to calling by uid in case the main api call fails', async () => {
server.use(
rest.get(`/calendar/v1/:calendarId/events/:eventId`, () => {
throw new Error('Anything can happen');
})
);
server.use(
rest.get(`/calendar/v1/events`, (req, res, ctx) => {
return res.once(
ctx.json({
Events: [calendarEventBuilder()],
})
);
})
);
const { skeleton } = renderComponent();
expect(skeleton).toBeInTheDocument();
await screen.findByText(/DateHeader/);
});
it('displays a generic error when both event API calls fail', async () => {
server.use(
rest.get(`/calendar/v1/:calendarId/events/:eventId`, () => {
throw new Error('Anything can happen');
})
);
server.use(
rest.get(`/calendar/v1/events`, () => {
throw new Error('Anything can happen in the fallback');
})
);
const { skeleton } = renderComponent();
expect(skeleton).toBeInTheDocument();
await waitFor(() => expect(screen.queryByText(/DateHeader/)).not.toBeInTheDocument());
expect(mockedUseNotifications().createNotification).toHaveBeenCalledWith({
type: 'error',
text: expect.stringContaining('Anything can happen in the fallback'),
});
});
});
|
3,617 | 0 | petrpan-code/ProtonMail/WebClients/applications/mail/src/app/components/message/extras | petrpan-code/ProtonMail/WebClients/applications/mail/src/app/components/message/extras/calendar/EventReminderText.test.tsx | import { render, screen } from '@testing-library/react';
import EventReminderText, { EventReminderTextProps } from './EventReminderText';
function renderComponent(props?: Partial<EventReminderTextProps>) {
const defaultProps = {
startDate: new Date(1969, 11, 31, 8, 9, 10),
endDate: new Date(1969, 11, 31, 8, 9, 10),
isAllDay: false,
};
return <EventReminderText {...defaultProps} {...props} />;
}
describe('EventReminderText', () => {
const fakeNow = new Date(1969, 11, 31, 7, 58, 10);
beforeEach(() => {
jest.useFakeTimers().setSystemTime(fakeNow.getTime());
});
afterEach(() => {
jest.clearAllTimers();
});
it('displays the time remaining until event', () => {
const { rerender } = render(renderComponent());
expect(screen.getByText(/Event starts in 11 minutes/)).toBeInTheDocument();
rerender(
renderComponent({
isAllDay: true,
startDate: new Date(1970, 0, 1),
endDate: new Date(1970, 0, 2),
})
);
expect(screen.getByText(/Event is tomorrow/)).toBeInTheDocument();
rerender(
renderComponent({
isAllDay: true,
startDate: new Date(1970, 0, 1),
endDate: new Date(1970, 0, 3),
})
);
expect(screen.getByText(/Event starts tomorrow/)).toBeInTheDocument();
});
it('displays an alert for events starting now', () => {
const { rerender } = render(
renderComponent({
startDate: new Date(1969, 11, 31, 7, 58, 30),
endDate: new Date(1969, 11, 31, 8, 9, 10),
isAllDay: false,
})
);
expect(screen.getByText(/Event starting now/)).toBeInTheDocument();
rerender(
renderComponent({
startDate: new Date(1969, 11, 31, 7, 58, 0),
endDate: new Date(1969, 11, 31, 8, 9, 10),
isAllDay: false,
})
);
expect(screen.getByText(/Event in progress/)).toBeInTheDocument();
});
it('displays an alert for events that already happened', () => {
const { rerender } = render(
renderComponent({
startDate: new Date(1969, 11, 31, 5, 9, 10),
endDate: new Date(1969, 11, 31, 6, 8, 10),
})
);
expect(screen.getByText(/Event already ended/)).toBeInTheDocument();
const endedEventCommonProps = {
isAllDay: true,
start: new Date(1969, 10, 11),
};
rerender(
renderComponent({
...endedEventCommonProps,
endDate: new Date(1969, 10, 12),
})
);
expect(screen.getByText(/Event already ended/)).toBeInTheDocument();
});
it('displays an alert for ongoing events', () => {
const { rerender } = render(
renderComponent({
startDate: new Date(1969, 11, 31, 6, 58, 10),
endDate: new Date(1969, 11, 31, 8, 58, 10),
})
);
expect(screen.getByText(/Event in progress/)).toBeInTheDocument();
rerender(
renderComponent({
isAllDay: true,
startDate: new Date(1969, 11, 31),
endDate: new Date(1970, 0, 1),
})
);
expect(screen.getByText(/Event in progress/)).toBeInTheDocument();
});
it('does not display anything when out of range', () => {
const { container, rerender } = render(
renderComponent({
startDate: new Date(1969, 11, 31, 9, 9, 10),
endDate: new Date(1969, 11, 31, 9, 9, 10),
})
);
expect(container).toBeEmptyDOMElement();
rerender(
renderComponent({
isAllDay: true,
startDate: new Date(1970, 0, 2),
endDate: new Date(1970, 0, 3),
})
);
expect(container).toBeEmptyDOMElement();
});
});
|
3,630 | 0 | petrpan-code/ProtonMail/WebClients/applications/mail/src/app/components/message/extras | petrpan-code/ProtonMail/WebClients/applications/mail/src/app/components/message/extras/calendar/ExtraEventSummary.test.tsx | import { render, screen } from '@testing-library/react';
import { ICAL_ATTENDEE_STATUS, ICAL_EVENT_STATUS, ICAL_METHOD } from '@proton/shared/lib/calendar/constants';
import { Participant, VcalDateProperty, VcalVeventComponent } from '@proton/shared/lib/interfaces/calendar';
import { calendarEventBuilder, veventBuilder } from '@proton/testing';
import { EVENT_TIME_STATUS, InvitationModel, UPDATE_ACTION } from '../../../../helpers/calendar/invite';
import ExtraEventSummary from './ExtraEventSummary';
const dummyRecurrenceID: VcalDateProperty = {
value: {
year: 2020,
month: 2,
day: 2,
},
parameters: {
type: 'date',
},
};
const getAttendee = (partstat = ICAL_ATTENDEE_STATUS.NEEDS_ACTION) => ({
vcalComponent: { value: '[email protected]' },
name: 'test',
emailAddress: '[email protected]',
displayName: 'test',
displayEmail: '[email protected]',
partstat,
});
function renderComponent({
vevent,
method = ICAL_METHOD.REPLY,
attendee,
props,
}: {
vevent?: Partial<VcalVeventComponent>;
attendee?: Participant;
method?: ICAL_METHOD;
props?: Partial<InvitationModel>;
}) {
const model = {
isImport: false,
isOrganizerMode: false,
hasMultipleVevents: false,
hasProtonUID: true,
timeStatus: EVENT_TIME_STATUS.FUTURE,
isAddressActive: true,
isAddressDisabled: false,
canCreateCalendar: true,
maxUserCalendarsDisabled: false,
hasNoCalendars: false,
hideSummary: false,
invitationIcs: {
vevent: {
component: 'vevent' as const,
uid: { value: 'uid' },
dtstamp: {
value: {
year: 2020,
month: 2,
day: 2,
hours: 2,
minutes: 2,
seconds: 2,
isUTC: true,
},
},
dtstart: {
value: {
year: 2020,
month: 2,
day: 2,
hours: 2,
minutes: 2,
seconds: 2,
isUTC: true,
},
},
attendee: [{ value: '[email protected]' }],
...vevent,
},
method,
attendee,
},
...props,
};
return render(<ExtraEventSummary model={model} />);
}
describe('ExtraEventSummary', () => {
it('displays nothing when importing', () => {
const { container } = renderComponent({
props: { isImport: true },
attendee: getAttendee(),
});
expect(container).toBeEmptyDOMElement();
});
it('displays nothing when hideSummary is set', () => {
const { container } = renderComponent({
props: { hideSummary: true },
attendee: getAttendee(),
});
expect(container).toBeEmptyDOMElement();
});
describe('Attendee mode', () => {
describe('method: request', () => {
describe('outdated event', () => {
it('displays nothing when there is no event from api', () => {
const { container } = renderComponent({
props: { isOutdated: true },
attendee: getAttendee(),
method: ICAL_METHOD.REQUEST,
});
expect(container).toBeEmptyDOMElement();
});
it('displays a cancellation message when the status is canceled', () => {
renderComponent({
props: {
isOutdated: true,
invitationApi: {
vevent: veventBuilder({
overrides: { status: { value: ICAL_EVENT_STATUS.CANCELLED } },
}),
calendarEvent: calendarEventBuilder(),
},
},
attendee: getAttendee(),
method: ICAL_METHOD.REQUEST,
});
expect(
screen.getByText(/This invitation is out of date. The event has been canceled./)
).toBeInTheDocument();
});
it('displays an out of date message when the event is out of date', () => {
renderComponent({
props: {
isOutdated: true,
invitationApi: {
vevent: veventBuilder(),
calendarEvent: calendarEventBuilder(),
},
},
attendee: getAttendee(),
method: ICAL_METHOD.REQUEST,
});
expect(
screen.getByText(/This invitation is out of date. The event has been updated./)
).toBeInTheDocument();
});
});
describe('has been updated text', () => {
it('displays the updated text for partstat keep update action', () => {
renderComponent({
props: {
updateAction: UPDATE_ACTION.KEEP_PARTSTAT,
invitationApi: {
vevent: veventBuilder(),
calendarEvent: calendarEventBuilder(),
},
},
attendee: getAttendee(ICAL_ATTENDEE_STATUS.ACCEPTED),
method: ICAL_METHOD.REQUEST,
});
expect(screen.getByText(/This event has been updated./)).toBeInTheDocument();
});
it('displays the updated text for partstat reset update action', () => {
renderComponent({
props: {
updateAction: UPDATE_ACTION.RESET_PARTSTAT,
invitationApi: {
vevent: veventBuilder(),
calendarEvent: calendarEventBuilder(),
},
},
attendee: getAttendee(ICAL_ATTENDEE_STATUS.ACCEPTED),
method: ICAL_METHOD.REQUEST,
});
expect(screen.getByText(/This event has been updated./)).toBeInTheDocument();
});
});
it('displays nothing when there is no event from api', () => {
const { container } = renderComponent({
attendee: getAttendee(),
method: ICAL_METHOD.REQUEST,
});
expect(container).toBeEmptyDOMElement();
});
it('displays nothing when the partstat is "needs action"', () => {
const { container } = renderComponent({
props: {
invitationApi: {
vevent: veventBuilder(),
calendarEvent: calendarEventBuilder(),
},
},
attendee: getAttendee(ICAL_ATTENDEE_STATUS.NEEDS_ACTION),
method: ICAL_METHOD.REQUEST,
});
expect(container).toBeEmptyDOMElement();
});
it('displays accepted message when the partstat is accepted', () => {
renderComponent({
props: {
invitationApi: {
vevent: veventBuilder(),
calendarEvent: calendarEventBuilder(),
},
},
attendee: getAttendee(ICAL_ATTENDEE_STATUS.ACCEPTED),
method: ICAL_METHOD.REQUEST,
});
expect(screen.getByText(/You already accepted this invitation./)).toBeInTheDocument();
});
it('displays declined message when the partstat is declined', () => {
renderComponent({
props: {
invitationApi: {
vevent: veventBuilder(),
calendarEvent: calendarEventBuilder(),
},
},
attendee: getAttendee(ICAL_ATTENDEE_STATUS.DECLINED),
method: ICAL_METHOD.REQUEST,
});
expect(screen.getByText(/You already declined this invitation./)).toBeInTheDocument();
});
it('displays tentatively accepted message when the partstat is tentatively accepted', () => {
renderComponent({
props: {
invitationApi: {
vevent: veventBuilder(),
calendarEvent: calendarEventBuilder(),
},
},
attendee: getAttendee(ICAL_ATTENDEE_STATUS.TENTATIVE),
method: ICAL_METHOD.REQUEST,
});
expect(screen.getByText(/You already tentatively accepted this invitation./)).toBeInTheDocument();
});
});
describe('method: cancel', () => {
it('displays the canceled message when the method is cancel', () => {
renderComponent({
attendee: getAttendee(),
method: ICAL_METHOD.CANCEL,
});
expect(screen.getByText(/This event has been canceled./)).toBeInTheDocument();
});
});
describe('method: add', () => {
it('displays the out of date message when there is no vevent from api', () => {
renderComponent({
attendee: getAttendee(),
method: ICAL_METHOD.ADD,
});
expect(
screen.getByText(/This invitation is out of date. The event has been deleted./)
).toBeInTheDocument();
});
it('displays the deletion message when there is no vevent from api', () => {
renderComponent({
attendee: getAttendee(),
method: ICAL_METHOD.ADD,
});
expect(
screen.getByText(/This invitation is out of date. The event has been deleted./)
).toBeInTheDocument();
});
describe('outdated event', () => {
it('displays the cancellation message when the outdated event has a canceled status', () => {
renderComponent({
props: {
invitationApi: {
vevent: veventBuilder({
overrides: { status: { value: ICAL_EVENT_STATUS.CANCELLED } },
}),
calendarEvent: calendarEventBuilder(),
},
isOutdated: true,
},
attendee: getAttendee(),
method: ICAL_METHOD.ADD,
});
expect(
screen.getByText(/This invitation is out of date. The event has been canceled./)
).toBeInTheDocument();
});
it('displays the outdated message when the invitation is outdated', () => {
renderComponent({
props: {
invitationApi: {
vevent: veventBuilder(),
calendarEvent: calendarEventBuilder(),
},
isOutdated: true,
},
attendee: getAttendee(),
method: ICAL_METHOD.ADD,
});
expect(
screen.getByText(/This invitation is out of date. The event has been updated./)
).toBeInTheDocument();
});
});
it('does not display the occurrence added message when the event is not outdated and is available from the API', () => {
renderComponent({
props: {
invitationApi: {
vevent: veventBuilder(),
calendarEvent: calendarEventBuilder(),
},
},
attendee: getAttendee(),
method: ICAL_METHOD.ADD,
});
expect(
screen.queryByText(/An occurrence has been added to the event \(no title\)/)
).not.toBeInTheDocument();
});
});
});
describe('Organizer mode', () => {
it('displays nothing when there are no attendees', () => {
const { container } = renderComponent({
props: { isOrganizerMode: true },
});
expect(container).toBeEmptyDOMElement();
});
describe('method: reply', () => {
it('displays nothing when the attendee has no partstat', () => {
const attendee = getAttendee();
// If somehow the attendee doesn't have a partstat
// @ts-ignore
delete attendee.partstat;
const { container } = renderComponent({
props: { isOrganizerMode: true },
attendee,
});
expect(container).toBeEmptyDOMElement();
});
describe('no event from api', () => {
it('displays the no calendars message when there are no calendars', () => {
renderComponent({
props: { isOrganizerMode: true, hasNoCalendars: true },
attendee: getAttendee(),
});
expect(
screen.getByText(/This response is out of date. You have no calendars./)
).toBeInTheDocument();
});
describe('decryption error', () => {
describe('partstat: accepted', () => {
it('displays the accepted message when the event was accepted', () => {
renderComponent({
props: { isOrganizerMode: true, hasDecryptionError: true },
attendee: getAttendee(ICAL_ATTENDEE_STATUS.ACCEPTED),
});
expect(screen.getByText(/test accepted your invitation./)).toBeInTheDocument();
});
it('displays the partycrasher accepted message when the event was accepted', () => {
renderComponent({
props: { isOrganizerMode: true, hasDecryptionError: true, isPartyCrasher: true },
attendee: getAttendee(ICAL_ATTENDEE_STATUS.ACCEPTED),
});
expect(screen.getByText(/test accepted an invitation to this event./)).toBeInTheDocument();
});
});
describe('partstat: declined', () => {
it('displays the declined message when the event was declined', () => {
renderComponent({
props: { isOrganizerMode: true, hasDecryptionError: true },
attendee: getAttendee(ICAL_ATTENDEE_STATUS.DECLINED),
});
expect(screen.getByText(/test declined your invitation./)).toBeInTheDocument();
});
it('displays the partycrasher declined message when the event was declined', () => {
renderComponent({
props: { isOrganizerMode: true, hasDecryptionError: true, isPartyCrasher: true },
attendee: getAttendee(ICAL_ATTENDEE_STATUS.DECLINED),
});
expect(screen.getByText(/test declined an invitation to this event./)).toBeInTheDocument();
});
});
describe('partstat: tentative', () => {
it('displays the tentative message when the event was accepted tentatively', () => {
renderComponent({
props: { isOrganizerMode: true, hasDecryptionError: true },
attendee: getAttendee(ICAL_ATTENDEE_STATUS.TENTATIVE),
});
expect(screen.getByText(/test tentatively accepted your invitation./)).toBeInTheDocument();
});
it('displays the partycrasher tentative message when the event was accepted tentatively', () => {
renderComponent({
props: { isOrganizerMode: true, hasDecryptionError: true, isPartyCrasher: true },
attendee: getAttendee(ICAL_ATTENDEE_STATUS.TENTATIVE),
});
expect(
screen.getByText(/test tentatively accepted an invitation to this event./)
).toBeInTheDocument();
});
});
});
it('displays the does not exist message when the event does not exist', () => {
renderComponent({ props: { isOrganizerMode: true }, attendee: getAttendee() });
expect(
screen.getByText(
/This response is out of date. The event does not exist in your calendar anymore./
)
).toBeInTheDocument();
});
});
it('displays the future event message when the event is in the future', () => {
renderComponent({
props: {
isOrganizerMode: true,
isFromFuture: true,
invitationApi: { vevent: veventBuilder(), calendarEvent: calendarEventBuilder() },
},
attendee: getAttendee(),
});
expect(
screen.getByText(
/This response doesn't match your invitation details. Please verify the invitation details in your calendar./
)
).toBeInTheDocument();
});
describe('outdated event', () => {
describe('partstat: accepted', () => {
describe('single edit', () => {
it('displays the accepted message when the event was accepted', () => {
renderComponent({
props: {
isOrganizerMode: true,
invitationApi: { vevent: veventBuilder(), calendarEvent: calendarEventBuilder() },
isOutdated: true,
},
vevent: { 'recurrence-id': dummyRecurrenceID },
attendee: getAttendee(ICAL_ATTENDEE_STATUS.ACCEPTED),
});
expect(
screen.getByText(
/test had previously accepted your invitation to one occurrence of the event./
)
).toBeInTheDocument();
// has been updated text
expect(screen.getByText(/This response is out of date./)).toBeInTheDocument();
});
it('displays the partycrasher accepted message when the event was accepted', () => {
renderComponent({
props: {
isOrganizerMode: true,
invitationApi: { vevent: veventBuilder(), calendarEvent: calendarEventBuilder() },
isOutdated: true,
isPartyCrasher: true,
},
vevent: { 'recurrence-id': dummyRecurrenceID },
attendee: getAttendee(ICAL_ATTENDEE_STATUS.ACCEPTED),
});
expect(
screen.getByText(/test had accepted an invitation to one occurrence of the event./)
).toBeInTheDocument();
});
});
it('displays the accepted message when the event was accepted', () => {
renderComponent({
props: {
isOrganizerMode: true,
invitationApi: { vevent: veventBuilder(), calendarEvent: calendarEventBuilder() },
isOutdated: true,
},
attendee: getAttendee(ICAL_ATTENDEE_STATUS.ACCEPTED),
});
expect(screen.getByText(/test had previously accepted your invitation./)).toBeInTheDocument();
});
it('displays the partycrasher accepted message when the event was accepted', () => {
renderComponent({
props: {
isOrganizerMode: true,
invitationApi: { vevent: veventBuilder(), calendarEvent: calendarEventBuilder() },
isOutdated: true,
isPartyCrasher: true,
},
attendee: getAttendee(ICAL_ATTENDEE_STATUS.ACCEPTED),
});
expect(screen.getByText(/test had accepted an invitation to this event./)).toBeInTheDocument();
});
});
describe('partstat: declined', () => {
describe('single edit', () => {
it('displays the declined message when the event was declined', () => {
renderComponent({
props: {
isOrganizerMode: true,
invitationApi: { vevent: veventBuilder(), calendarEvent: calendarEventBuilder() },
isOutdated: true,
},
vevent: { 'recurrence-id': dummyRecurrenceID },
attendee: getAttendee(ICAL_ATTENDEE_STATUS.DECLINED),
});
expect(
screen.getByText(
/test had previously declined your invitation to one occurrence of the event./
)
).toBeInTheDocument();
});
it('displays the partycrasher declined message when the event was declined', () => {
renderComponent({
props: {
isOrganizerMode: true,
invitationApi: { vevent: veventBuilder(), calendarEvent: calendarEventBuilder() },
isOutdated: true,
isPartyCrasher: true,
},
vevent: { 'recurrence-id': dummyRecurrenceID },
attendee: getAttendee(ICAL_ATTENDEE_STATUS.DECLINED),
});
expect(
screen.getByText(/test had declined an invitation to one occurrence of the event./)
).toBeInTheDocument();
});
});
it('displays the declined message when the event was declined', () => {
renderComponent({
props: {
isOrganizerMode: true,
invitationApi: { vevent: veventBuilder(), calendarEvent: calendarEventBuilder() },
isOutdated: true,
},
attendee: getAttendee(ICAL_ATTENDEE_STATUS.DECLINED),
});
expect(screen.getByText(/test had previously declined your invitation./)).toBeInTheDocument();
});
it('displays the partycrasher declined message when the event was declined', () => {
renderComponent({
props: {
isOrganizerMode: true,
invitationApi: { vevent: veventBuilder(), calendarEvent: calendarEventBuilder() },
isOutdated: true,
isPartyCrasher: true,
},
attendee: getAttendee(ICAL_ATTENDEE_STATUS.DECLINED),
});
expect(screen.getByText(/test had declined an invitation to this event./)).toBeInTheDocument();
});
});
describe('partstat: tentative', () => {
describe('single edit', () => {
it('displays the tentative message when the event was accepted tentatively', () => {
renderComponent({
props: {
isOrganizerMode: true,
invitationApi: { vevent: veventBuilder(), calendarEvent: calendarEventBuilder() },
isOutdated: true,
},
vevent: { 'recurrence-id': dummyRecurrenceID },
attendee: getAttendee(ICAL_ATTENDEE_STATUS.TENTATIVE),
});
expect(
screen.getByText(
/test had previously tentatively accepted your invitation to one occurrence of the event./
)
).toBeInTheDocument();
});
it('displays the partycrasher tentative message when the event was accepted tentatively', () => {
renderComponent({
props: {
isOrganizerMode: true,
invitationApi: { vevent: veventBuilder(), calendarEvent: calendarEventBuilder() },
isOutdated: true,
isPartyCrasher: true,
},
vevent: { 'recurrence-id': dummyRecurrenceID },
attendee: getAttendee(ICAL_ATTENDEE_STATUS.TENTATIVE),
});
expect(
screen.getByText(
/test had tentatively accepted an invitation to one occurrence of the event./
)
).toBeInTheDocument();
});
});
it('displays the tentative message when the event was accepted tentatively', () => {
renderComponent({
props: {
isOrganizerMode: true,
invitationApi: { vevent: veventBuilder(), calendarEvent: calendarEventBuilder() },
isOutdated: true,
},
attendee: getAttendee(ICAL_ATTENDEE_STATUS.TENTATIVE),
});
expect(
screen.getByText(/test had previously tentatively accepted your invitation./)
).toBeInTheDocument();
});
it('displays the partycrasher tentative message when the event was accepted tentatively', () => {
renderComponent({
props: {
isOrganizerMode: true,
invitationApi: { vevent: veventBuilder(), calendarEvent: calendarEventBuilder() },
isOutdated: true,
isPartyCrasher: true,
},
attendee: getAttendee(ICAL_ATTENDEE_STATUS.TENTATIVE),
});
expect(
screen.getByText(/test had tentatively accepted an invitation to this event./)
).toBeInTheDocument();
});
});
});
describe('partstat: accepted', () => {
describe('single edit', () => {
it('displays the accepted message when the event was accepted', () => {
renderComponent({
props: {
isOrganizerMode: true,
invitationApi: { vevent: veventBuilder(), calendarEvent: calendarEventBuilder() },
},
vevent: { 'recurrence-id': dummyRecurrenceID },
attendee: getAttendee(ICAL_ATTENDEE_STATUS.ACCEPTED),
});
expect(
screen.getByText(/test accepted your invitation to one occurrence of the event./)
).toBeInTheDocument();
});
it('displays the partycrasher accepted message when the event was accepted', () => {
renderComponent({
props: {
isOrganizerMode: true,
invitationApi: { vevent: veventBuilder(), calendarEvent: calendarEventBuilder() },
isPartyCrasher: true,
},
vevent: { 'recurrence-id': dummyRecurrenceID },
attendee: getAttendee(ICAL_ATTENDEE_STATUS.ACCEPTED),
});
expect(
screen.getByText(/test accepted an invitation to one occurrence of the event./)
).toBeInTheDocument();
});
});
it('displays the accepted message when the event was accepted', () => {
renderComponent({
props: {
isOrganizerMode: true,
invitationApi: { vevent: veventBuilder(), calendarEvent: calendarEventBuilder() },
},
attendee: getAttendee(ICAL_ATTENDEE_STATUS.ACCEPTED),
});
expect(screen.getByText(/test accepted your invitation./)).toBeInTheDocument();
});
it('displays the partycrasher accepted message when the event was accepted', () => {
renderComponent({
props: {
isOrganizerMode: true,
invitationApi: { vevent: veventBuilder(), calendarEvent: calendarEventBuilder() },
isPartyCrasher: true,
},
attendee: getAttendee(ICAL_ATTENDEE_STATUS.ACCEPTED),
});
expect(screen.getByText(/test accepted an invitation to this event./)).toBeInTheDocument();
});
});
describe('partstat: declined', () => {
describe('single edit', () => {
it('displays the declined message when the event was declined', () => {
renderComponent({
props: {
isOrganizerMode: true,
invitationApi: { vevent: veventBuilder(), calendarEvent: calendarEventBuilder() },
},
vevent: { 'recurrence-id': dummyRecurrenceID },
attendee: getAttendee(ICAL_ATTENDEE_STATUS.DECLINED),
});
expect(
screen.getByText(/test declined your invitation to one occurrence of the event./)
).toBeInTheDocument();
});
it('displays the partycrasher declined message when the event was declined', () => {
renderComponent({
props: {
isOrganizerMode: true,
invitationApi: { vevent: veventBuilder(), calendarEvent: calendarEventBuilder() },
isPartyCrasher: true,
},
vevent: { 'recurrence-id': dummyRecurrenceID },
attendee: getAttendee(ICAL_ATTENDEE_STATUS.DECLINED),
});
expect(
screen.getByText(/test declined an invitation to one occurrence of the event./)
).toBeInTheDocument();
});
});
it('displays the declined message when the event was declined', () => {
renderComponent({
props: {
isOrganizerMode: true,
invitationApi: { vevent: veventBuilder(), calendarEvent: calendarEventBuilder() },
},
attendee: getAttendee(ICAL_ATTENDEE_STATUS.DECLINED),
});
expect(screen.getByText(/test declined your invitation./)).toBeInTheDocument();
});
it('displays the partycrasher declined message when the event was declined', () => {
renderComponent({
props: {
isOrganizerMode: true,
invitationApi: { vevent: veventBuilder(), calendarEvent: calendarEventBuilder() },
isPartyCrasher: true,
},
attendee: getAttendee(ICAL_ATTENDEE_STATUS.DECLINED),
});
expect(screen.getByText(/test declined an invitation to this event./)).toBeInTheDocument();
});
});
describe('partstat: tentative', () => {
describe('single edit', () => {
it('displays the tentatively accepted message when the event was tentatively accepted', () => {
renderComponent({
props: {
isOrganizerMode: true,
invitationApi: { vevent: veventBuilder(), calendarEvent: calendarEventBuilder() },
},
vevent: { 'recurrence-id': dummyRecurrenceID },
attendee: getAttendee(ICAL_ATTENDEE_STATUS.TENTATIVE),
});
expect(
screen.getByText(
/test tentatively accepted your invitation to one occurrence of the event./
)
).toBeInTheDocument();
});
it('displays the partycrasher tentatively accepted message when the event was tentatively accepted', () => {
renderComponent({
props: {
isOrganizerMode: true,
invitationApi: { vevent: veventBuilder(), calendarEvent: calendarEventBuilder() },
isPartyCrasher: true,
},
vevent: { 'recurrence-id': dummyRecurrenceID },
attendee: getAttendee(ICAL_ATTENDEE_STATUS.TENTATIVE),
});
expect(
screen.getByText(/test tentatively accepted an invitation to one occurrence of the event./)
).toBeInTheDocument();
});
});
it('displays the tentatively accepted message when the event was tentatively accepted', () => {
renderComponent({
props: {
isOrganizerMode: true,
invitationApi: { vevent: veventBuilder(), calendarEvent: calendarEventBuilder() },
},
attendee: getAttendee(ICAL_ATTENDEE_STATUS.TENTATIVE),
});
expect(screen.getByText(/test tentatively accepted your invitation./)).toBeInTheDocument();
});
it('displays the partycrasher tentatively accepted message when the event was tentatively accepted', () => {
renderComponent({
props: {
isOrganizerMode: true,
invitationApi: { vevent: veventBuilder(), calendarEvent: calendarEventBuilder() },
isPartyCrasher: true,
},
attendee: getAttendee(ICAL_ATTENDEE_STATUS.TENTATIVE),
});
expect(
screen.getByText(/test tentatively accepted an invitation to this event./)
).toBeInTheDocument();
});
});
});
describe('method: counter', () => {
describe('no event from api', () => {
it('single edit: displays the no calendars message when there are no calendars', () => {
renderComponent({
props: { isOrganizerMode: true, hasNoCalendars: true },
attendee: getAttendee(),
vevent: { 'recurrence-id': dummyRecurrenceID },
method: ICAL_METHOD.COUNTER,
});
expect(
screen.getByText(
/test had proposed a new time for one occurrence of this event. This proposal is out of date. You have no calendars./
)
).toBeInTheDocument();
});
it('displays the no calendars message when there are no calendars', () => {
renderComponent({
props: { isOrganizerMode: true, hasNoCalendars: true },
attendee: getAttendee(),
method: ICAL_METHOD.COUNTER,
});
expect(
screen.getByText(
/test had proposed a new time for this event. This proposal is out of date. You have no calendars./
)
).toBeInTheDocument();
});
describe('has decryption error', () => {
describe('partstat: accepted', () => {
describe('single edit', () => {
it('displays the accepted message when the event was accepted', () => {
renderComponent({
props: {
hasDecryptionError: true,
isOrganizerMode: true,
},
vevent: { 'recurrence-id': dummyRecurrenceID },
attendee: getAttendee(ICAL_ATTENDEE_STATUS.ACCEPTED),
method: ICAL_METHOD.COUNTER,
});
expect(
screen.getByText(
/test accepted your invitation and proposed a new time for one occurrence of this event./
)
).toBeInTheDocument();
});
it('displays the partycrasher accepted message when the event was accepted', () => {
renderComponent({
props: {
hasDecryptionError: true,
isOrganizerMode: true,
isPartyCrasher: true,
},
vevent: { 'recurrence-id': dummyRecurrenceID },
attendee: getAttendee(ICAL_ATTENDEE_STATUS.ACCEPTED),
method: ICAL_METHOD.COUNTER,
});
expect(
screen.getByText(
/test accepted an invitation and proposed a new time for one occurrence of this event./
)
).toBeInTheDocument();
});
});
it('displays the accepted message when the event was accepted', () => {
renderComponent({
props: {
hasDecryptionError: true,
isOrganizerMode: true,
},
attendee: getAttendee(ICAL_ATTENDEE_STATUS.ACCEPTED),
method: ICAL_METHOD.COUNTER,
});
expect(
screen.getByText(
/test accepted your invitation and proposed a new time for this event./
)
).toBeInTheDocument();
});
it('displays the partycrasher accepted message when the event was accepted', () => {
renderComponent({
props: {
hasDecryptionError: true,
isOrganizerMode: true,
isPartyCrasher: true,
},
attendee: getAttendee(ICAL_ATTENDEE_STATUS.ACCEPTED),
method: ICAL_METHOD.COUNTER,
});
expect(
screen.getByText(/test accepted an invitation and proposed a new time for this event./)
).toBeInTheDocument();
});
});
describe('partstat: declined', () => {
describe('single edit', () => {
it('displays the declined message when the event was declined', () => {
renderComponent({
props: {
hasDecryptionError: true,
isOrganizerMode: true,
},
vevent: { 'recurrence-id': dummyRecurrenceID },
attendee: getAttendee(ICAL_ATTENDEE_STATUS.DECLINED),
method: ICAL_METHOD.COUNTER,
});
expect(
screen.getByText(
/test declined your invitation and proposed a new time for one occurrence of this event./
)
).toBeInTheDocument();
});
it('displays the partycrasher declined message when the event was declined', () => {
renderComponent({
props: {
hasDecryptionError: true,
isOrganizerMode: true,
isPartyCrasher: true,
},
vevent: { 'recurrence-id': dummyRecurrenceID },
attendee: getAttendee(ICAL_ATTENDEE_STATUS.DECLINED),
method: ICAL_METHOD.COUNTER,
});
expect(
screen.getByText(
/test declined an invitation and proposed a new time for one occurrence of this event./
)
).toBeInTheDocument();
});
});
it('displays the declined message when the event was declined', () => {
renderComponent({
props: {
hasDecryptionError: true,
isOrganizerMode: true,
},
attendee: getAttendee(ICAL_ATTENDEE_STATUS.DECLINED),
method: ICAL_METHOD.COUNTER,
});
expect(
screen.getByText(
/test declined your invitation and proposed a new time for this event./
)
).toBeInTheDocument();
});
it('displays the partycrasher declined message when the event was declined', () => {
renderComponent({
props: {
hasDecryptionError: true,
isOrganizerMode: true,
isPartyCrasher: true,
},
attendee: getAttendee(ICAL_ATTENDEE_STATUS.DECLINED),
method: ICAL_METHOD.COUNTER,
});
expect(
screen.getByText(/test declined an invitation and proposed a new time for this event./)
).toBeInTheDocument();
});
});
describe('partstat: tentative', () => {
describe('single edit', () => {
it('displays the tentative message when the event was accepted tentatively', () => {
renderComponent({
props: {
hasDecryptionError: true,
isOrganizerMode: true,
},
vevent: { 'recurrence-id': dummyRecurrenceID },
attendee: getAttendee(ICAL_ATTENDEE_STATUS.TENTATIVE),
method: ICAL_METHOD.COUNTER,
});
expect(
screen.getByText(
/test tentatively accepted your invitation and proposed a new time for one occurrence of this event./
)
).toBeInTheDocument();
});
it('displays the partycrasher tentative message when the event was accepted tentatively', () => {
renderComponent({
props: {
hasDecryptionError: true,
isOrganizerMode: true,
isPartyCrasher: true,
},
vevent: { 'recurrence-id': dummyRecurrenceID },
attendee: getAttendee(ICAL_ATTENDEE_STATUS.TENTATIVE),
method: ICAL_METHOD.COUNTER,
});
expect(
screen.getByText(
/test tentatively accepted an invitation and proposed a new time for one occurrence of this event./
)
).toBeInTheDocument();
});
});
it('displays the tentative message when the event was accepted tentatively', () => {
renderComponent({
props: {
hasDecryptionError: true,
isOrganizerMode: true,
},
attendee: getAttendee(ICAL_ATTENDEE_STATUS.TENTATIVE),
method: ICAL_METHOD.COUNTER,
});
expect(
screen.getByText(
/test tentatively accepted your invitation and proposed a new time for this event./
)
).toBeInTheDocument();
});
it('displays the partycrasher tentative message when the event was accepted tentatively', () => {
renderComponent({
props: {
hasDecryptionError: true,
isOrganizerMode: true,
isPartyCrasher: true,
},
attendee: getAttendee(ICAL_ATTENDEE_STATUS.TENTATIVE),
method: ICAL_METHOD.COUNTER,
});
expect(
screen.getByText(
/test tentatively accepted an invitation and proposed a new time for this event./
)
).toBeInTheDocument();
});
});
it('single edit: displays the out of date message when there are out of date', () => {
renderComponent({
props: { isOrganizerMode: true, hasDecryptionError: true },
attendee: getAttendee(),
vevent: { 'recurrence-id': dummyRecurrenceID },
method: ICAL_METHOD.COUNTER,
});
expect(
screen.getByText(/test proposed a new time for one occurrence of this event./)
).toBeInTheDocument();
});
it('displays the out of date message when there are out of date', () => {
renderComponent({
props: { isOrganizerMode: true, hasDecryptionError: true },
attendee: getAttendee(),
method: ICAL_METHOD.COUNTER,
});
expect(screen.getByText(/test proposed a new time for this event./)).toBeInTheDocument();
});
});
it('single edit: displays the out of date message when there are out of date', () => {
renderComponent({
props: { isOrganizerMode: true },
attendee: getAttendee(),
vevent: { 'recurrence-id': dummyRecurrenceID },
method: ICAL_METHOD.COUNTER,
});
expect(
screen.getByText(
/test had proposed a new time for one occurrence of this event. This proposal is out of date. The event does not exist in your calendar anymore./
)
).toBeInTheDocument();
});
it('displays the out of date message when there are out of date', () => {
renderComponent({
props: { isOrganizerMode: true },
attendee: getAttendee(),
method: ICAL_METHOD.COUNTER,
});
expect(
screen.getByText(
/test had proposed a new time for this event. This proposal is out of date. The event does not exist in your calendar anymore./
)
).toBeInTheDocument();
});
});
it('displays the future event message when the event is in the future', () => {
const { container } = renderComponent({
props: {
isOrganizerMode: true,
isFromFuture: true,
invitationApi: { vevent: veventBuilder(), calendarEvent: calendarEventBuilder() },
},
method: ICAL_METHOD.COUNTER,
attendee: getAttendee(),
});
expect(container.children[0].children.length).toBe(1);
expect(
screen.getByText(
/This new time proposal doesn't match your invitation details. Please verify the invitation details in your calendar./
)
).toBeInTheDocument();
});
describe('outdated event', () => {
describe('partstat: accepted', () => {
describe('single edit', () => {
it('displays the accepted message when the event was accepted', () => {
renderComponent({
props: {
isOrganizerMode: true,
invitationApi: { vevent: veventBuilder(), calendarEvent: calendarEventBuilder() },
isOutdated: true,
},
vevent: { 'recurrence-id': dummyRecurrenceID },
attendee: getAttendee(ICAL_ATTENDEE_STATUS.ACCEPTED),
method: ICAL_METHOD.COUNTER,
});
expect(
screen.getByText(
/test had accepted your invitation and proposed a new time for one occurrence of this event. Answer and proposal are out of date./
)
).toBeInTheDocument();
});
it('displays the partycrasher accepted message when the event was accepted', () => {
renderComponent({
props: {
isOrganizerMode: true,
invitationApi: { vevent: veventBuilder(), calendarEvent: calendarEventBuilder() },
isOutdated: true,
isPartyCrasher: true,
},
vevent: { 'recurrence-id': dummyRecurrenceID },
attendee: getAttendee(ICAL_ATTENDEE_STATUS.ACCEPTED),
method: ICAL_METHOD.COUNTER,
});
expect(
screen.getByText(
/test had accepted an invitation and proposed a new time for one occurrence of this event. Answer and proposal are out of date./
)
).toBeInTheDocument();
});
});
it('displays the accepted message when the event was accepted', () => {
renderComponent({
props: {
isOrganizerMode: true,
invitationApi: { vevent: veventBuilder(), calendarEvent: calendarEventBuilder() },
isOutdated: true,
},
attendee: getAttendee(ICAL_ATTENDEE_STATUS.ACCEPTED),
method: ICAL_METHOD.COUNTER,
});
expect(
screen.getByText(
/test had accepted your invitation and proposed a new time for this event. Answer and proposal are out of date./
)
).toBeInTheDocument();
});
it('displays the partycrasher accepted message when the event was accepted', () => {
renderComponent({
props: {
isOrganizerMode: true,
invitationApi: { vevent: veventBuilder(), calendarEvent: calendarEventBuilder() },
isOutdated: true,
isPartyCrasher: true,
},
attendee: getAttendee(ICAL_ATTENDEE_STATUS.ACCEPTED),
method: ICAL_METHOD.COUNTER,
});
expect(
screen.getByText(
/test had accepted an invitation and proposed a new time for this event. Answer and proposal are out of date./
)
).toBeInTheDocument();
});
});
describe('partstat: declined', () => {
describe('single edit', () => {
it('displays the declined message when the event was declined', () => {
renderComponent({
props: {
isOrganizerMode: true,
invitationApi: { vevent: veventBuilder(), calendarEvent: calendarEventBuilder() },
isOutdated: true,
},
vevent: { 'recurrence-id': dummyRecurrenceID },
attendee: getAttendee(ICAL_ATTENDEE_STATUS.DECLINED),
method: ICAL_METHOD.COUNTER,
});
expect(
screen.getByText(
/test had declined your invitation and proposed a new time for one occurrence of this event. Answer and proposal are out of date./
)
).toBeInTheDocument();
});
it('displays the partycrasher declined message when the event was declined', () => {
renderComponent({
props: {
isOrganizerMode: true,
invitationApi: { vevent: veventBuilder(), calendarEvent: calendarEventBuilder() },
isOutdated: true,
isPartyCrasher: true,
},
vevent: { 'recurrence-id': dummyRecurrenceID },
attendee: getAttendee(ICAL_ATTENDEE_STATUS.DECLINED),
method: ICAL_METHOD.COUNTER,
});
expect(
screen.getByText(
/test had declined an invitation and proposed a new time for one occurrence of this event. Answer and proposal are out of date./
)
).toBeInTheDocument();
});
});
it('displays the declined message when the event was declined', () => {
renderComponent({
props: {
isOrganizerMode: true,
invitationApi: { vevent: veventBuilder(), calendarEvent: calendarEventBuilder() },
isOutdated: true,
},
attendee: getAttendee(ICAL_ATTENDEE_STATUS.DECLINED),
method: ICAL_METHOD.COUNTER,
});
expect(
screen.getByText(
/test had declined your invitation and proposed a new time for this event. Answer and proposal are out of date./
)
).toBeInTheDocument();
});
it('displays the partycrasher declined message when the event was declined', () => {
renderComponent({
props: {
isOrganizerMode: true,
invitationApi: { vevent: veventBuilder(), calendarEvent: calendarEventBuilder() },
isOutdated: true,
isPartyCrasher: true,
},
attendee: getAttendee(ICAL_ATTENDEE_STATUS.DECLINED),
method: ICAL_METHOD.COUNTER,
});
expect(
screen.getByText(
/test had declined an invitation and proposed a new time for this event. Answer and proposal are out of date./
)
).toBeInTheDocument();
});
});
describe('partstat: tentative', () => {
describe('single edit', () => {
it('displays the tentative message when the event was accepted tentatively', () => {
renderComponent({
props: {
isOrganizerMode: true,
invitationApi: { vevent: veventBuilder(), calendarEvent: calendarEventBuilder() },
isOutdated: true,
},
vevent: { 'recurrence-id': dummyRecurrenceID },
attendee: getAttendee(ICAL_ATTENDEE_STATUS.TENTATIVE),
method: ICAL_METHOD.COUNTER,
});
expect(
screen.getByText(
/test had tentatively accepted your invitation and proposed a new time for one occurrence of this event. Answer and proposal are out of date./
)
).toBeInTheDocument();
});
it('displays the partycrasher tentative message when the event was accepted tentatively', () => {
renderComponent({
props: {
isOrganizerMode: true,
invitationApi: { vevent: veventBuilder(), calendarEvent: calendarEventBuilder() },
isOutdated: true,
isPartyCrasher: true,
},
vevent: { 'recurrence-id': dummyRecurrenceID },
attendee: getAttendee(ICAL_ATTENDEE_STATUS.TENTATIVE),
method: ICAL_METHOD.COUNTER,
});
expect(
screen.getByText(
/test had tentatively accepted an invitation and proposed a new time for one occurrence of this event. Answer and proposal are out of date./
)
).toBeInTheDocument();
});
});
it('displays the tentative message when the event was accepted tentatively', () => {
renderComponent({
props: {
isOrganizerMode: true,
invitationApi: { vevent: veventBuilder(), calendarEvent: calendarEventBuilder() },
isOutdated: true,
},
attendee: getAttendee(ICAL_ATTENDEE_STATUS.TENTATIVE),
method: ICAL_METHOD.COUNTER,
});
expect(
screen.getByText(
/test had tentatively accepted your invitation and proposed a new time for this event. Answer and proposal are out of date./
)
).toBeInTheDocument();
});
it('displays the partycrasher tentative message when the event was accepted tentatively', () => {
renderComponent({
props: {
isOrganizerMode: true,
invitationApi: { vevent: veventBuilder(), calendarEvent: calendarEventBuilder() },
isOutdated: true,
isPartyCrasher: true,
},
attendee: getAttendee(ICAL_ATTENDEE_STATUS.TENTATIVE),
method: ICAL_METHOD.COUNTER,
});
expect(
screen.getByText(
/test had tentatively accepted an invitation and proposed a new time for this event. Answer and proposal are out of date./
)
).toBeInTheDocument();
});
});
describe('single edit', () => {
it('displays the correct message when a counter was proposed', () => {
renderComponent({
props: {
isOrganizerMode: true,
invitationApi: { vevent: veventBuilder(), calendarEvent: calendarEventBuilder() },
isOutdated: true,
},
vevent: { 'recurrence-id': dummyRecurrenceID },
attendee: getAttendee(),
method: ICAL_METHOD.COUNTER,
});
expect(
screen.getByText(
/test had proposed a new time for one occurrence of this event. This proposal is out of date./
)
).toBeInTheDocument();
});
});
it('displays the correct message when a counter was proposed', () => {
renderComponent({
props: {
isOrganizerMode: true,
invitationApi: { vevent: veventBuilder(), calendarEvent: calendarEventBuilder() },
isOutdated: true,
},
attendee: getAttendee(),
method: ICAL_METHOD.COUNTER,
});
expect(
screen.getByText(/test had proposed a new time for this event. This proposal is out of date./)
).toBeInTheDocument();
});
});
describe('partstat: accepted', () => {
describe('single edit', () => {
it('displays the accepted message when the event was accepted', () => {
renderComponent({
props: {
isOrganizerMode: true,
invitationApi: { vevent: veventBuilder(), calendarEvent: calendarEventBuilder() },
},
vevent: { 'recurrence-id': dummyRecurrenceID },
attendee: getAttendee(ICAL_ATTENDEE_STATUS.ACCEPTED),
method: ICAL_METHOD.COUNTER,
});
expect(
screen.getByText(
/test accepted your invitation and proposed a new time for one occurrence of this event./
)
).toBeInTheDocument();
});
it('displays the partycrasher accepted message when the event was accepted', () => {
renderComponent({
props: {
isOrganizerMode: true,
invitationApi: { vevent: veventBuilder(), calendarEvent: calendarEventBuilder() },
isPartyCrasher: true,
},
vevent: { 'recurrence-id': dummyRecurrenceID },
attendee: getAttendee(ICAL_ATTENDEE_STATUS.ACCEPTED),
method: ICAL_METHOD.COUNTER,
});
expect(
screen.getByText(
/test accepted an invitation and proposed a new time for one occurrence of this event./
)
).toBeInTheDocument();
});
});
it('displays the accepted message when the event was accepted', () => {
renderComponent({
props: {
isOrganizerMode: true,
invitationApi: { vevent: veventBuilder(), calendarEvent: calendarEventBuilder() },
},
attendee: getAttendee(ICAL_ATTENDEE_STATUS.ACCEPTED),
method: ICAL_METHOD.COUNTER,
});
expect(
screen.getByText(/test accepted your invitation and proposed a new time for this event./)
).toBeInTheDocument();
});
it('displays the partycrasher accepted message when the event was accepted', () => {
renderComponent({
props: {
isOrganizerMode: true,
invitationApi: { vevent: veventBuilder(), calendarEvent: calendarEventBuilder() },
isPartyCrasher: true,
},
attendee: getAttendee(ICAL_ATTENDEE_STATUS.ACCEPTED),
method: ICAL_METHOD.COUNTER,
});
expect(
screen.getByText(/test accepted an invitation and proposed a new time for this event./)
).toBeInTheDocument();
});
});
describe('partstat: declined', () => {
describe('single edit', () => {
it('displays the declined message when the event was declined', () => {
renderComponent({
props: {
isOrganizerMode: true,
invitationApi: { vevent: veventBuilder(), calendarEvent: calendarEventBuilder() },
},
vevent: { 'recurrence-id': dummyRecurrenceID },
attendee: getAttendee(ICAL_ATTENDEE_STATUS.DECLINED),
method: ICAL_METHOD.COUNTER,
});
expect(
screen.getByText(
/test declined your invitation and proposed a new time for one occurrence of this event./
)
).toBeInTheDocument();
});
it('displays the partycrasher declined message when the event was declined', () => {
renderComponent({
props: {
isOrganizerMode: true,
invitationApi: { vevent: veventBuilder(), calendarEvent: calendarEventBuilder() },
isPartyCrasher: true,
},
vevent: { 'recurrence-id': dummyRecurrenceID },
attendee: getAttendee(ICAL_ATTENDEE_STATUS.DECLINED),
method: ICAL_METHOD.COUNTER,
});
expect(
screen.getByText(
/test declined an invitation and proposed a new time for one occurrence of this event./
)
).toBeInTheDocument();
});
});
it('displays the declined message when the event was declined', () => {
renderComponent({
props: {
isOrganizerMode: true,
invitationApi: { vevent: veventBuilder(), calendarEvent: calendarEventBuilder() },
},
attendee: getAttendee(ICAL_ATTENDEE_STATUS.DECLINED),
method: ICAL_METHOD.COUNTER,
});
expect(
screen.getByText(/test declined your invitation and proposed a new time for this event./)
).toBeInTheDocument();
});
it('displays the partycrasher declined message when the event was declined', () => {
renderComponent({
props: {
isOrganizerMode: true,
invitationApi: { vevent: veventBuilder(), calendarEvent: calendarEventBuilder() },
isPartyCrasher: true,
},
attendee: getAttendee(ICAL_ATTENDEE_STATUS.DECLINED),
method: ICAL_METHOD.COUNTER,
});
expect(
screen.getByText(/test declined an invitation and proposed a new time for this event./)
).toBeInTheDocument();
});
});
describe('partstat: tentative', () => {
describe('single edit', () => {
it('displays the tentative message when the event was accepted tentatively', () => {
renderComponent({
props: {
isOrganizerMode: true,
invitationApi: { vevent: veventBuilder(), calendarEvent: calendarEventBuilder() },
},
vevent: { 'recurrence-id': dummyRecurrenceID },
attendee: getAttendee(ICAL_ATTENDEE_STATUS.TENTATIVE),
method: ICAL_METHOD.COUNTER,
});
expect(
screen.getByText(
/test tentatively accepted your invitation and proposed a new time for one occurrence of this event./
)
).toBeInTheDocument();
});
it('displays the partycrasher tentative message when the event was accepted tentatively', () => {
renderComponent({
props: {
isOrganizerMode: true,
invitationApi: { vevent: veventBuilder(), calendarEvent: calendarEventBuilder() },
isPartyCrasher: true,
},
vevent: { 'recurrence-id': dummyRecurrenceID },
attendee: getAttendee(ICAL_ATTENDEE_STATUS.TENTATIVE),
method: ICAL_METHOD.COUNTER,
});
expect(
screen.getByText(
/test tentatively accepted an invitation and proposed a new time for one occurrence of this event./
)
).toBeInTheDocument();
});
});
it('displays the tentative message when the event was accepted tentatively', () => {
renderComponent({
props: {
isOrganizerMode: true,
invitationApi: { vevent: veventBuilder(), calendarEvent: calendarEventBuilder() },
},
attendee: getAttendee(ICAL_ATTENDEE_STATUS.TENTATIVE),
method: ICAL_METHOD.COUNTER,
});
expect(
screen.getByText(
/test tentatively accepted your invitation and proposed a new time for this event./
)
).toBeInTheDocument();
});
it('displays the partycrasher tentative message when the event was accepted tentatively', () => {
renderComponent({
props: {
isOrganizerMode: true,
invitationApi: { vevent: veventBuilder(), calendarEvent: calendarEventBuilder() },
isPartyCrasher: true,
},
attendee: getAttendee(ICAL_ATTENDEE_STATUS.TENTATIVE),
method: ICAL_METHOD.COUNTER,
});
expect(
screen.getByText(
/test tentatively accepted an invitation and proposed a new time for this event./
)
).toBeInTheDocument();
});
it('single edit: displays the out of date message when there are out of date', () => {
renderComponent({
props: {
isOrganizerMode: true,
invitationApi: { vevent: veventBuilder(), calendarEvent: calendarEventBuilder() },
},
attendee: getAttendee(),
vevent: { 'recurrence-id': dummyRecurrenceID },
method: ICAL_METHOD.COUNTER,
});
expect(
screen.getByText(/test proposed a new time for one occurrence of this event./)
).toBeInTheDocument();
});
it('displays the out of date message when there are out of date', () => {
renderComponent({
props: {
isOrganizerMode: true,
invitationApi: { vevent: veventBuilder(), calendarEvent: calendarEventBuilder() },
},
attendee: getAttendee(),
method: ICAL_METHOD.COUNTER,
});
expect(screen.getByText(/test proposed a new time for this event./)).toBeInTheDocument();
});
});
describe('single edit', () => {
it('displays the correct message when a counter was proposed', () => {
renderComponent({
props: {
isOrganizerMode: true,
invitationApi: { vevent: veventBuilder(), calendarEvent: calendarEventBuilder() },
},
vevent: { 'recurrence-id': dummyRecurrenceID },
attendee: getAttendee(),
method: ICAL_METHOD.COUNTER,
});
expect(
screen.getByText(/test proposed a new time for one occurrence of this event./)
).toBeInTheDocument();
});
});
it('displays the correct message when a counter was proposed', () => {
renderComponent({
props: {
isOrganizerMode: true,
invitationApi: { vevent: veventBuilder(), calendarEvent: calendarEventBuilder() },
},
attendee: getAttendee(),
method: ICAL_METHOD.COUNTER,
});
expect(screen.getByText(/test proposed a new time for this event./)).toBeInTheDocument();
});
});
describe('method: refresh', () => {
describe('no event from api', () => {
it('displays the no calendars message when there are no calendars', () => {
renderComponent({
props: { isOrganizerMode: true, hasNoCalendars: true },
attendee: getAttendee(),
method: ICAL_METHOD.REFRESH,
});
expect(
screen.getByText(
/test asked for the latest updates to an event which does not exist anymore. You have no calendars./
)
).toBeInTheDocument();
});
describe('decryption error', () => {
it('displays the accepted message when the event was accepted', () => {
renderComponent({
props: { isOrganizerMode: true, hasDecryptionError: true },
attendee: getAttendee(ICAL_ATTENDEE_STATUS.ACCEPTED),
method: ICAL_METHOD.REFRESH,
});
expect(screen.getByText(/test asked for the latest event updates./)).toBeInTheDocument();
});
});
it('displays the accepted message when the event was accepted', () => {
renderComponent({
props: { isOrganizerMode: true },
attendee: getAttendee(ICAL_ATTENDEE_STATUS.ACCEPTED),
method: ICAL_METHOD.REFRESH,
});
expect(
screen.getByText(
/test asked for the latest updates to an event which does not exist in your calendar anymore./
)
).toBeInTheDocument();
});
});
it('displays the future message when the invite is from the future', () => {
renderComponent({
props: {
isFromFuture: true,
isOrganizerMode: true,
invitationApi: { vevent: veventBuilder(), calendarEvent: calendarEventBuilder() },
},
attendee: getAttendee(),
method: ICAL_METHOD.REFRESH,
});
expect(
screen.getByText(
/test asked for the latest updates to an event which doesn't match your invitation details. Please verify the invitation details in your calendar./
)
).toBeInTheDocument();
});
it('displays the refresh message when the invitation was found', () => {
renderComponent({
props: {
isOrganizerMode: true,
invitationApi: { vevent: veventBuilder(), calendarEvent: calendarEventBuilder() },
},
attendee: getAttendee(),
method: ICAL_METHOD.REFRESH,
});
expect(screen.getByText(/test asked for the latest event updates./)).toBeInTheDocument();
});
});
});
});
|
3,639 | 0 | petrpan-code/ProtonMail/WebClients/applications/mail/src/app/components/message/extras | petrpan-code/ProtonMail/WebClients/applications/mail/src/app/components/message/extras/expiration/ExtraExpirationTime.test.tsx | import { Message } from '@proton/shared/lib/interfaces/mail/Message';
import { clearAll, render } from '../../../../helpers/test/helper';
import ExtraExpirationTime from './ExtraExpirationTime';
const getExpirationTime = (numberOfSeconds: number) => {
return new Date().getTime() / 1000 + numberOfSeconds;
};
describe('ExtraExpirationTime', () => {
const seconds = 50;
const setup = async (ExpirationTime: number) => {
const result = await render(
<ExtraExpirationTime message={{ localID: 'localID', data: { ExpirationTime } as Message }} />
);
const rerender = async (ExpirationTime: number) => {
await result.rerender(
<ExtraExpirationTime message={{ localID: 'localID', data: { ExpirationTime } as Message }} />
);
return result.queryByTestId('expiration-banner');
};
return { banner: result.queryByTestId('expiration-banner'), rerender };
};
afterEach(() => {
jest.clearAllMocks();
clearAll();
});
it('should return no expiration if no expiration time', async () => {
const { banner } = await setup(0);
expect(banner).toBe(null);
});
it('should return the expiration message if there is expiration time', async () => {
const ExpirationTime = getExpirationTime(seconds);
const { banner } = await setup(ExpirationTime);
expect(banner).not.toBe(null);
const value = Number(/\d+/.exec(banner?.textContent || '')?.[0]);
expect(value).toBeLessThanOrEqual(seconds);
});
it('should be able to react to new message', async () => {
const ExpirationTime = getExpirationTime(seconds);
const result = await setup(0);
let { banner } = result;
expect(banner).toBe(null);
banner = await result.rerender(ExpirationTime);
expect(banner).not.toBe(null);
banner = await result.rerender(0);
expect(banner).toBe(null);
});
});
|
3,646 | 0 | petrpan-code/ProtonMail/WebClients/applications/mail/src/app/components/message | petrpan-code/ProtonMail/WebClients/applications/mail/src/app/components/message/helpers/getIframeHtml.test.tsx | import { createDocument } from '../../../helpers/test/message';
import {
MESSAGE_IFRAME_PRINT_CLASS,
MESSAGE_IFRAME_PRINT_FOOTER_ID,
MESSAGE_IFRAME_PRINT_HEADER_ID,
} from '../constants';
import getIframeHtml from './getIframeHtml';
describe('getIframeHTML', () => {
describe('rich text', () => {
it('Should not contain print classes and elements', () => {
const document = createDocument('hello buddy');
const htmlString = getIframeHtml({
emailContent: 'dude',
messageDocument: document,
isPlainText: false,
isPrint: false,
themeCSSVariables: '',
});
expect(htmlString).not.toContain(MESSAGE_IFRAME_PRINT_CLASS);
expect(htmlString).not.toContain(MESSAGE_IFRAME_PRINT_HEADER_ID);
expect(htmlString).not.toContain(MESSAGE_IFRAME_PRINT_FOOTER_ID);
});
it('Should contain print classes and elements', () => {
const document = createDocument('hello buddy');
const htmlString = getIframeHtml({
emailContent: 'dude',
messageDocument: document,
isPlainText: false,
isPrint: true,
themeCSSVariables: '',
});
expect(htmlString).toContain(MESSAGE_IFRAME_PRINT_CLASS);
expect(htmlString).toContain(MESSAGE_IFRAME_PRINT_HEADER_ID);
expect(htmlString).toContain(MESSAGE_IFRAME_PRINT_FOOTER_ID);
});
});
describe('plain text', () => {
it('Should not contain print classes and elements', () => {
const document = createDocument('hello buddy');
const htmlString = getIframeHtml({
emailContent: 'dude',
messageDocument: document,
isPlainText: true,
isPrint: false,
themeCSSVariables: '',
});
expect(htmlString).not.toContain(MESSAGE_IFRAME_PRINT_CLASS);
expect(htmlString).not.toContain(MESSAGE_IFRAME_PRINT_HEADER_ID);
expect(htmlString).not.toContain(MESSAGE_IFRAME_PRINT_FOOTER_ID);
});
it('Should not contain print classes and elements', () => {
const document = createDocument('hello buddy');
const htmlString = getIframeHtml({
emailContent: 'dude',
messageDocument: document,
isPlainText: true,
isPrint: true,
themeCSSVariables: '',
});
expect(htmlString).toContain(MESSAGE_IFRAME_PRINT_CLASS);
expect(htmlString).toContain(MESSAGE_IFRAME_PRINT_HEADER_ID);
expect(htmlString).toContain(MESSAGE_IFRAME_PRINT_FOOTER_ID);
});
});
});
|
3,655 | 0 | petrpan-code/ProtonMail/WebClients/applications/mail/src/app/components/message | petrpan-code/ProtonMail/WebClients/applications/mail/src/app/components/message/modals/ContactResignModal.test.tsx | import { fireEvent, waitFor } from '@testing-library/react';
import { Address } from '@proton/shared/lib/interfaces';
import { ContactEmail } from '@proton/shared/lib/interfaces/contacts';
import { addApiMock } from '../../../helpers/test/api';
import { addToCache, minimalCache } from '../../../helpers/test/cache';
import { addKeysToUserKeysCache } from '../../../helpers/test/crypto';
import { releaseCryptoProxy, setupCryptoProxyForTesting } from '../../../helpers/test/crypto';
import { contactID, receiver, sender, setupContactsForPinKeys } from '../../../helpers/test/pinKeys';
import { render, tick } from '../../../helpers/test/render';
import ContactResignModal from './ContactResignModal';
const contacts = [{ contactID: contactID }];
const title = 'Contact Resign Modal title';
const children = 'Contact Resign Modal children';
describe('Contact resign modal', () => {
beforeAll(async () => {
await setupCryptoProxyForTesting();
});
afterAll(async () => {
await releaseCryptoProxy();
});
const setup = async (hasFingerprint: boolean) => {
minimalCache();
addToCache('Addresses', [{ Email: receiver.Address } as Address]);
const { receiverKeys, senderKeys } = await setupContactsForPinKeys(hasFingerprint);
addApiMock('core/v4/keys/all', () => ({ Address: { Keys: [{ PublicKey: senderKeys.publicKeyArmored }] } }));
addApiMock(
'contacts/v4/contacts/emails',
() => ({
ContactEmails: [{ Email: sender.Address, ContactID: contactID } as ContactEmail] as ContactEmail[],
}),
'get'
);
const updateSpy = jest.fn();
addApiMock(`contacts/v4/contacts/${contactID}`, updateSpy, 'put');
addKeysToUserKeysCache(receiverKeys);
const onResignSpy = jest.fn();
const container = await render(
<ContactResignModal title={title} contacts={contacts} onResign={onResignSpy} open>
{children}
</ContactResignModal>,
false
);
return { container, senderKeys, updateSpy, onResignSpy };
};
it('should resign the contact and render email rows', async () => {
const {
container: { getByText, getByTestId },
senderKeys,
updateSpy,
onResignSpy,
} = await setup(true);
// Modal and content are displayed
getByText(title);
getByText(children);
// Email rows are rendered (Email + fingerprints)
await waitFor(() => getByText(`${sender.Address}:`));
const expectedFingerPrint = senderKeys.publicKeys[0].getFingerprint();
getByText(expectedFingerPrint);
// Click on Re-sign button
const resignButton = getByTestId('resign-contact');
fireEvent.click(resignButton);
await tick();
// Contact update is called
expect(updateSpy).toHaveBeenCalled();
// Optional on Resign action is called
expect(onResignSpy).toHaveBeenCalled();
});
it('should resign the contact not render email rows', async () => {
const {
container: { getByText, queryByText, getByTestId },
updateSpy,
onResignSpy,
} = await setup(false);
// Modal and content are displayed
getByText(title);
getByText(children);
// Email rows are not rendered
const emailRow = queryByText(`${sender.Address}:`);
expect(emailRow).toBeNull();
// Click on Re-sign button
const resignButton = getByTestId('resign-contact');
fireEvent.click(resignButton);
await tick();
// Contact update is called
expect(updateSpy).toHaveBeenCalled();
// Optional on Resign action is called
expect(onResignSpy).toHaveBeenCalled();
});
});
|
3,669 | 0 | petrpan-code/ProtonMail/WebClients/applications/mail/src/app/components/message | petrpan-code/ProtonMail/WebClients/applications/mail/src/app/components/message/modals/TrustPublicKeyModal.test.tsx | import { fireEvent } from '@testing-library/react';
import { act } from '@testing-library/react';
import { PublicKeyReference } from '@proton/crypto';
import { wait } from '@proton/shared/lib/helpers/promise';
import { ContactWithBePinnedPublicKey } from '@proton/shared/lib/interfaces/contacts';
import { addApiMock } from '../../../helpers/test/api';
import { GeneratedKey, addKeysToUserKeysCache, generateKeys } from '../../../helpers/test/crypto';
import { releaseCryptoProxy, setupCryptoProxyForTesting } from '../../../helpers/test/crypto';
import { clearAll, waitForNotification } from '../../../helpers/test/helper';
import { receiver, sender, setupContactsForPinKeys } from '../../../helpers/test/pinKeys';
import { render, tick } from '../../../helpers/test/render';
import TrustPublicKeyModal from './TrustPublicKeyModal';
const senderAddress = '[email protected]';
const getContact = (senderKey: PublicKeyReference, isContact = false) => {
return {
emailAddress: senderAddress,
name: 'Sender',
contactID: isContact ? 'contactID' : undefined,
isInternal: false,
bePinnedPublicKey: senderKey,
} as ContactWithBePinnedPublicKey;
};
describe('Trust public key modal', () => {
beforeAll(async () => {
await setupCryptoProxyForTesting();
});
afterAll(async () => {
await releaseCryptoProxy();
});
afterEach(clearAll);
const setup = async (senderKeys: GeneratedKey, isContact: boolean) => {
const contact = getContact(senderKeys.publicKeys[0], isContact);
const component = await render(<TrustPublicKeyModal contact={contact} open />);
return component;
};
it('should update contact when trusting key if contact already exists', async () => {
// Create the contact
const { senderKeys, receiverKeys, updateSpy } = await setupContactsForPinKeys();
addKeysToUserKeysCache(receiverKeys);
const { getByText, getByTestId } = await setup(senderKeys, true);
// Modal is displayed
getByText('Trust public key?');
// Click on Trust key button
const submitButton = getByTestId('trust-key-modal:submit');
// Without the wait the test is sometimes failing because the call is not done
await act(async () => {
fireEvent.click(submitButton);
await wait(100);
});
// Contact has been updated
expect(updateSpy).toHaveBeenCalled();
});
it('should create a contact when trusting key if contact does not exists', async () => {
const senderKeys = await generateKeys('sender', sender.Address);
const receiverKeys = await generateKeys('me', receiver.Address);
addKeysToUserKeysCache(receiverKeys);
const createSpy = jest.fn(() => {
return {
Responses: [
{
Response: { Code: 1000 },
},
],
};
});
addApiMock('contacts/v4/contacts', createSpy, 'post');
const { getByText, getByTestId } = await setup(senderKeys, false);
// Modal is displayed
getByText('Trust public key?');
// Click on Trust key button
const submitButton = getByTestId('trust-key-modal:submit');
fireEvent.click(submitButton);
await tick();
// Contact has been created
expect(createSpy).toHaveBeenCalled();
});
it('should display a notification when key could not be trusted', async () => {
const senderKeys = await generateKeys('sender', sender.Address);
const receiverKeys = await generateKeys('me', receiver.Address);
addKeysToUserKeysCache(receiverKeys);
const createSpy = jest.fn(() => {
return {
Responses: [
{
Response: { Code: 1002 }, // Wrong api code to trigger the error
},
],
};
});
addApiMock('contacts/v4/contacts', createSpy, 'post');
const { getByText, getByTestId } = await setup(senderKeys, false);
// Modal is displayed
getByText('Trust public key?');
// Click on Trust key button
const submitButton = getByTestId('trust-key-modal:submit');
fireEvent.click(submitButton);
await tick();
// Contact has been created
expect(createSpy).toHaveBeenCalled();
await waitForNotification('Public key could not be trusted');
});
});
|
3,682 | 0 | petrpan-code/ProtonMail/WebClients/applications/mail/src/app/components/message/recipients | petrpan-code/ProtonMail/WebClients/applications/mail/src/app/components/message/recipients/tests/MailRecipientItemSingle.blockSender.test.tsx | import { act } from 'react-dom/test-utils';
import { fireEvent } from '@testing-library/react';
import { RenderResult, queryByTestId } from '@testing-library/react';
import { INCOMING_DEFAULTS_LOCATION, MIME_TYPES } from '@proton/shared/lib/constants';
import { IncomingDefault, MailSettings, Recipient } from '@proton/shared/lib/interfaces';
import { BLOCK_SENDER_CONFIRMATION } from '@proton/shared/lib/mail/constants';
import {
addApiMock,
addToCache,
clearAll,
getDropdown,
minimalCache,
render,
setFeatureFlags,
waitForNotification,
} from '../../../../helpers/test/helper';
import { load } from '../../../../logic/incomingDefaults/incomingDefaultsActions';
import { MessageState } from '../../../../logic/messages/messagesTypes';
import { store } from '../../../../logic/store';
import MailRecipientItemSingle from '../MailRecipientItemSingle';
const meAddress = '[email protected]';
const me2Address = '[email protected]';
const alreadyBlockedAddress = '[email protected]';
const recipientAddress = '[email protected]';
const normalSenderAddress = '[email protected]';
const spamSenderAddress = '[email protected]';
const inboxSenderAddress = '[email protected]';
const spamSenderID = 'spamSender';
const modalsHandlers = {
onContactDetails: jest.fn(),
onContactEdit: jest.fn(),
};
const getTestMessageToBlock = (sender: Recipient) => {
return {
localID: 'message',
data: {
ID: 'message',
MIMEType: 'text/plain' as MIME_TYPES,
Subject: '',
Sender: sender,
ToList: [] as Recipient[],
ConversationID: 'conversationID',
},
} as MessageState;
};
const openDropdown = async (container: RenderResult, sender: Recipient) => {
const { getByTestId } = container;
const recipientItem = getByTestId(`recipient:details-dropdown-${sender.Address}`);
fireEvent.click(recipientItem);
const fromDropdown = await getDropdown();
return fromDropdown;
};
const setup = async (sender: Recipient, isRecipient = false, hasBlockSenderConfimationChecked = false) => {
minimalCache();
addToCache('MailSettings', {
BlockSenderConfirmation: hasBlockSenderConfimationChecked ? BLOCK_SENDER_CONFIRMATION.DO_NOT_ASK : undefined,
} as MailSettings);
addToCache('Addresses', [
{
Email: meAddress,
},
{
Email: me2Address,
},
]);
setFeatureFlags('BlockSender', true);
addApiMock('mail/v4/incomingdefaults', () => {
return {
IncomingDefaults: [
{
ID: 'alreadyBlocked',
Email: alreadyBlockedAddress,
Location: INCOMING_DEFAULTS_LOCATION.BLOCKED,
},
{
ID: spamSenderID,
Email: spamSenderAddress,
Location: INCOMING_DEFAULTS_LOCATION.SPAM,
},
{
ID: 'inboxSender',
Email: inboxSenderAddress,
Location: INCOMING_DEFAULTS_LOCATION.INBOX,
},
] as IncomingDefault[],
Total: 1,
GlobalTotal: 3,
};
});
const message = getTestMessageToBlock(sender);
const container = await render(
<MailRecipientItemSingle message={message} recipient={sender} isRecipient={isRecipient} {...modalsHandlers} />,
false
);
// Load manually incoming defaults
await store.dispatch(load());
const dropdown = await openDropdown(container, sender);
const blockSenderOption = queryByTestId(dropdown, 'block-sender:button');
return { container, dropdown, blockSenderOption };
};
describe('MailRecipientItemSingle block sender option in dropdown', () => {
afterEach(clearAll);
it('should not be possible to block sender if sender is the user', async () => {
const sender = {
Name: 'Me',
Address: meAddress,
} as Recipient;
const { blockSenderOption } = await setup(sender);
expect(blockSenderOption).toBeNull();
});
it('should not be possible to block sender if sender is a secondary address of the user', async () => {
const sender = {
Name: 'Me2',
Address: me2Address,
} as Recipient;
const { blockSenderOption } = await setup(sender);
expect(blockSenderOption).toBeNull();
});
it('should not be possible to block sender if sender is already blocked', async () => {
const sender = {
Name: 'already blocked',
Address: alreadyBlockedAddress,
} as Recipient;
const { blockSenderOption } = await setup(sender);
expect(blockSenderOption).toBeNull();
});
it('should not be possible to block sender if item is a recipient and not a sender', async () => {
const sender = {
Name: 'recipient',
Address: recipientAddress,
} as Recipient;
const { blockSenderOption } = await setup(sender, true);
expect(blockSenderOption).toBeNull();
});
it('should be possible to block sender', async () => {
const sender = {
Name: 'normal sender',
Address: normalSenderAddress,
} as Recipient;
const { blockSenderOption } = await setup(sender);
expect(blockSenderOption).not.toBeNull();
});
it('should be possible to block sender if already flagged as spam', async () => {
const sender = {
Name: 'spam sender',
Address: spamSenderAddress,
} as Recipient;
const { blockSenderOption } = await setup(sender);
expect(blockSenderOption).not.toBeNull();
});
it('should be possible to block sender if already flagged as inbox', async () => {
const sender = {
Name: 'inbox sender',
Address: inboxSenderAddress,
} as Recipient;
const { blockSenderOption } = await setup(sender);
expect(blockSenderOption).not.toBeNull();
});
});
describe('MailRecipientItemSingle blocking a sender', () => {
afterEach(clearAll);
const blockSender = async (
container: RenderResult,
senderAddress: string,
blockSenderOption: HTMLElement | null,
selectDoNotAsk = false
) => {
const { findByText, findByTestId } = container;
if (blockSenderOption) {
fireEvent.click(blockSenderOption);
}
// Modal is displayed
await findByText('Block sender');
await findByText(`New emails from ${senderAddress} won't be delivered and will be permanently deleted.`);
// Should check do not ask again
if (selectDoNotAsk) {
const checkbox = await findByTestId('block-sender-modal-dont-show:checkbox');
act(() => {
fireEvent.click(checkbox);
});
}
// Block sender
const blockButton = await findByTestId('block-sender-modal-block:button');
act(() => {
fireEvent.click(blockButton);
});
};
it('should block a sender', async () => {
const createSpy = jest.fn(() => ({
IncomingDefault: {
ID: 'normalSender',
Email: normalSenderAddress,
Location: INCOMING_DEFAULTS_LOCATION.BLOCKED,
} as IncomingDefault,
}));
addApiMock('mail/v4/incomingdefaults?Overwrite=1', createSpy, 'post');
const sender = {
Name: 'normal sender',
Address: normalSenderAddress,
} as Recipient;
const { container, blockSenderOption } = await setup(sender);
await blockSender(container, normalSenderAddress, blockSenderOption);
expect(createSpy).toHaveBeenCalled();
await waitForNotification(`Sender ${normalSenderAddress} blocked`);
});
it('should block a sender already in incoming defaults', async () => {
const createSpy = jest.fn(() => ({
IncomingDefault: {
Email: spamSenderAddress,
Location: INCOMING_DEFAULTS_LOCATION.BLOCKED,
} as IncomingDefault,
}));
addApiMock(`mail/v4/incomingdefaults?Overwrite=1`, createSpy, 'post');
const sender = {
Name: 'spam sender',
Address: spamSenderAddress,
} as Recipient;
const { container, blockSenderOption } = await setup(sender);
await blockSender(container, spamSenderAddress, blockSenderOption);
expect(createSpy).toHaveBeenCalled();
await waitForNotification(`Sender ${spamSenderAddress} blocked`);
});
it('should block a sender and apply do not ask', async () => {
const createSpy = jest.fn(() => ({
IncomingDefault: {
ID: 'normalSender',
Email: normalSenderAddress,
Location: INCOMING_DEFAULTS_LOCATION.BLOCKED,
} as IncomingDefault,
}));
addApiMock('mail/v4/incomingdefaults?Overwrite=1', createSpy, 'post');
const doNotAskSpy = jest.fn(() => ({
BlockSenderConfirmation: BLOCK_SENDER_CONFIRMATION.DO_NOT_ASK,
}));
addApiMock('mail/v4/settings/block-sender-confirmation', doNotAskSpy, 'put');
const sender = {
Name: 'normal sender',
Address: normalSenderAddress,
} as Recipient;
const { container, blockSenderOption } = await setup(sender);
await blockSender(container, normalSenderAddress, blockSenderOption, true);
expect(createSpy).toHaveBeenCalled();
expect(doNotAskSpy).toHaveBeenCalled();
await waitForNotification(`Sender ${normalSenderAddress} blocked`);
});
it('should block a sender and not open the modal', async () => {
const createSpy = jest.fn(() => ({
IncomingDefault: {
ID: 'normalSender',
Email: normalSenderAddress,
Location: INCOMING_DEFAULTS_LOCATION.BLOCKED,
} as IncomingDefault,
}));
addApiMock('mail/v4/incomingdefaults?Overwrite=1', createSpy, 'post');
const sender = {
Name: 'normal sender',
Address: normalSenderAddress,
} as Recipient;
const { blockSenderOption } = await setup(sender, false, true);
// Click on block sender option, no modal should be displayed
if (blockSenderOption) {
fireEvent.click(blockSenderOption);
}
expect(createSpy).toHaveBeenCalled();
await waitForNotification(`Sender ${normalSenderAddress} blocked`);
});
});
|
3,683 | 0 | petrpan-code/ProtonMail/WebClients/applications/mail/src/app/components/message/recipients | petrpan-code/ProtonMail/WebClients/applications/mail/src/app/components/message/recipients/tests/MailRecipientItemSingle.test.tsx | import { Matcher, fireEvent } from '@testing-library/react';
import { Recipient } from '@proton/shared/lib/interfaces';
import { GeneratedKey, generateKeys } from '../../../../helpers/test/crypto';
import { releaseCryptoProxy, setupCryptoProxyForTesting } from '../../../../helpers/test/crypto';
import { clearAll } from '../../../../helpers/test/helper';
import { render, tick } from '../../../../helpers/test/render';
import MailRecipientItemSingle from '../MailRecipientItemSingle';
const senderAddress = '[email protected]';
const sender = {
Name: 'sender',
Address: senderAddress,
} as Recipient;
const modalsHandlers = {
onContactDetails: jest.fn(),
onContactEdit: jest.fn(),
};
describe('MailRecipientItemSingle trust public key item in dropdown', () => {
let senderKeys: GeneratedKey;
beforeAll(async () => {
await setupCryptoProxyForTesting();
senderKeys = await generateKeys('sender', senderAddress);
});
afterAll(async () => {
await releaseCryptoProxy();
});
afterEach(clearAll);
const openDropdown = async (
getByTestId: (text: Matcher) => HTMLElement,
getByText: (text: Matcher) => HTMLElement
) => {
// Open the dropdown
const recipientItem = getByTestId(`recipient:details-dropdown-${sender.Address}`);
fireEvent.click(recipientItem);
await tick();
// The dropdown must be open
getByText('New message');
};
it('should not contain the trust key action in the dropdown', async () => {
const { queryByText, getByTestId, getByText } = await render(
<MailRecipientItemSingle recipient={sender} {...modalsHandlers} />
);
await openDropdown(getByTestId, getByText);
// Trust public key dropdown item should not be found
const dropdownItem = queryByText('Trust public key');
expect(dropdownItem).toBeNull();
});
it('should contain the trust key action in the dropdown if signing key', async () => {
const { getByTestId, getByText } = await render(
<MailRecipientItemSingle
recipient={sender}
signingPublicKey={senderKeys.publicKeys[0]}
{...modalsHandlers}
/>
);
await openDropdown(getByTestId, getByText);
// Trust public key dropdown item should be found
getByText('Trust public key');
});
it('should contain the trust key action in the dropdown if attached key', async () => {
const { getByTestId, getByText } = await render(
<MailRecipientItemSingle
recipient={sender}
attachedPublicKey={senderKeys.publicKeys[0]}
{...modalsHandlers}
/>
);
await openDropdown(getByTestId, getByText);
// Trust public key dropdown item should be found
getByText('Trust public key');
});
});
|
3,684 | 0 | petrpan-code/ProtonMail/WebClients/applications/mail/src/app/components/message | petrpan-code/ProtonMail/WebClients/applications/mail/src/app/components/message/tests/Message.attachments.test.tsx | import { fireEvent, within } from '@testing-library/react';
import { MIME_TYPES } from '@proton/shared/lib/constants';
import humanSize from '@proton/shared/lib/helpers/humanSize';
import { Attachment, Message } from '@proton/shared/lib/interfaces/mail/Message';
import { VERIFICATION_STATUS } from '@proton/shared/lib/mail/constants';
import { assertIcon } from '../../../helpers/test/assertion';
import { releaseCryptoProxy, setupCryptoProxyForTesting } from '../../../helpers/test/crypto';
import {
GeneratedKey,
addApiKeys,
addApiMock,
clearAll,
createEmbeddedImage,
createMessageImages,
encryptMessage,
generateKeys,
tick,
} from '../../../helpers/test/helper';
import { store } from '../../../logic/store';
import { addressID, body, initMessage, messageID, setup, subject } from './Message.test.helpers';
const cid = 'cid';
const attachment1 = {
ID: 'id1',
Name: 'attachment-name-unknown',
Size: 100,
Headers: { 'content-id': cid },
nameSplitStart: 'attachment-name-unkn',
nameSplitEnd: 'own',
};
const attachment2 = {
ID: 'id2',
Name: 'attachment-name-pdf.pdf',
Size: 200,
MIMEType: 'application/pdf',
nameSplitStart: 'attachment-name-p',
nameSplitEnd: 'df.pdf',
};
const attachment3 = {
ID: 'id3',
Name: 'attachment-name-png.png',
Size: 300,
MIMEType: 'image/png',
// Allow to skip actual download of the file content
Preview: {
data: [],
filename: 'preview',
signatures: [],
verified: VERIFICATION_STATUS.NOT_SIGNED,
},
nameSplitStart: 'attachment-name-p',
nameSplitEnd: 'ng.png',
};
describe('Message attachments', () => {
const Attachments = [attachment1, attachment2, attachment3];
const NumAttachments = Attachments.length;
const icons = ['md-unknown', 'md-pdf', 'md-image'];
const totalSize = Attachments.map((attachment) => attachment.Size).reduce((acc, size) => acc + size, 0);
const embeddedImage = createEmbeddedImage(attachment1);
const messageImages = createMessageImages([embeddedImage]);
afterEach(clearAll);
it('should show attachments with their correct icon', async () => {
initMessage({ data: { NumAttachments, Attachments } });
const { getAllByTestId } = await setup();
const items = getAllByTestId('attachment-item');
expect(items.length).toBe(NumAttachments);
for (let i = 0; i < NumAttachments; i++) {
const { getByText, getByTestId } = within(items[i]);
getByText(Attachments[i].nameSplitStart);
getByText(Attachments[i].nameSplitEnd);
const attachmentSizeText = getByTestId('attachment-item:size').textContent;
expect(attachmentSizeText).toEqual(humanSize(Attachments[i].Size));
assertIcon(items[i].querySelector('svg'), icons[i], undefined, 'mime');
}
});
it('should show global size and counters', async () => {
initMessage({ data: { NumAttachments, Attachments }, messageImages });
const { getByTestId } = await setup();
const header = getByTestId('attachment-list:header');
expect(header.textContent).toMatch(String(totalSize));
expect(header.textContent).toMatch(/2\s*files/);
expect(header.textContent).toMatch(/1\s*embedded/);
});
it('should open preview when clicking', async () => {
window.URL.createObjectURL = jest.fn();
initMessage({ data: { NumAttachments, Attachments } });
const { getAllByTestId } = await setup();
const items = getAllByTestId('attachment-item');
const itemButton = items[2].querySelectorAll('button')[1];
fireEvent.click(itemButton);
await tick();
const preview = document.querySelector('.file-preview');
expect(preview).toBeDefined();
expect(preview?.textContent).toMatch(new RegExp(attachment3.Name));
expect(preview?.textContent).toMatch(/3of3/);
});
});
describe('NumAttachments from message initialization', () => {
const toAddress = '[email protected]';
const fromName = 'someone';
const fromAddress = '[email protected]';
let toKeys: GeneratedKey;
let fromKeys: GeneratedKey;
beforeAll(async () => {
await setupCryptoProxyForTesting();
toKeys = await generateKeys('me', toAddress);
fromKeys = await generateKeys('someone', fromAddress);
});
afterAll(async () => {
await releaseCryptoProxy();
});
it('should have the correct NumAttachments', async () => {
const receivedNumAttachment = 1;
addApiKeys(false, fromAddress, []);
const encryptedBody = await encryptMessage(body, fromKeys, toKeys);
addApiMock(`mail/v4/messages/${messageID}`, () => ({
Message: {
ID: messageID,
AddressID: addressID,
Subject: subject,
Sender: { Name: fromName, Address: fromAddress },
Body: encryptedBody,
MIMEType: MIME_TYPES.DEFAULT,
Attachments: [attachment1] as Attachment[],
NumAttachments: receivedNumAttachment,
} as Message,
}));
const { open } = await setup({ conversationMode: true });
await open();
const messageFromCache = store.getState().messages[messageID];
expect(messageFromCache?.data?.NumAttachments).toEqual(receivedNumAttachment);
});
it('should update NumAttachments', async () => {
const receivedNumAttachment = 0;
const expectedNumAttachments = 1;
addApiKeys(false, fromAddress, []);
const encryptedBody = await encryptMessage(body, fromKeys, toKeys);
addApiMock(`mail/v4/messages/${messageID}`, () => ({
Message: {
ID: messageID,
AddressID: addressID,
Subject: subject,
Sender: { Name: fromName, Address: fromAddress },
Body: encryptedBody,
MIMEType: MIME_TYPES.DEFAULT,
Attachments: [attachment1] as Attachment[],
NumAttachments: receivedNumAttachment,
} as Message,
}));
const { open } = await setup({ conversationMode: true });
await open();
const messageFromCache = store.getState().messages[messageID];
expect(messageFromCache?.data?.NumAttachments).not.toEqual(receivedNumAttachment);
expect(messageFromCache?.data?.NumAttachments).toEqual(expectedNumAttachments);
});
});
|
3,685 | 0 | petrpan-code/ProtonMail/WebClients/applications/mail/src/app/components/message | petrpan-code/ProtonMail/WebClients/applications/mail/src/app/components/message/tests/Message.banners.test.tsx | import { waitFor } from '@testing-library/react';
import { setBit } from '@proton/shared/lib/helpers/bitset';
import { MESSAGE_FLAGS } from '@proton/shared/lib/mail/constants';
import { addAddressToCache, minimalCache } from '../../../helpers/test/cache';
import { clearAll } from '../../../helpers/test/helper';
import { initMessage, setup } from './Message.test.helpers';
describe('Message banners', () => {
afterEach(clearAll);
it('should show expiration banner', async () => {
const ExpirationTime = new Date().getTime() / 1000 + 1000;
initMessage({ data: { ExpirationTime } });
const { getByTestId } = await setup();
const banner = await waitFor(() => getByTestId('expiration-banner'));
expect(banner.textContent).toMatch(/This message will expire/);
});
it('should show the decrypted subject banner', async () => {
const decryptedSubject = 'decrypted-subject';
initMessage({ data: { Subject: '...' }, decryption: { decryptedSubject } });
const { getByTestId } = await setup();
const banner = getByTestId('encrypted-subject-banner');
expect(banner.textContent).toMatch(new RegExp(decryptedSubject));
});
it('should show the spam banner', async () => {
initMessage({
data: {
Flags: setBit(
MESSAGE_FLAGS.FLAG_PHISHING_AUTO,
setBit(MESSAGE_FLAGS.FLAG_SENT, setBit(0, MESSAGE_FLAGS.FLAG_RECEIVED))
),
},
});
const { getByTestId } = await setup();
const banner = getByTestId('spam-banner:phishing-banner');
expect(banner.textContent).toMatch(/phishing/);
});
it('should show error banner for network error', async () => {
initMessage({ errors: { network: [new Error('test')] } });
const { getByTestId } = await setup();
const banner = getByTestId('errors-banner');
expect(banner.textContent).toMatch(/error/);
});
it('should show the unsubscribe banner with one click method', async () => {
const toAddress = '[email protected]';
minimalCache();
addAddressToCache({ Email: toAddress });
initMessage({
data: {
ParsedHeaders: { 'X-Original-To': toAddress },
UnsubscribeMethods: { OneClick: 'OneClick' },
},
});
const { getByTestId } = await setup({}, false);
const banner = getByTestId('unsubscribe-banner');
expect(banner.textContent).toMatch(/Unsubscribe/);
});
// it('AUTOPROMPT', async () => {});
// it('PIN_UNSEEN', async () => {});
// it('PIN_ATTACHED_SIGNING mode', async () => {});
// it('PIN_ATTACHED mode', async () => {});
});
|
3,686 | 0 | petrpan-code/ProtonMail/WebClients/applications/mail/src/app/components/message | petrpan-code/ProtonMail/WebClients/applications/mail/src/app/components/message/tests/Message.content.test.tsx | import { fireEvent, screen } from '@testing-library/react';
import { MIME_TYPES } from '@proton/shared/lib/constants';
import { Message } from '@proton/shared/lib/interfaces/mail/Message';
import { addApiKeys } from '../../../helpers/test/crypto';
import { initialize } from '../../../logic/messages/read/messagesReadActions';
import { store } from '../../../logic/store';
import {
MESSAGE_IFRAME_PRINT_CLASS,
MESSAGE_IFRAME_PRINT_FOOTER_ID,
MESSAGE_IFRAME_PRINT_HEADER_ID,
} from '../constants';
import { getIframeRootDiv, setup } from './Message.test.helpers';
describe('Message content', () => {
describe('plain text', () => {
it('should not contain print classes and elements', async () => {
const ID1 = 'ID1';
const sender1Email = '[email protected]';
addApiKeys(false, sender1Email, []);
const message1 = {
localID: ID1,
data: {
ID: ID1,
Body: 'something',
MIMEType: MIME_TYPES.PLAINTEXT,
Sender: { Name: '', Address: sender1Email },
} as Message,
messageDocument: { initialized: true, plainText: 'Body1' },
};
store.dispatch(initialize(message1));
const { container } = await setup({ message: message1.data });
const iframe = await getIframeRootDiv(container);
const wrapper = document.createElement('div');
wrapper.appendChild(iframe);
expect(wrapper.querySelector('.proton-plain-text')).not.toBe(null);
expect(wrapper.querySelector('.' + MESSAGE_IFRAME_PRINT_CLASS)).toBe(null);
expect(wrapper.querySelector('#' + MESSAGE_IFRAME_PRINT_HEADER_ID)).toBe(null);
expect(wrapper.querySelector('#' + MESSAGE_IFRAME_PRINT_FOOTER_ID)).toBe(null);
});
// Issues displaying dropdown.
it.skip('should contain print classes and elements', async () => {
const ID1 = 'ID1';
const sender1Email = '[email protected]';
addApiKeys(false, sender1Email, []);
const message1 = {
localID: ID1,
data: {
ID: ID1,
Body: 'something',
MIMEType: MIME_TYPES.PLAINTEXT,
Sender: { Name: '', Address: sender1Email },
} as Message,
messageDocument: { initialized: true, plainText: 'Body1' },
};
store.dispatch(initialize(message1));
await setup({ message: message1.data });
const moreDropdown = await screen.findByTestId('message-header-expanded:more-dropdown');
fireEvent.click(moreDropdown);
const printButton = await screen.findByTestId('message-view-more-dropdown:print');
fireEvent.click(printButton);
const printModal = await screen.findByTestId('modal:print-message');
const iframe = await getIframeRootDiv(printModal.querySelector('iframe') as HTMLIFrameElement);
const wrapper = document.createElement('div');
wrapper.appendChild(iframe);
expect(wrapper.querySelector('.proton-plain-text')).not.toBe(null);
expect(wrapper.querySelector('.' + MESSAGE_IFRAME_PRINT_CLASS)).not.toBe(null);
expect(wrapper.querySelector('#' + MESSAGE_IFRAME_PRINT_HEADER_ID)).not.toBe(null);
expect(wrapper.querySelector('#' + MESSAGE_IFRAME_PRINT_FOOTER_ID)).not.toBe(null);
});
});
});
|
3,687 | 0 | petrpan-code/ProtonMail/WebClients/applications/mail/src/app/components/message | petrpan-code/ProtonMail/WebClients/applications/mail/src/app/components/message/tests/Message.dark.test.tsx | import { waitFor } from '@testing-library/react';
import { FeatureCode } from '@proton/components';
import { Message } from '@proton/shared/lib/interfaces/mail/Message';
import { addApiMock, clearAll, createDocument, minimalCache, setFeatureFlags } from '../../../helpers/test/helper';
import { MessageState } from '../../../logic/messages/messagesTypes';
import { getIframeRootDiv, initMessage, setup as messageSetup } from './Message.test.helpers';
jest.mock('@proton/components/containers/themes/ThemeProvider', () => {
return {
useTheme: () => ({ information: { dark: true } }),
};
});
describe('Message dark styles', () => {
afterEach(clearAll);
const setup = async (content: string) => {
addApiMock('metrics', () => ({}));
setFeatureFlags(FeatureCode.DarkStylesInBody, true);
const document = createDocument(content);
const message: MessageState = {
localID: 'messageID',
data: {
ID: 'messageID',
} as Message,
messageDocument: { document },
};
minimalCache();
initMessage(message);
const { container } = await messageSetup({}, false);
const iframe = await getIframeRootDiv(container);
await waitFor(() => {
const placeholders = container.querySelectorAll('.message-content-loading-placeholder');
if (placeholders.length > 0) {
throw new Error('placeholders');
}
});
return iframe.classList.contains('proton-dark-style');
};
it('should activate dark style when no contrast issue', async () => {
const content = `
<div>
<p>this is a test</p>
<p>with no special style</p>
</div>
`;
const hasDarkStyle = await setup(content);
expect(hasDarkStyle).toBe(true);
});
it('should not activate dark style when a contrast issue is found', async () => {
const content = `
<div>
<p>this is a test</p>
<p style='color: #111'>with forced color</p>
</div>
`;
const hasDarkStyle = await setup(content);
expect(hasDarkStyle).toBe(false);
});
it('should deal with transparent backgrounds', async () => {
const content = `
<div>
<p>this is a test</p>
<p style='background: #0000'>with transparent background</p>
</div>
`;
const hasDarkStyle = await setup(content);
expect(hasDarkStyle).toBe(true);
});
it('should deal with forced light', async () => {
const content = `
<div>
<p>this is a test</p>
<p style='color: #fff; background: #000'>with forced light section</p>
</div>
`;
const hasDarkStyle = await setup(content);
expect(hasDarkStyle).toBe(true);
});
});
|
3,688 | 0 | petrpan-code/ProtonMail/WebClients/applications/mail/src/app/components/message | petrpan-code/ProtonMail/WebClients/applications/mail/src/app/components/message/tests/Message.encryption.test.tsx | import { findByText } from '@testing-library/react';
import { MIME_TYPES } from '@proton/shared/lib/constants';
import { Attachment, Message } from '@proton/shared/lib/interfaces/mail/Message';
import { parseInDiv } from '../../../helpers/dom';
import { constructMime } from '../../../helpers/send/sendMimeBuilder';
import { addApiContact } from '../../../helpers/test/contact';
import { releaseCryptoProxy, setupCryptoProxyForTesting } from '../../../helpers/test/crypto';
import {
GeneratedKey,
addApiKeys,
addApiMock,
addKeysToAddressKeysCache,
addKeysToUserKeysCache,
api,
assertIcon,
clearAll,
encryptMessage,
generateKeys,
} from '../../../helpers/test/helper';
import { MessageKeys } from '../../../logic/messages/messagesTypes';
import { X_PM_HEADERS } from '../../../models/crypto';
import { addressID, body, getIframeRootDiv, localID, messageID, setup, subject } from './Message.test.helpers';
jest.setTimeout(20000);
describe('MessageView encryption', () => {
const toAddress = '[email protected]';
const fromName = 'someone';
const fromAddress = '[email protected]';
const otherAddress = '[email protected]';
let toKeys: GeneratedKey;
let fromKeys: GeneratedKey;
let otherKeys: GeneratedKey;
let publicPrivateKey: MessageKeys;
beforeAll(async () => {
await setupCryptoProxyForTesting();
toKeys = await generateKeys('me', toAddress);
fromKeys = await generateKeys('someone', fromAddress);
otherKeys = await generateKeys('other', otherAddress);
publicPrivateKey = {
type: 'publicPrivate',
publicKeys: toKeys.publicKeys,
privateKeys: toKeys.privateKeys,
};
});
afterAll(async () => {
await releaseCryptoProxy();
});
afterEach(clearAll);
describe('Decrypt and render', () => {
it('html', async () => {
addKeysToAddressKeysCache(addressID, toKeys);
addApiKeys(false, fromAddress, []);
const encryptedBody = await encryptMessage(body, fromKeys, toKeys);
addApiMock(`mail/v4/messages/${messageID}`, () => ({
Message: {
ID: messageID,
AddressID: addressID,
Subject: subject,
Sender: { Name: fromName, Address: fromAddress },
Body: encryptedBody,
MIMEType: MIME_TYPES.DEFAULT,
Attachments: [] as Attachment[],
} as Message,
}));
const { open, container } = await setup({ conversationMode: true });
await open();
const iframeContent = await getIframeRootDiv(container);
await findByText(iframeContent, body);
});
it('plaintext', async () => {
addKeysToAddressKeysCache(addressID, toKeys);
addApiKeys(false, fromAddress, []);
const encryptedBody = await encryptMessage(body, fromKeys, toKeys);
addApiMock(`mail/v4/messages/${messageID}`, () => ({
Message: {
ID: messageID,
AddressID: addressID,
Subject: subject,
Sender: { Name: fromName, Address: fromAddress },
Body: encryptedBody,
MIMEType: MIME_TYPES.PLAINTEXT,
Attachments: [] as Attachment[],
} as Message,
}));
const { open, container } = await setup();
await open();
const iframeContent = await getIframeRootDiv(container);
await findByText(iframeContent, body);
});
it('multipart/mixed html', async () => {
const message = {
ID: messageID,
AddressID: addressID,
Subject: subject,
Sender: { Name: fromName, Address: fromAddress },
MIMEType: MIME_TYPES.MIME,
Attachments: [] as Attachment[],
} as Message;
addKeysToAddressKeysCache(addressID, toKeys);
addApiKeys(false, fromAddress, []);
const mimeBody = await constructMime(
{ localID, data: message, messageDocument: { document: parseInDiv(body) } },
publicPrivateKey,
jest.fn(),
jest.fn(),
api,
false
);
const encryptedBody = await encryptMessage(mimeBody, fromKeys, toKeys);
addApiMock(`mail/v4/messages/${messageID}`, () => ({
Message: { ...message, Body: encryptedBody },
}));
const { open, container } = await setup();
await open();
const iframeContent = await getIframeRootDiv(container);
await findByText(iframeContent, body);
});
it('multipart/mixed plaintext', async () => {
const message = {
ID: messageID,
AddressID: addressID,
Subject: subject,
Sender: { Name: fromName, Address: fromAddress },
MIMEType: MIME_TYPES.MIME,
Attachments: [] as Attachment[],
} as Message;
addKeysToAddressKeysCache(addressID, toKeys);
addApiKeys(false, fromAddress, []);
const mimeBody = await constructMime(
{ localID, data: { ...message, MIMEType: MIME_TYPES.PLAINTEXT }, messageDocument: { plainText: body } },
publicPrivateKey,
jest.fn(),
jest.fn(),
api,
false
);
const encryptedBody = await encryptMessage(mimeBody, fromKeys, toKeys);
addApiMock(`mail/v4/messages/${messageID}`, () => ({
Message: { ...message, Body: encryptedBody },
}));
const { open, container } = await setup();
await open();
const iframeContent = await getIframeRootDiv(container);
await findByText(iframeContent, body);
});
});
describe('Signature verification', () => {
it('verified sender internal', async () => {
addKeysToAddressKeysCache(addressID, toKeys);
addKeysToUserKeysCache(toKeys);
addApiKeys(true, fromAddress, [fromKeys]);
addApiContact({ contactID: 'contactID', email: fromAddress, pinKey: fromKeys }, toKeys);
const encryptedBody = await encryptMessage(body, fromKeys, toKeys);
addApiMock(`mail/v4/messages/${messageID}`, () => ({
Message: {
ID: messageID,
AddressID: addressID,
Sender: {
Name: fromName,
Address: fromAddress,
},
Subject: subject,
Body: encryptedBody,
MIMEType: MIME_TYPES.DEFAULT,
Attachments: [] as Attachment[],
ParsedHeaders: {
'X-Pm-Origin': X_PM_HEADERS.INTERNAL,
'X-Pm-Content-Encryption': X_PM_HEADERS.END_TO_END,
} as any,
Time: new Date().getTime(),
} as Message,
}));
const { open, findByTestId } = await setup();
await open();
const icon = await findByTestId('encryption-icon');
assertIcon(icon, 'lock-check-filled', 'color-info');
});
it('verified sender external', async () => {
addKeysToAddressKeysCache(addressID, toKeys);
addKeysToUserKeysCache(toKeys);
addApiKeys(false, fromAddress, [fromKeys]);
addApiContact({ contactID: 'contactID', email: fromAddress, pinKey: fromKeys }, toKeys);
const message = {
ID: messageID,
AddressID: addressID,
Sender: {
Address: fromAddress,
},
Subject: subject,
MIMEType: MIME_TYPES.DEFAULT,
Attachments: [] as Attachment[],
ParsedHeaders: {
'X-Pm-Origin': X_PM_HEADERS.EXTERNAL,
'X-Pm-Content-Encryption': X_PM_HEADERS.END_TO_END,
} as any,
Time: new Date().getTime(),
} as Message;
const mimeBody = await constructMime(
{ localID, data: message, messageDocument: { document: parseInDiv(body) } },
publicPrivateKey,
jest.fn(),
jest.fn(),
api,
false
);
const encryptedBody = await encryptMessage(mimeBody, fromKeys, toKeys);
addApiMock(`mail/v4/messages/${messageID}`, () => ({
Message: { ...message, Body: encryptedBody },
}));
const { open, findByTestId } = await setup();
await open();
const icon = await findByTestId('encryption-icon');
assertIcon(icon, 'lock-check-filled', 'color-success');
});
it('signature verification error', async () => {
addKeysToAddressKeysCache(addressID, toKeys);
addKeysToUserKeysCache(toKeys);
addApiKeys(true, fromAddress, []);
addApiContact({ contactID: 'contactID', email: fromAddress, pinKey: otherKeys }, toKeys);
const encryptedBody = await encryptMessage(body, fromKeys, toKeys);
addApiMock(`mail/v4/messages/${messageID}`, () => ({
Message: {
ID: messageID,
AddressID: addressID,
Sender: {
Name: fromName,
Address: fromAddress,
},
Subject: subject,
Body: encryptedBody,
MIMEType: MIME_TYPES.DEFAULT,
Attachments: [] as Attachment[],
ParsedHeaders: {
'X-Pm-Origin': X_PM_HEADERS.INTERNAL,
'X-Pm-Content-Encryption': X_PM_HEADERS.END_TO_END,
} as any,
Time: new Date().getTime(),
} as Message,
}));
const { open, findByTestId } = await setup();
await open();
const icon = await findByTestId('encryption-icon');
assertIcon(icon, 'lock-exclamation-filled', 'color-info');
});
});
});
|
3,689 | 0 | petrpan-code/ProtonMail/WebClients/applications/mail/src/app/components/message | petrpan-code/ProtonMail/WebClients/applications/mail/src/app/components/message/tests/Message.images.test.tsx | import { findByTestId, fireEvent } from '@testing-library/react';
import { mockWindowLocation, resetWindowLocation } from '@proton/components/helpers/url.test.helpers';
import { Message } from '@proton/shared/lib/interfaces/mail/Message';
import { IMAGE_PROXY_FLAGS, SHOW_IMAGES } from '@proton/shared/lib/mail/mailSettings';
import { addApiMock, addToCache, assertIcon, clearAll, minimalCache } from '../../../helpers/test/helper';
import { createDocument } from '../../../helpers/test/message';
import { MessageState } from '../../../logic/messages/messagesTypes';
import MessageView from '../MessageView';
import { defaultProps, getIframeRootDiv, initMessage, setup } from './Message.test.helpers';
const imageURL = 'imageURL';
const blobURL = 'blobURL';
const content = `<div>
<div>
<table>
<tbody>
<tr>
<td proton-background='${imageURL}' data-testid="image-background">Element</td>
</tr>
</tbody>
</table>
</div>
<div>
<video proton-poster='${imageURL}' data-testid="image-poster">
<source src="" type="video/mp4" />
</video>
</div>
<div>
<picture>
<source media="(min-width:650px)" proton-srcset='${imageURL}' data-testid="image-srcset"/>
<img src='${imageURL}' data-testid="image-srcset2"/>
</picture>
</div>
<div>
<svg width="50" height="50">
<image proton-xlink:href='${imageURL}' data-testid="image-xlinkhref"/>
</svg>
</div>
</div>`;
jest.mock('../../../helpers/dom', () => ({
...jest.requireActual('../../../helpers/dom'),
preloadImage: jest.fn(() => Promise.resolve()),
}));
const windowHostname = 'https://mail.proton.pink';
describe('Message images', () => {
beforeEach(() => {
mockWindowLocation(windowHostname);
});
afterEach(() => {
resetWindowLocation();
});
afterEach(clearAll);
it('should display all elements other than images', async () => {
const document = createDocument(content);
const message: MessageState = {
localID: 'messageID',
data: {
ID: 'messageID',
} as Message,
messageDocument: { document },
messageImages: {
hasEmbeddedImages: false,
hasRemoteImages: true,
showRemoteImages: false,
showEmbeddedImages: true,
trackersStatus: 'not-loaded',
images: [],
},
};
minimalCache();
addToCache('MailSettings', { HideRemoteImages: SHOW_IMAGES.HIDE });
initMessage(message);
const { container, rerender, getByTestId } = await setup({}, false);
const iframe = await getIframeRootDiv(container);
// Check that all elements are displayed in their proton attributes before loading them
const elementBackground = await findByTestId(iframe, 'image-background');
expect(elementBackground.getAttribute('proton-background')).toEqual(imageURL);
const elementPoster = await findByTestId(iframe, 'image-poster');
expect(elementPoster.getAttribute('proton-poster')).toEqual(imageURL);
const elementSrcset = await findByTestId(iframe, 'image-srcset');
expect(elementSrcset.getAttribute('proton-srcset')).toEqual(imageURL);
const elementXlinkhref = await findByTestId(iframe, 'image-xlinkhref');
expect(elementXlinkhref.getAttribute('proton-xlink:href')).toEqual(imageURL);
const loadButton = getByTestId('remote-content:load');
fireEvent.click(loadButton);
// Rerender the message view to check that images have been loaded
await rerender(<MessageView {...defaultProps} />);
const iframeRerendered = await getIframeRootDiv(container);
// Check that proton attribute has been removed after images loading
const updatedElementBackground = await findByTestId(iframeRerendered, 'image-background');
expect(updatedElementBackground.getAttribute('background')).toEqual(imageURL);
const updatedElementPoster = await findByTestId(iframeRerendered, 'image-poster');
expect(updatedElementPoster.getAttribute('poster')).toEqual(imageURL);
// srcset attribute is not loaded so we should check proton-srcset
const updatedElementSrcset = await findByTestId(iframeRerendered, 'image-srcset');
expect(updatedElementSrcset.getAttribute('proton-srcset')).toEqual(imageURL);
const updatedElementXlinkhref = await findByTestId(iframeRerendered, 'image-xlinkhref');
expect(updatedElementXlinkhref.getAttribute('xlink:href')).toEqual(imageURL);
});
it('should load correctly all elements other than images with proxy', async () => {
const forgedURL = `${windowHostname}/api/core/v4/images?Url=imageURL&DryRun=0&UID=uid`;
const document = createDocument(content);
const message: MessageState = {
localID: 'messageID',
data: {
ID: 'messageID',
} as Message,
messageDocument: { document },
messageImages: {
hasEmbeddedImages: false,
hasRemoteImages: true,
showRemoteImages: false,
showEmbeddedImages: true,
trackersStatus: 'not-loaded',
images: [],
},
};
minimalCache();
addToCache('MailSettings', { HideRemoteImages: SHOW_IMAGES.HIDE, ImageProxy: IMAGE_PROXY_FLAGS.PROXY });
initMessage(message);
const { container, rerender, getByTestId } = await setup({}, false);
const iframe = await getIframeRootDiv(container);
// Need to mock this function to mock the blob url
window.URL.createObjectURL = jest.fn(() => blobURL);
// Check that all elements are displayed in their proton attributes before loading them
const elementBackground = await findByTestId(iframe, 'image-background');
expect(elementBackground.getAttribute('proton-background')).toEqual(imageURL);
const elementPoster = await findByTestId(iframe, 'image-poster');
expect(elementPoster.getAttribute('proton-poster')).toEqual(imageURL);
const elementSrcset = await findByTestId(iframe, 'image-srcset');
expect(elementSrcset.getAttribute('proton-srcset')).toEqual(imageURL);
const elementXlinkhref = await findByTestId(iframe, 'image-xlinkhref');
expect(elementXlinkhref.getAttribute('proton-xlink:href')).toEqual(imageURL);
const loadButton = getByTestId('remote-content:load');
fireEvent.click(loadButton);
// Rerender the message view to check that images have been loaded
await rerender(<MessageView {...defaultProps} />);
const iframeRerendered = await getIframeRootDiv(container);
// Check that proton attribute has been removed after images loading
const updatedElementBackground = await findByTestId(iframeRerendered, 'image-background');
expect(updatedElementBackground.getAttribute('background')).toEqual(forgedURL);
const updatedElementPoster = await findByTestId(iframeRerendered, 'image-poster');
expect(updatedElementPoster.getAttribute('poster')).toEqual(forgedURL);
// srcset attribute is not loaded, so we need to check proton-srcset
const updatedElementSrcset = await findByTestId(iframeRerendered, 'image-srcset');
expect(updatedElementSrcset.getAttribute('proton-srcset')).toEqual(imageURL);
const updatedElementXlinkhref = await findByTestId(iframeRerendered, 'image-xlinkhref');
expect(updatedElementXlinkhref.getAttribute('xlink:href')).toEqual(forgedURL);
});
it('should be able to load direct when proxy failed at loading', async () => {
const imageURL = 'imageURL';
const content = `<div><img proton-src="${imageURL}" data-testid="image"/></div>`;
const document = createDocument(content);
const message: MessageState = {
localID: 'messageID',
data: {
ID: 'messageID',
} as Message,
messageDocument: { document },
messageImages: {
hasEmbeddedImages: false,
hasRemoteImages: true,
showRemoteImages: false,
showEmbeddedImages: true,
trackersStatus: 'not-loaded',
images: [],
},
};
addApiMock(`core/v4/images`, () => {
const error = new Error();
(error as any).data = { Code: 2902, Error: 'TEST error message' };
return Promise.reject(error);
});
minimalCache();
addToCache('MailSettings', { HideRemoteImages: SHOW_IMAGES.HIDE, ImageProxy: IMAGE_PROXY_FLAGS.PROXY });
initMessage(message);
const { getByTestId, rerender, container } = await setup({}, false);
const iframe = await getIframeRootDiv(container);
const image = await findByTestId(iframe, 'image');
expect(image.getAttribute('proton-src')).toEqual(imageURL);
let loadButton = getByTestId('remote-content:load');
fireEvent.click(loadButton);
// Rerender the message view to check that images have been loaded through URL
await rerender(<MessageView {...defaultProps} />);
const iframeRerendered = await getIframeRootDiv(container);
const placeholder = iframeRerendered.querySelector('.proton-image-placeholder') as HTMLImageElement;
expect(placeholder).not.toBe(null);
assertIcon(placeholder.querySelector('svg'), 'cross-circle');
loadButton = getByTestId('remote-content:load');
fireEvent.click(loadButton);
// Rerender the message view to check that images have been loaded
await rerender(<MessageView {...defaultProps} />);
const loadedImage = iframeRerendered.querySelector('.proton-image-anchor img') as HTMLImageElement;
expect(loadedImage).toBeDefined();
expect(loadedImage.getAttribute('src')).toEqual(
`https://mail.proton.pink/api/core/v4/images?Url=${imageURL}&DryRun=0&UID=uid`
);
});
});
|
3,690 | 0 | petrpan-code/ProtonMail/WebClients/applications/mail/src/app/components/message | petrpan-code/ProtonMail/WebClients/applications/mail/src/app/components/message/tests/Message.modes.test.tsx | import { act } from '@testing-library/react';
import { addApiResolver, clearAll } from '../../../helpers/test/helper';
import { initMessage, messageID, setup } from './Message.test.helpers';
jest.setTimeout(20000);
describe('Message display modes', () => {
afterEach(clearAll);
it('loading mode', async () => {
addApiResolver(`mail/v4/messages/${messageID}`);
const { ref, getByTestId } = await setup();
const messageView = getByTestId('message-view-0');
act(() => ref.current?.expand());
const placeholders = messageView.querySelectorAll('.message-content-loading-placeholder');
expect(placeholders.length).toBeGreaterThanOrEqual(3);
});
it('encrypted mode', async () => {
const encryptedBody = 'body-test';
initMessage({ data: { Body: encryptedBody }, errors: { decryption: [new Error('test')] } });
const { getByTestId } = await setup();
const errorsBanner = getByTestId('errors-banner');
expect(errorsBanner.textContent).toContain('Decryption error');
const messageView = getByTestId('message-view-0');
expect(messageView.textContent).toContain(encryptedBody);
});
it('source mode on processing error', async () => {
const decryptedBody = 'decrypted-test';
initMessage({
data: { Body: 'test' },
errors: { processing: [new Error('test')] },
decryption: { decryptedBody },
});
const { getByTestId } = await setup();
const errorsBanner = getByTestId('errors-banner');
expect(errorsBanner.textContent).toContain('processing error');
const messageView = getByTestId('message-view-0');
expect(messageView.textContent).toContain(decryptedBody);
});
});
|
3,691 | 0 | petrpan-code/ProtonMail/WebClients/applications/mail/src/app/components/message | petrpan-code/ProtonMail/WebClients/applications/mail/src/app/components/message/tests/Message.recipients.test.tsx | import { ContactEmail, ContactGroup } from '@proton/shared/lib/interfaces/contacts';
import { clearAll } from '../../../helpers/test/helper';
import { refresh } from '../../../logic/contacts/contactsActions';
import { store } from '../../../logic/store';
import { initMessage, setup } from './Message.test.helpers';
describe('Message recipients rendering', () => {
afterEach(clearAll);
it('show a recipient not associated with a contact', async () => {
const Name = 'test-name';
const Address = '[email protected]';
initMessage({ data: { ToList: [{ Name, Address }] } });
const { getByText, details } = await setup();
getByText(Name);
await details();
getByText(Name);
getByText(Address, { exact: false });
});
it('show a recipient matching a contact', async () => {
const Name = 'test-name';
const Address = '[email protected]';
const ContactEmail = {
Email: Address,
Name: 'test-contact',
} as ContactEmail;
store.dispatch(refresh({ contacts: [ContactEmail], contactGroups: [] }));
initMessage({ data: { ToList: [{ Name, Address }] } });
const { getByText, details } = await setup();
getByText(ContactEmail.Name);
await details();
getByText(ContactEmail.Name);
getByText(Address, { exact: false });
});
it('show recipients in a contact group partial', async () => {
const Name = 'test-name';
const Address = '[email protected]';
const ContactGroup = {
ID: 'test-group-id',
Name: 'test-group-name',
Path: 'test-group-path',
} as ContactGroup;
const Group = ContactGroup.Path;
const contacts = [
{ Email: '', LabelIDs: [ContactGroup.ID] },
{ Email: '', LabelIDs: [ContactGroup.ID] },
{ Email: '', LabelIDs: [ContactGroup.ID] },
] as ContactEmail[];
const ToList = [
{ Name, Address, Group },
{ Name, Address, Group },
];
store.dispatch(refresh({ contacts, contactGroups: [ContactGroup] }));
initMessage({ data: { ToList } });
const { getByText } = await setup();
const expectation = `${ContactGroup.Name} (${ToList.length}/${contacts.length})`;
getByText(expectation);
});
it('show recipients in a contact group full', async () => {
const Name = 'test-name';
const Address = '[email protected]';
const ContactGroup = {
ID: 'test-group-id',
Name: 'test-group-name',
Path: 'test-group-path',
} as ContactGroup;
const Group = ContactGroup.Path;
const contacts = [
{ Email: '', LabelIDs: [ContactGroup.ID] },
{ Email: '', LabelIDs: [ContactGroup.ID] },
{ Email: '', LabelIDs: [ContactGroup.ID] },
] as ContactEmail[];
const ToList = [
{ Name, Address, Group },
{ Name, Address, Group },
{ Name, Address, Group },
];
store.dispatch(refresh({ contacts, contactGroups: [ContactGroup] }));
initMessage({ data: { ToList } });
const { getByText } = await setup();
const expectation = `${ContactGroup.Name} (${contacts.length})`;
getByText(expectation);
});
});
|
3,692 | 0 | petrpan-code/ProtonMail/WebClients/applications/mail/src/app/components/message | petrpan-code/ProtonMail/WebClients/applications/mail/src/app/components/message/tests/Message.state.test.tsx | import { findByText } from '@testing-library/react';
import { MIME_TYPES } from '@proton/shared/lib/constants';
import { Message } from '@proton/shared/lib/interfaces/mail/Message';
import { addApiKeys, addApiMock, clearAll } from '../../../helpers/test/helper';
import { initialize } from '../../../logic/messages/read/messagesReadActions';
import { store } from '../../../logic/store';
import { addressID, getIframeRootDiv, initMessage, messageID, setup } from './Message.test.helpers';
describe('message state', () => {
afterEach(clearAll);
it('should initialize message in cache if not existing', async () => {
const senderEmail = '[email protected]';
addApiKeys(false, senderEmail, []);
const Message = {
ID: messageID,
AddressID: addressID,
Attachments: [],
NumAttachments: 0,
Sender: { Name: '', Address: senderEmail },
} as any as Message;
addApiMock(`mail/v4/messages/${messageID}`, () => ({ Message }));
await setup();
const messageFromCache = store.getState().messages[messageID];
expect(messageFromCache).toBeDefined();
expect(messageFromCache?.data).toEqual(Message);
});
it('should returns message from the cache', async () => {
const apiMock = jest.fn();
addApiMock(`mail/v4/messages/${messageID}`, apiMock);
initMessage();
await setup();
expect(apiMock).not.toHaveBeenCalled();
});
it('should handle switching of message', async () => {
const ID1 = 'ID1';
const ID2 = 'ID2';
const sender1Email = '[email protected]';
const sender2Email = '[email protected]';
addApiKeys(false, sender1Email, []);
addApiKeys(false, sender2Email, []);
const message1 = {
localID: ID1,
data: {
ID: ID1,
Body: 'something',
MIMEType: MIME_TYPES.PLAINTEXT,
Sender: { Name: '', Address: sender1Email },
} as Message,
messageDocument: { initialized: true, plainText: 'Body1' },
};
const message2 = {
localID: ID2,
data: {
ID: ID2,
Body: 'something',
MIMEType: MIME_TYPES.PLAINTEXT,
Sender: { Name: '', Address: sender2Email },
} as Message,
messageDocument: { initialized: true, plainText: 'Body2' },
};
store.dispatch(initialize(message1));
store.dispatch(initialize(message2));
const { container, rerender } = await setup({ message: message1.data });
const iframe = await getIframeRootDiv(container);
await findByText(iframe, 'Body1');
await rerender({ message: message2.data });
const iframe2 = await getIframeRootDiv(container);
await findByText(iframe2, 'Body2');
await rerender({ message: message1.data });
const iframe3 = await getIframeRootDiv(container);
await findByText(iframe3, 'Body1');
await rerender({ message: message2.data });
const iframe4 = await getIframeRootDiv(container);
await findByText(iframe4, 'Body2');
});
});
|
3,694 | 0 | petrpan-code/ProtonMail/WebClients/applications/mail/src/app/components/message | petrpan-code/ProtonMail/WebClients/applications/mail/src/app/components/message/tests/Message.trackers.test.tsx | import { fireEvent, screen } from '@testing-library/react';
import { MailSettings } from '@proton/shared/lib/interfaces';
import { Attachment, Message } from '@proton/shared/lib/interfaces/mail/Message';
import { IMAGE_PROXY_FLAGS, SHOW_IMAGES } from '@proton/shared/lib/mail/mailSettings';
import { addApiMock } from '@proton/testing/lib/api';
import noop from '@proton/utils/noop';
import { addToCache, minimalCache } from '../../../helpers/test/cache';
import {
GeneratedKey,
addKeysToAddressKeysCache,
generateKeys,
releaseCryptoProxy,
setupCryptoProxyForTesting,
} from '../../../helpers/test/crypto';
import { encryptMessage } from '../../../helpers/test/message';
import { render } from '../../../helpers/test/render';
import { MessageState } from '../../../logic/messages/messagesTypes';
import { initialize } from '../../../logic/messages/read/messagesReadActions';
import { store } from '../../../logic/store';
import { Breakpoints } from '../../../models/utils';
import MessageView from '../MessageView';
import { addressID, labelID, messageID } from './Message.test.helpers';
const trackerName = 'Tracker.com';
const trackerURL = 'https://tracker.com';
const tracker1URL = `${trackerURL}/1`;
const tracker2URL = `${trackerURL}/2`;
const content = `<div>
<img src={${tracker1URL}} />
<img src={${tracker2URL}} />
</div>`;
describe('message trackers', () => {
const toAddress = '[email protected]';
const fromAddress = '[email protected]';
let toKeys: GeneratedKey;
let fromKeys: GeneratedKey;
beforeAll(async () => {
await setupCryptoProxyForTesting();
toKeys = await generateKeys('me', toAddress);
fromKeys = await generateKeys('someone', fromAddress);
addKeysToAddressKeysCache(addressID, toKeys);
addApiMock('core/v4/keys/all', () => ({ Address: { Keys: [] } }));
});
afterAll(async () => {
await releaseCryptoProxy();
});
it('should display the correct number of trackers before and after load', async () => {
addApiMock(`core/v4/images`, () => {
const map = new Map();
map.set('x-pm-tracker-provider', trackerName);
return { headers: map };
});
minimalCache();
const mailSettings = { HideRemoteImages: SHOW_IMAGES.HIDE, ImageProxy: IMAGE_PROXY_FLAGS.PROXY };
addToCache('MailSettings', mailSettings);
const encryptedBody = await encryptMessage(content, fromKeys, toKeys);
const message = {
ID: messageID,
AddressID: addressID,
Subject: 'test',
Sender: { Name: 'testName', Address: 'testAddress' },
Attachments: [] as Attachment[],
Body: encryptedBody,
} as Message;
addApiMock(`mail/v4/messages/${messageID}`, () => ({
Message: message,
}));
store.dispatch(initialize({ data: { ID: messageID, AddressID: addressID } as Message } as MessageState));
const props = {
labelID,
conversationMode: false,
loading: false,
labels: [],
message: { ID: messageID, AddressID: addressID } as Message,
mailSettings: mailSettings as MailSettings,
onBack: jest.fn(),
breakpoints: {} as Breakpoints,
onFocus: noop,
isComposerOpened: false,
};
await render(<MessageView {...props} />, false);
// Check number of trackers before load
const trackersNumberBeforeLoad = screen.queryByTestId('privacy:icon-number-of-trackers');
expect(trackersNumberBeforeLoad?.innerHTML).toEqual('2');
const loadButton = screen.getByTestId('remote-content:load');
fireEvent.click(loadButton);
// Check number of trackers after load
const trackersNumberAfterLoad = screen.queryByTestId('privacy:icon-number-of-trackers');
expect(trackersNumberAfterLoad?.innerHTML).toEqual('2');
});
});
|
3,707 | 0 | petrpan-code/ProtonMail/WebClients/applications/mail/src/app/components | petrpan-code/ProtonMail/WebClients/applications/mail/src/app/components/sidebar/MailSidebar.test.tsx | import { act } from 'react-dom/test-utils';
import { fireEvent, getAllByText } from '@testing-library/react';
import { Location } from 'history';
import loudRejection from 'loud-rejection';
import { getAppVersion } from '@proton/components';
import useEventManager from '@proton/components/hooks/useEventManager';
import { LABEL_TYPE, MAILBOX_LABEL_IDS } from '@proton/shared/lib/constants';
import { removeItem, setItem } from '@proton/shared/lib/helpers/storage';
import { CHECKLIST_DISPLAY_TYPE } from '@proton/shared/lib/interfaces';
import range from '@proton/utils/range';
import {
ContextState,
useGetStartedChecklist,
} from '../../containers/onboardingChecklist/provider/GetStartedChecklistProvider';
import {
addToCache,
assertFocus,
clearAll,
config,
getDropdown,
getHistory,
minimalCache,
render,
} from '../../helpers/test/helper';
import { SYSTEM_FOLDER_SECTION } from '../../hooks/useMoveSystemFolders';
import MailSidebar from './MailSidebar';
jest.mock('../../../../CHANGELOG.md', () => 'ProtonMail Changelog');
jest.mock('../../containers/onboardingChecklist/provider/GetStartedChecklistProvider', () => ({
__esModule: true,
useGetStartedChecklist: jest.fn(),
default: ({ children }: { children: any }) => <>{children}</>,
}));
jest.mock('../../containers/onboardingChecklist/provider/GetStartedChecklistProvider');
const mockedReturn = useGetStartedChecklist as jest.MockedFunction<any>;
loudRejection();
const labelID = 'labelID';
const props = {
labelID,
location: {} as Location,
onToggleExpand: jest.fn(),
};
const folder = { ID: 'folder1', Type: LABEL_TYPE.MESSAGE_FOLDER, Name: 'folder1' };
const subfolder = { ID: 'folder2', Type: LABEL_TYPE.MESSAGE_FOLDER, Name: 'folder2', ParentID: folder.ID };
const label = { ID: 'label1', Type: LABEL_TYPE.MESSAGE_LABEL, Name: 'label1' };
const systemFolders = [
{
ID: MAILBOX_LABEL_IDS.INBOX,
Name: 'inbox',
Path: 'inbox',
Type: LABEL_TYPE.SYSTEM_FOLDER,
Order: 1,
Display: SYSTEM_FOLDER_SECTION.MAIN,
},
{
ID: MAILBOX_LABEL_IDS.SCHEDULED,
Name: 'all scheduled',
Path: 'all scheduled',
Type: LABEL_TYPE.SYSTEM_FOLDER,
Order: 3,
Display: SYSTEM_FOLDER_SECTION.MAIN,
},
{
ID: MAILBOX_LABEL_IDS.DRAFTS,
Name: 'drafts',
Path: 'drafts',
Type: LABEL_TYPE.SYSTEM_FOLDER,
Order: 4,
Display: SYSTEM_FOLDER_SECTION.MAIN,
},
{
ID: MAILBOX_LABEL_IDS.SENT,
Name: 'sent',
Path: 'sent',
Type: LABEL_TYPE.SYSTEM_FOLDER,
Order: 5,
Display: SYSTEM_FOLDER_SECTION.MAIN,
},
{
ID: MAILBOX_LABEL_IDS.ALL_MAIL,
Name: 'all mail',
Path: 'all mail',
Type: LABEL_TYPE.SYSTEM_FOLDER,
Order: 11,
Display: SYSTEM_FOLDER_SECTION.MAIN,
},
];
const inboxMessages = { LabelID: MAILBOX_LABEL_IDS.INBOX, Unread: 3, Total: 20 };
const allMailMessages = { LabelID: MAILBOX_LABEL_IDS.ALL_MAIL, Unread: 10000, Total: 10001 };
const scheduledMessages = { LabelID: MAILBOX_LABEL_IDS.SCHEDULED, Unread: 1, Total: 4 };
const folderMessages = { LabelID: folder.ID, Unread: 1, Total: 2 };
const labelMessages = { LabelID: label.ID, Unread: 2, Total: 3 };
const setupTest = (labels: any[] = [], messageCounts: any[] = [], conversationCounts: any[] = []) => {
// open the more section otherwise it's closed by default
setItem('item-display-more-items', 'true');
minimalCache();
addToCache('Labels', labels);
addToCache('MessageCounts', messageCounts);
addToCache('ConversationCounts', conversationCounts);
mockedReturn.mockReturnValue({
displayState: CHECKLIST_DISPLAY_TYPE.FULL,
items: new Set(),
} as ContextState);
};
describe('MailSidebar', () => {
const setup = async () => {
minimalCache();
mockedReturn.mockReturnValue({
displayState: CHECKLIST_DISPLAY_TYPE.FULL,
items: new Set(),
} as ContextState);
const result = await render(<MailSidebar {...props} />, false);
return { ...result };
};
afterEach(() => {
clearAll();
// We need to remove the item from the localStorage otherwise it will keep the previous state
removeItem('item-display-folders');
removeItem('item-display-labels');
});
it('should redirect on inbox when click on logo', async () => {
const { getByTestId } = await setup();
const logo = getByTestId('main-logo') as HTMLAnchorElement;
fireEvent.click(logo);
const history = getHistory();
expect(history.length).toBe(1);
expect(history.location.pathname).toBe('/inbox');
});
it('should open app dropdown', async () => {
const { getByTitle } = await setup();
const appsButton = getByTitle('Proton applications');
fireEvent.click(appsButton);
const dropdown = await getDropdown();
getAllByText(dropdown, 'Proton Mail');
getAllByText(dropdown, 'Proton Calendar');
getAllByText(dropdown, 'Proton Drive');
getAllByText(dropdown, 'Proton VPN');
});
it('should show folder tree', async () => {
setupTest([folder, subfolder]);
const { getByTestId, queryByTestId } = await render(<MailSidebar {...props} />, false);
const folderElement = getByTestId(`navigation-link:${folder.ID}`);
const folderIcon = folderElement.querySelector('svg:not(.navigation-icon--expand)');
expect(folderElement.textContent).toContain(folder.Name);
expect((folderIcon?.firstChild as Element).getAttribute('xlink:href')).toBe('#ic-folders');
const subfolderElement = getByTestId(`navigation-link:${subfolder.ID}`);
const subfolderIcon = subfolderElement.querySelector('svg');
expect(subfolderElement.textContent).toContain(subfolder.Name);
expect((subfolderIcon?.firstChild as Element).getAttribute('xlink:href')).toBe('#ic-folder');
const collapseButton = folderElement.querySelector('button');
if (collapseButton) {
fireEvent.click(collapseButton);
}
expect(queryByTestId(`sidebar-item-${subfolder.ID}`)).toBeNull();
});
it('should show label list', async () => {
setupTest([label]);
const { getByTestId } = await render(<MailSidebar {...props} />, false);
const labelElement = getByTestId(`navigation-link:${label.ID}`);
const labelIcon = labelElement.querySelector('svg');
expect(labelElement.textContent).toContain(label.Name);
expect((labelIcon?.firstChild as Element).getAttribute('xlink:href')).toBe('#ic-circle-filled');
});
it('should show unread counters', async () => {
setupTest(
[folder, label, ...systemFolders],
[],
[inboxMessages, allMailMessages, folderMessages, labelMessages]
);
const { getByTestId } = await render(<MailSidebar {...props} />, false);
const inboxElement = getByTestId(`navigation-link:inbox`);
const allMailElement = getByTestId(`navigation-link:all-mail`);
const folderElement = getByTestId(`navigation-link:${folder.ID}`);
const labelElement = getByTestId(`navigation-link:${label.ID}`);
const inBoxLocationAside = inboxElement.querySelector('.navigation-counter-item');
const allMailLocationAside = allMailElement.querySelector('.navigation-counter-item');
const folderLocationAside = folderElement.querySelector('.navigation-counter-item');
const labelLocationAside = labelElement.querySelector('.navigation-counter-item');
expect(inBoxLocationAside?.innerHTML).toBe(`${inboxMessages.Unread}`);
expect(allMailLocationAside?.innerHTML).toBe('9999+');
expect(folderLocationAside?.innerHTML).toBe(`${folderMessages.Unread}`);
expect(labelLocationAside?.innerHTML).toBe(`${labelMessages.Unread}`);
});
it('should navigate to the label on click', async () => {
setupTest([folder]);
const { getByTestId } = await render(<MailSidebar {...props} />, false);
const folderElement = getByTestId(`navigation-link:${folder.ID}`);
const history = getHistory();
expect(history.location.pathname).toBe('/inbox');
act(() => {
fireEvent.click(folderElement);
});
expect(history.location.pathname).toBe(`/${folder.ID}`);
});
it('should call event manager on click if already on label', async () => {
setupTest([folder]);
const { getByTestId } = await render(<MailSidebar {...props} />, false);
const folderElement = getByTestId(`navigation-link:${folder.ID}`);
// Click on the label to be redirected in it
act(() => {
fireEvent.click(folderElement);
});
// Check if we are in the label
expect(getHistory().location.pathname).toBe(`/${folder.ID}`);
// Click again on the label to trigger the event manager
act(() => {
fireEvent.click(folderElement);
});
expect(useEventManager.call).toHaveBeenCalled();
});
it('should show app version and changelog', async () => {
setupTest();
const { getByText } = await render(<MailSidebar {...props} />, false);
const appVersion = getAppVersion(config.APP_VERSION);
const appVersionButton = getByText(appVersion);
// Check if the changelog modal opens on click
fireEvent.click(appVersionButton);
getByText("What's new");
getByText('ProtonMail Changelog');
});
it('should be updated when counters are updated', async () => {
setupTest(systemFolders, [], [inboxMessages]);
const { getByTestId } = await render(<MailSidebar {...props} />, false);
const inboxElement = getByTestId('navigation-link:inbox');
const inBoxLocationAside = inboxElement.querySelector('.navigation-counter-item');
expect(inBoxLocationAside?.innerHTML).toBe(`${inboxMessages.Unread}`);
const inboxMessagesUpdated = { LabelID: '0', Unread: 7, Total: 21 };
act(() => {
addToCache('ConversationCounts', [inboxMessagesUpdated]);
});
expect(inBoxLocationAside?.innerHTML).toBe(`${inboxMessagesUpdated.Unread}`);
});
it('should not show scheduled sidebar item when feature flag is disabled', async () => {
setupTest(systemFolders, [], [scheduledMessages]);
const { queryByTestId } = await render(<MailSidebar {...props} />, false);
expect(queryByTestId(`Scheduled`)).toBeNull();
});
it('should show scheduled sidebar item if scheduled messages', async () => {
setupTest(systemFolders, [], [scheduledMessages]);
const { getByTestId } = await render(<MailSidebar {...props} />, false);
const scheduledLocationAside = getByTestId(`navigation-link:unread-count`);
// We have two navigation counters for scheduled messages, one to display the number of scheduled messages and one for unread scheduled messages
expect(scheduledLocationAside.innerHTML).toBe(`${scheduledMessages.Total}`);
});
it('should not show scheduled sidebar item without scheduled messages', async () => {
setupTest([], [], []);
const { queryByTestId } = await render(<MailSidebar {...props} />, false);
expect(queryByTestId(`Scheduled`)).toBeNull();
});
describe('Sidebar hotkeys', () => {
it('should navigate with the arrow keys', async () => {
setupTest([label, folder, ...systemFolders]);
const { getByTestId, getByTitle, container } = await render(<MailSidebar {...props} />, false);
const sidebar = container.querySelector('nav > div') as HTMLDivElement;
const More = getByTitle('Less'); // When opened, it becomes "LESS"
const Folders = getByTitle('Folders');
const Labels = getByTitle('Labels');
const Inbox = getByTestId('navigation-link:inbox');
const Drafts = getByTestId('navigation-link:drafts');
const Folder = getByTestId(`navigation-link:${folder.ID}`);
const Label = getByTestId(`navigation-link:${label.ID}`);
const down = () => fireEvent.keyDown(sidebar, { key: 'ArrowDown' });
const up = () => fireEvent.keyDown(sidebar, { key: 'ArrowUp' });
const ctrlDown = () => fireEvent.keyDown(sidebar, { key: 'ArrowDown', ctrlKey: true });
const ctrlUp = () => fireEvent.keyDown(sidebar, { key: 'ArrowUp', ctrlKey: true });
down();
assertFocus(Inbox);
down();
assertFocus(Drafts);
range(0, 3).forEach(down);
assertFocus(More);
down();
assertFocus(Folders);
down();
assertFocus(Folder);
down();
assertFocus(Labels);
down();
assertFocus(Label);
up();
assertFocus(Labels);
up();
assertFocus(Folder);
up();
assertFocus(Folders);
range(0, 10).forEach(up);
assertFocus(Inbox);
ctrlDown();
assertFocus(Label);
ctrlUp();
assertFocus(Inbox);
});
it('should navigate to list with right key', async () => {
setupTest([label, folder]);
const TestComponent = () => {
return (
<>
<MailSidebar {...props} />
<div data-shortcut-target="item-container" tabIndex={-1}>
test
</div>
</>
);
};
const { container } = await render(<TestComponent />, false);
const sidebar = container.querySelector('nav > div') as HTMLDivElement;
fireEvent.keyDown(sidebar, { key: 'ArrowRight' });
const target = document.querySelector('[data-shortcut-target="item-container"]');
assertFocus(target);
});
});
});
describe('Sidebar checklist display', () => {
beforeEach(() => {
minimalCache();
});
it('Should display the checklist if state is reduced', async () => {
mockedReturn.mockReturnValue({
displayState: CHECKLIST_DISPLAY_TYPE.REDUCED,
items: new Set(),
} as ContextState);
const { getByTestId, container } = await render(<MailSidebar {...props} />, false);
getByTestId('onboarding-checklist');
const nav = container.querySelector('nav');
expect(nav?.childNodes.length).toEqual(3);
});
it('Should not display the checklist if state is full', async () => {
mockedReturn.mockReturnValue({
displayState: CHECKLIST_DISPLAY_TYPE.FULL,
items: new Set(),
} as ContextState);
const { queryByTestId, container } = await render(<MailSidebar {...props} />, false);
const checklistWrapper = queryByTestId('onboarding-checklist');
const nav = container.querySelector('nav');
expect(checklistWrapper).toBeNull();
expect(nav?.childNodes.length).toEqual(2);
});
it('Should not display the checklist if state is hidden', async () => {
mockedReturn.mockReturnValue({
displayState: CHECKLIST_DISPLAY_TYPE.HIDDEN,
items: new Set(),
} as ContextState);
const { queryByTestId, container } = await render(<MailSidebar {...props} />, false);
const checklistWrapper = queryByTestId('onboarding-checklist');
const nav = container.querySelector('nav');
expect(checklistWrapper).toBeNull();
expect(nav?.childNodes.length).toEqual(2);
});
it('Should hide the checklist when pressing the cross button in the sidebar', async () => {
const mockedChangeDisplay = jest.fn();
mockedReturn.mockReturnValue({
displayState: CHECKLIST_DISPLAY_TYPE.REDUCED,
items: new Set(),
changeChecklistDisplay: mockedChangeDisplay,
} as Partial<ContextState>);
const { container, getByTestId } = await render(<MailSidebar {...props} />, false);
const nav = container.querySelector('nav');
expect(nav?.childNodes.length).toEqual(3);
const closeButton = getByTestId('onboarding-checklist-header-hide-button');
fireEvent.click(closeButton);
expect(mockedChangeDisplay).toHaveBeenCalledWith(CHECKLIST_DISPLAY_TYPE.HIDDEN);
});
});
|
3,709 | 0 | petrpan-code/ProtonMail/WebClients/applications/mail/src/app/components | petrpan-code/ProtonMail/WebClients/applications/mail/src/app/components/sidebar/MailSidebarDriveSpotlight.test.tsx | import { render, screen } from '@testing-library/react';
import { getUnixTime, subDays } from 'date-fns';
import * as spotlightModule from '@proton/components/components/spotlight/Spotlight';
import * as useDriveWindowsGASpotlightModule from '@proton/components/hooks/useDriveWindowsGASpotlight';
import * as useFeatureModule from '@proton/components/hooks/useFeature';
import * as useSpotlightOnFeatureModule from '@proton/components/hooks/useSpotlightOnFeature';
import * as useWelcomeFlagsModule from '@proton/components/hooks/useWelcomeFlags';
import * as browserHelpersModule from '@proton/shared/lib/helpers/browser';
import {
SpotlightMock,
mockUseActiveBreakpoint,
mockUseFeature,
mockUseSpotlightOnFeature,
mockUseUser,
} from '@proton/testing/index';
import noop from '@proton/utils/noop';
import MailSidebarDriveSpotlight from './MailSidebarDriveSpotlight';
describe('MailSidebarDriveSpotlight', () => {
const spotlightMock = jest.spyOn(spotlightModule, 'default');
const useWelcomeFlagsMock = jest.spyOn(useWelcomeFlagsModule, 'default');
const useFeatureMock = jest.spyOn(useFeatureModule, 'default');
const useSpotlightOnFeatureMock = jest.spyOn(useSpotlightOnFeatureModule, 'default');
const useDriveWindowsGASpotlightMock = jest.spyOn(useDriveWindowsGASpotlightModule, 'useDriveWindowsGASpotlight');
const isWindows = jest.spyOn(browserHelpersModule, 'isWindows');
beforeEach(() => {
isWindows.mockReturnValue(true);
spotlightMock.mockImplementation(SpotlightMock);
useWelcomeFlagsMock.mockReturnValue([
{ isDone: true, hasGenericWelcomeStep: false, isWelcomeFlow: false },
noop,
]);
useDriveWindowsGASpotlightMock.mockReturnValue([
{
show: true,
content: 'spotlight',
originalPlacement: 'bottom',
size: 'large',
onClose: noop,
},
noop,
]);
mockUseActiveBreakpoint({ isNarrow: false });
mockUseFeature({ feature: { Value: true } });
mockUseSpotlightOnFeature({ show: true });
mockUseUser([
{
CreateTime: getUnixTime(subDays(new Date(), 2)),
},
false,
]);
});
afterEach(() => {
jest.clearAllMocks();
});
const setup = () => {
return render(
<MailSidebarDriveSpotlight
renderDropdown={(hideSpotlight) => <div onClick={hideSpotlight}>{'content'}</div>}
/>
);
};
it('Should render child and spotlight', () => {
setup();
// Ensure we call the right FF in first call
expect(useFeatureMock.mock.calls[0][0]).toBe('DriveWindowsGAMailSpotlightShown');
expect(screen.getByText('content')).toBeInTheDocument();
expect(screen.getByText('spotlight')).toBeInTheDocument();
});
it('Should not render spotlight when feature flag is false', () => {
useFeatureMock.mockReturnValue({ feature: { Value: false } } as any);
setup();
expect(screen.getByText('content')).toBeInTheDocument();
expect(screen.queryByText('spotlight')).toBe(null);
});
it('Should not render spotlight when feature flag has been displayed', () => {
useSpotlightOnFeatureMock.mockReturnValue({ show: false, onDisplayed: () => {}, onClose: () => {} });
setup();
expect(screen.getByText('content')).toBeInTheDocument();
expect(screen.queryByText('spotlight')).toBe(null);
});
it('Should not render spotlight when feature is not on windows', () => {
isWindows.mockReturnValue(false);
setup();
expect(screen.getByText('content')).toBeInTheDocument();
expect(screen.queryByText('spotlight')).toBe(null);
});
it('Should not render spotlight when user created account less than two days ago', () => {
mockUseUser([
{
CreateTime: getUnixTime(subDays(new Date(), 1)),
},
false,
]);
setup();
expect(screen.getByText('content')).toBeInTheDocument();
expect(screen.queryByText('spotlight')).toBe(null);
});
it('Should not render spotlight when user is on mobile screen', () => {
mockUseActiveBreakpoint({ isNarrow: true });
setup();
expect(screen.getByText('content')).toBeInTheDocument();
expect(screen.queryByText('spotlight')).toBe(null);
});
});
|
3,729 | 0 | petrpan-code/ProtonMail/WebClients/applications/mail/src/app/components | petrpan-code/ProtonMail/WebClients/applications/mail/src/app/components/toolbar/MoreDropdown.test.tsx | import { fireEvent, render } from '@testing-library/react';
import useSnooze from '../../hooks/actions/useSnooze';
import { useLabelActions } from '../../hooks/useLabelActions';
import MoreDropdown from './MoreDropdown';
jest.mock('../../hooks/useLabelActions');
jest.mock('../../hooks/actions/useSnooze');
jest.mock('../../hooks/actions/useEmptyLabel', () => ({
useEmptyLabel: () => ({ emptyLabel: '', modal: null }),
}));
jest.mock('../../hooks/actions/useMoveAll', () => ({
useMoveAll: () => ({ moveAll: '', modal: null }),
}));
const BREAKPOINTS = {
breakpoint: '',
isLargeDesktop: false,
isMediumDesktop: false,
isSmallDesktop: false,
isDesktop: false,
isTablet: false,
isMobile: false,
isTinyMobile: false,
isNarrow: false,
};
const props = {
labelID: '1',
elementIDs: [''],
selectedIDs: ['a', 'b'],
isSearch: false,
isNarrow: false,
isTiny: false,
isExtraTiny: false,
onMove: jest.fn(),
onDelete: jest.fn(),
breakpoints: BREAKPOINTS,
};
const isTinyProps = {
...props,
isTiny: true,
};
const isExtraTinyProps = {
...props,
isExtraTiny: true,
};
const isNarrowProps = {
...props,
isNarrow: true,
};
describe('MoreDropdown', () => {
const useSnoozeMock = useSnooze as jest.Mock;
const useLabelActionMock = useLabelActions as jest.Mock;
beforeAll(() => {
useLabelActionMock.mockReturnValue([[''], ['']]);
useSnoozeMock.mockReturnValue({
isSnoozeEnabled: true,
canSnooze: jest.fn(),
canUnsnooze: jest.fn(),
});
});
afterAll(() => {
useLabelActionMock.mockReset();
useSnoozeMock.mockReset();
});
it('should contain all option in more when screen is tiny', () => {
const { getByTestId } = render(<MoreDropdown {...isTinyProps} />);
const moreButton = getByTestId('toolbar:more-dropdown');
fireEvent.click(moreButton);
expect(getByTestId('toolbar:more-dropdown--moveto'));
expect(getByTestId('toolbar:more-dropdown--labelas'));
expect(getByTestId('toolbar:more-dropdown--snooze'));
});
it('should contain no option in more when all breakpoints are false', () => {
const { getByTestId, queryByTestId } = render(<MoreDropdown {...props} />);
const moreButton = getByTestId('toolbar:more-dropdown');
fireEvent.click(moreButton);
expect(queryByTestId('toolbar:more-dropdown--moveto')).toBeNull();
expect(queryByTestId('toolbar:more-dropdown--labelas')).toBeNull();
expect(queryByTestId('toolbar:more-dropdown--snooze')).toBeNull();
});
it('should contain no option in more when screen narrow', () => {
const { getByTestId, queryByTestId } = render(<MoreDropdown {...isNarrowProps} />);
const moreButton = getByTestId('toolbar:more-dropdown');
fireEvent.click(moreButton);
expect(queryByTestId('toolbar:more-dropdown--moveto')).toBeNull();
expect(queryByTestId('toolbar:more-dropdown--labelas')).toBeNull();
expect(queryByTestId('toolbar:more-dropdown--snooze')).toBeNull();
});
it('should contain no option in more when screen is extra tiny', () => {
const { getByTestId, queryByTestId } = render(<MoreDropdown {...isExtraTinyProps} />);
const moreButton = getByTestId('toolbar:more-dropdown');
fireEvent.click(moreButton);
expect(queryByTestId('toolbar:more-dropdown--moveto')).toBeNull();
expect(queryByTestId('toolbar:more-dropdown--labelas')).toBeNull();
expect(queryByTestId('toolbar:more-dropdown--snooze')).toBeNull();
});
it('should have move and label action when snooze is disabled and screen tiny', () => {
useSnoozeMock.mockReturnValue({
isSnoozeEnabled: false,
canSnooze: jest.fn(),
canUnsnooze: jest.fn(),
});
const { getByTestId } = render(<MoreDropdown {...isTinyProps} />);
const moreButton = getByTestId('toolbar:more-dropdown');
fireEvent.click(moreButton);
expect(getByTestId('toolbar:more-dropdown--moveto'));
expect(getByTestId('toolbar:more-dropdown--labelas'));
});
it('should have all move actions returned by useLabelAction hook', () => {
useLabelActionMock.mockReturnValue([['inbox', 'trash', 'archive', 'spam', 'nospam', 'delete'], ['']]);
const { getByTestId } = render(<MoreDropdown {...isExtraTinyProps} />);
const moreButton = getByTestId('toolbar:more-dropdown');
fireEvent.click(moreButton);
expect(getByTestId('toolbar:more-dropdown--movetoinbox'));
expect(getByTestId('toolbar:more-dropdown--movetonospam'));
expect(getByTestId('toolbar:more-dropdown--movetonoarchive'));
expect(getByTestId('toolbar:more-dropdown--movetotrash'));
expect(getByTestId('toolbar:more-dropdown--movetospam'));
expect(getByTestId('toolbar:more-dropdown--delete'));
});
it('should have only move actions returned by useLabelAction hook', () => {
useLabelActionMock.mockReturnValue([['inbox', 'trash', 'error'], ['not real']]);
const { getByTestId } = render(<MoreDropdown {...isExtraTinyProps} />);
const moreButton = getByTestId('toolbar:more-dropdown');
fireEvent.click(moreButton);
expect(getByTestId('toolbar:more-dropdown--movetoinbox'));
expect(getByTestId('toolbar:more-dropdown--movetotrash'));
});
it('should have no move actions when screen is not extra tiny', () => {
useLabelActionMock.mockReturnValue([['inbox', 'trash', 'archive', 'spam', 'nospam', 'delete'], ['']]);
const { getByTestId, queryByTestId } = render(<MoreDropdown {...isTinyProps} />);
const moreButton = getByTestId('toolbar:more-dropdown');
fireEvent.click(moreButton);
expect(queryByTestId('toolbar:more-dropdown--movetoinbox')).toBeNull();
expect(queryByTestId('toolbar:more-dropdown--movetonospam')).toBeNull();
expect(queryByTestId('toolbar:more-dropdown--movetonoarchive')).toBeNull();
expect(queryByTestId('toolbar:more-dropdown--movetotrash')).toBeNull();
expect(queryByTestId('toolbar:more-dropdown--movetospam')).toBeNull();
expect(queryByTestId('toolbar:more-dropdown--delete')).toBeNull();
});
});
|
3,731 | 0 | petrpan-code/ProtonMail/WebClients/applications/mail/src/app/components | petrpan-code/ProtonMail/WebClients/applications/mail/src/app/components/toolbar/MoveButtons.test.tsx | import { screen } from '@testing-library/react';
import { LABEL_TYPE, MAILBOX_LABEL_IDS } from '@proton/shared/lib/constants';
import { Label } from '@proton/shared/lib/interfaces';
import { addToCache, clearAll, minimalCache, render } from '../../helpers/test/helper';
import MoveButtons from './MoveButtons';
const labelID = 'labelID';
const folderID = 'folderID';
const labels: Label[] = [
{ ID: labelID, Type: LABEL_TYPE.MESSAGE_LABEL } as Label,
{ ID: folderID, Type: LABEL_TYPE.MESSAGE_FOLDER } as Label,
];
const getProps = (labelID: string) => {
return {
labelID,
isExtraTiny: false,
isNarrow: false,
isTiny: false,
selectedIDs: ['randomID'],
onMove: jest.fn(),
onDelete: jest.fn(),
};
};
describe('MoveButtons', () => {
afterEach(clearAll);
it.each`
labelID | label
${MAILBOX_LABEL_IDS.INBOX} | ${'Inbox'}
${MAILBOX_LABEL_IDS.STARRED} | ${'Starred'}
${MAILBOX_LABEL_IDS.ALL_MAIL} | ${'All Mail'}
${folderID} | ${'Custom folders'}
${labelID} | ${'Custom labels'}
`('should display trash, archive and spam actions in $label', async ({ labelID }) => {
const props = getProps(labelID);
minimalCache();
addToCache('Labels', labels);
await render(<MoveButtons {...props} />, false);
// Actions displayed
screen.getByText('Move to trash');
screen.getByText('Move to archive');
screen.getByText('Move to spam');
// Actions not displayed
expect(screen.queryByText('Move to inbox')).toBeNull();
expect(screen.queryByText('Move to inbox (not spam)')).toBeNull();
expect(screen.queryByText('Delete permanently')).toBeNull();
});
it.each`
labelID | label
${MAILBOX_LABEL_IDS.DRAFTS} | ${'Drafts'}
${MAILBOX_LABEL_IDS.ALL_DRAFTS} | ${'All Drafts'}
${MAILBOX_LABEL_IDS.SENT} | ${'Sent'}
${MAILBOX_LABEL_IDS.ALL_SENT} | ${'All Sent'}
`(`should display trash, archive and delete actions in $label`, async ({ labelID }) => {
const props = getProps(labelID);
await render(<MoveButtons {...props} />);
// Actions displayed
screen.getByText('Move to trash');
screen.getByText('Move to archive');
screen.getByText('Delete permanently');
// Actions not displayed
expect(screen.queryByText('Move to inbox')).toBeNull();
expect(screen.queryByText('Move to inbox (not spam)')).toBeNull();
expect(screen.queryByText('Move to spam')).toBeNull();
});
it('should display trash and archive actions in Scheduled', async () => {
const props = getProps(MAILBOX_LABEL_IDS.SCHEDULED);
await render(<MoveButtons {...props} />);
// Actions displayed
screen.getByText('Move to trash');
screen.getByText('Move to archive');
// Actions not displayed
expect(screen.queryByText('Move to inbox')).toBeNull();
expect(screen.queryByText('Move to inbox (not spam)')).toBeNull();
expect(screen.queryByText('Delete permanently')).toBeNull();
expect(screen.queryByText('Move to spam')).toBeNull();
});
it('should display trash, inbox and spam actions in Archive', async () => {
const props = getProps(MAILBOX_LABEL_IDS.ARCHIVE);
await render(<MoveButtons {...props} />);
// Actions displayed
screen.getByText('Move to trash');
screen.getByText('Move to inbox');
screen.getByText('Move to spam');
// Actions not displayed
expect(screen.queryByText('Move to archive')).toBeNull();
expect(screen.queryByText('Move to inbox (not spam)')).toBeNull();
expect(screen.queryByText('Delete permanently')).toBeNull();
});
it('should display trash, nospam and delete actions in Spam', async () => {
const props = getProps(MAILBOX_LABEL_IDS.SPAM);
await render(<MoveButtons {...props} />);
// Actions displayed
screen.getByText('Move to trash');
screen.getByText('Move to inbox (not spam)');
screen.getByText('Delete permanently');
// Actions not displayed
expect(screen.queryByText('Move to inbox')).toBeNull();
expect(screen.queryByText('Move to archive')).toBeNull();
expect(screen.queryByText('Move to spam')).toBeNull();
});
it('should display inbox, archive and delete actions in Trash', async () => {
const props = getProps(MAILBOX_LABEL_IDS.TRASH);
await render(<MoveButtons {...props} />);
// Actions displayed
screen.getByText('Move to inbox');
screen.getByText('Move to archive');
screen.getByText('Delete permanently');
// Actions not displayed
expect(screen.queryByText('Move to trash')).toBeNull();
expect(screen.queryByText('Move to inbox (not spam)')).toBeNull();
expect(screen.queryByText('Move to spam')).toBeNull();
});
});
|
3,748 | 0 | petrpan-code/ProtonMail/WebClients/applications/mail/src/app/components | petrpan-code/ProtonMail/WebClients/applications/mail/src/app/components/view/EmptyListPlaceholder.test.tsx | import { screen } from '@testing-library/react';
import { CHECKLIST_DISPLAY_TYPE } from '@proton/shared/lib/interfaces';
import {
ContextState,
useGetStartedChecklist,
} from '../../containers/onboardingChecklist/provider/GetStartedChecklistProvider';
import { render } from '../../helpers/test/helper';
import EmptyListPlaceholder from './EmptyListPlaceholder';
jest.mock('../../containers/onboardingChecklist/provider/GetStartedChecklistProvider', () => ({
__esModule: true,
useGetStartedChecklist: jest.fn(),
default: ({ children }: { children: any }) => <>{children}</>,
}));
jest.mock('../../containers/onboardingChecklist/provider/GetStartedChecklistProvider');
const mockedReturn = useGetStartedChecklist as jest.MockedFunction<typeof useGetStartedChecklist>;
describe('EmptyListPlaceholder', () => {
it('Should display checklist when no mails are present', async () => {
mockedReturn.mockReturnValue({ displayState: CHECKLIST_DISPLAY_TYPE.FULL, items: new Set() } as ContextState);
await render(<EmptyListPlaceholder labelID="labelID" isSearch={false} isUnread={false} />);
screen.getByTestId('onboarding-checklist');
});
it('Should display placeholder when checklist is not reduced', async () => {
mockedReturn.mockReturnValue({
displayState: CHECKLIST_DISPLAY_TYPE.REDUCED,
items: new Set(),
} as ContextState);
await render(<EmptyListPlaceholder labelID="labelID" isSearch={false} isUnread={false} />);
screen.getByTestId('empty-view-placeholder--empty-title');
});
it('Should display placeholder when checklist is not hidden', async () => {
mockedReturn.mockReturnValue({
displayState: CHECKLIST_DISPLAY_TYPE.HIDDEN,
items: new Set(),
} as ContextState);
await render(<EmptyListPlaceholder labelID="labelID" isSearch={false} isUnread={false} />);
screen.getByTestId('empty-view-placeholder--empty-title');
});
});
|
3,756 | 0 | petrpan-code/ProtonMail/WebClients/applications/mail/src/app | petrpan-code/ProtonMail/WebClients/applications/mail/src/app/containers/ComposerContainer.test.tsx | import { act } from '@testing-library/react';
import { getAppName } from '@proton/shared/lib/apps/helper';
import { APPS, MIME_TYPES } from '@proton/shared/lib/constants';
import { Recipient } from '@proton/shared/lib/interfaces';
import { FORWARDED_MESSAGE } from '@proton/shared/lib/mail/messages';
import { MESSAGE_ACTIONS } from '../constants';
import { formatFullDate } from '../helpers/date';
import { addAddressToCache, clearAll, minimalCache, render, tick } from '../helpers/test/helper';
import { preparePlainText } from '../helpers/transforms/transforms';
import { ComposeTypes, OnCompose } from '../hooks/composer/useCompose';
import { MessageState } from '../logic/messages/messagesTypes';
import { Breakpoints } from '../models/utils';
import { useOnCompose } from './ComposeProvider';
import ComposerContainer from './ComposerContainer';
const ID = 'ID';
const Email = '[email protected]';
const Signature = 'Signature';
const Sender = {
Name: 'sender',
Address: '[email protected]',
};
const protonmailAppName = getAppName(APPS.PROTONMAIL);
describe('ComposerContainer', () => {
afterEach(clearAll);
it('should reply to a plaintext message with the right content', async () => {
let onCompose: OnCompose;
const content = `mail content
with a link -> https://protonmail.com/`;
minimalCache();
addAddressToCache({ Email, Signature });
const message = {
localID: ID,
data: {
ID,
MIMEType: 'text/plain' as MIME_TYPES,
Subject: '',
Sender,
ToList: [] as Recipient[],
},
decryption: {
decryptedBody: content,
},
messageDocument: {
initialized: true,
},
...(await preparePlainText(content, false)),
} as MessageState;
const Inside = () => {
onCompose = useOnCompose();
return null;
};
const { findByTestId, unmount } = await render(
<ComposerContainer breakpoints={{} as Breakpoints}>
<Inside />
</ComposerContainer>,
false
);
await act(async () => {
onCompose({
type: ComposeTypes.newMessage,
action: MESSAGE_ACTIONS.REPLY,
referenceMessage: message,
});
});
const textarea = (await findByTestId('editor-textarea')) as HTMLTextAreaElement;
expect(textarea.value).toBe(`
${Signature}
Sent with ${protonmailAppName} secure email.
On ${formatFullDate(new Date(0))}, ${Sender.Name} <${Sender.Address}> wrote:
> mail content
> with a link -> https://protonmail.com/`);
// Wait for Address focus action
await tick();
// Unmount unless the container will listen the reset action
unmount();
});
it('should forward to a plaintext message with the right content', async () => {
let onCompose: OnCompose;
const content = `mail content
with a link -> https://protonmail.com/`;
minimalCache();
addAddressToCache({ Email, Signature });
const me = { Name: 'me', Address: '[email protected]' };
const toRecipient = { Name: 'toRecipient', Address: '[email protected]' };
const ccRecipient = { Name: 'ccRecipient', Address: '[email protected]' };
const ccRecipient2 = { Name: '', Address: '[email protected]' };
const messageSubject = 'Message subject';
const message = {
localID: ID,
data: {
ID,
MIMEType: 'text/plain' as MIME_TYPES,
Subject: messageSubject,
Sender,
ToList: [me, toRecipient] as Recipient[],
CCList: [ccRecipient, ccRecipient2] as Recipient[],
},
decryption: {
decryptedBody: content,
},
messageDocument: {
initialized: true,
},
...(await preparePlainText(content, false)),
} as MessageState;
const Inside = () => {
onCompose = useOnCompose();
return null;
};
const { findByTestId, unmount } = await render(
<ComposerContainer breakpoints={{} as Breakpoints}>
<Inside />
</ComposerContainer>,
false
);
await act(async () => {
onCompose({
type: ComposeTypes.newMessage,
action: MESSAGE_ACTIONS.FORWARD,
referenceMessage: message,
});
});
const textarea = (await findByTestId('editor-textarea')) as HTMLTextAreaElement;
expect(textarea.value).toBe(`
${Signature}
Sent with ${protonmailAppName} secure email.
${FORWARDED_MESSAGE}
From: ${Sender.Name} <${Sender.Address}>
Date: On ${formatFullDate(new Date(0))}
Subject: ${messageSubject}
To: ${me.Name} <${me.Address}>, ${toRecipient.Name} <${toRecipient.Address}>
CC: ${ccRecipient.Name} <${ccRecipient.Address}>, ${ccRecipient2.Address} <${ccRecipient2.Address}>
> mail content
> with a link -> https://protonmail.com/`);
// Wait for Address focus action
await tick();
// Unmount unless the container will listen the reset action
unmount();
});
});
|
3,761 | 0 | petrpan-code/ProtonMail/WebClients/applications/mail/src/app | petrpan-code/ProtonMail/WebClients/applications/mail/src/app/containers/PageContainer.test.tsx | import { fireEvent } from '@testing-library/react';
import { getAppName } from '@proton/shared/lib/apps/helper';
import { APPS } from '@proton/shared/lib/constants';
import { SHORTCUTS } from '@proton/shared/lib/mail/mailSettings';
import {
addApiMock,
addToCache,
assertFocus,
clearAll,
minimalCache,
onCompose,
render,
tick,
} from '../helpers/test/helper';
import { Breakpoints } from '../models/utils';
import PageContainer from './PageContainer';
jest.setTimeout(20000);
describe('PageContainer', () => {
const props = {
breakpoints: {} as Breakpoints,
isComposerOpened: false,
};
beforeAll(() => {
global.fetch = jest.fn();
});
beforeEach(clearAll);
const setup = async ({ Component = PageContainer } = {}) => {
addApiMock('importer/v1/importers', () => ({ Importers: [] }));
addApiMock('settings/calendar', () => ({}));
addApiMock('calendar/v1', () => ({}));
addApiMock('payments/v4/plans', () => ({}));
addApiMock('mail/v4/conversations', () => ({}));
addApiMock('domains/optin', () => ({}));
addApiMock('payments/v4/subscription/latest', () => ({}));
addApiMock('mail/v4/incomingdefaults', () => ({
IncomingDefaults: [],
Total: 0,
GlobalTotal: 0,
}));
minimalCache();
addToCache('MailSettings', { Shortcuts: SHORTCUTS.ENABLED });
const renderResult = await render(<Component {...props} />, false);
const { container } = renderResult;
return {
...renderResult,
questionMark: () => fireEvent.keyDown(container, { key: '?' }),
tab: () => fireEvent.keyDown(container, { key: 'Tab' }),
slash: () => fireEvent.keyDown(container, { key: '/' }),
n: () => fireEvent.keyDown(container, { key: 'N' }),
};
};
describe('hotkeys', () => {
it('should open hotkeys modal on ?', async () => {
const { questionMark, getByText } = await setup();
const appName = getAppName(APPS.PROTONMAIL);
questionMark();
getByText(`${appName} Keyboard Shortcuts`);
});
it('should focus element list on Tab', async () => {
const Component = () => {
return (
<>
<PageContainer {...props} />
<div data-shortcut-target="item-container" tabIndex={-1} />
</>
);
};
const { tab } = await setup({ Component: Component as any });
tab();
const itemContainer = document.querySelector('[data-shortcut-target="item-container"]');
assertFocus(itemContainer);
});
it('should focus search bar on /', async () => {
const { slash } = await setup();
slash();
await tick();
const search = document.querySelector('[data-shorcut-target="searchbox-field"]');
assertFocus(search);
});
it('should open composer on a N', async () => {
const { n } = await setup();
n();
expect(onCompose).toHaveBeenCalled();
});
});
});
|
3,773 | 0 | petrpan-code/ProtonMail/WebClients/applications/mail/src/app/containers/mailbox | petrpan-code/ProtonMail/WebClients/applications/mail/src/app/containers/mailbox/tests/Mailbox.elements.test.tsx | import { fireEvent } from '@testing-library/react';
import { queryConversations } from '@proton/shared/lib/api/conversations';
import { MESSAGE_FLAGS } from '@proton/shared/lib/mail/constants';
import { ELEMENTS_CACHE_REQUEST_SIZE, PAGE_SIZE } from '../../../constants';
import { addApiMock, api, apiMocks, clearAll, getHistory, tick, waitForSpyCall } from '../../../helpers/test/helper';
import { Element } from '../../../models/element';
import { Sort } from '../../../models/tools';
import { getElements, props, sendEvent, setup } from './Mailbox.test.helpers';
describe('Mailbox element list', () => {
const { labelID } = props;
const element1 = {
ID: 'id1',
Labels: [{ ID: labelID, ContextTime: 1 }],
LabelIDs: [labelID],
Size: 20,
NumUnread: 1,
NumMessages: 1,
} as Element;
const element2 = {
ID: 'id2',
Labels: [{ ID: labelID, ContextTime: 2 }],
LabelIDs: [labelID],
Size: 10,
NumUnread: 1,
NumMessages: 1,
} as Element;
const element3 = {
ID: 'id3',
Labels: [{ ID: 'otherLabelID', ContextTime: 3 }],
LabelIDs: ['otherLabelID'],
NumUnread: 0,
NumMessages: 1,
} as Element;
beforeEach(clearAll);
describe('elements memo', () => {
it('should order by label context time', async () => {
const conversations = [element1, element2];
const { getItems } = await setup({ conversations });
const items = getItems();
expect(items.length).toBe(2);
expect(items[0].getAttribute('data-element-id')).toBe(conversations[1].ID);
expect(items[1].getAttribute('data-element-id')).toBe(conversations[0].ID);
});
it('should filter message with the right label', async () => {
const { getItems } = await setup({
page: 0,
totalConversations: 2,
conversations: [element1, element2, element3],
});
const items = getItems();
expect(items.length).toBe(2);
});
it('should limit to the page size', async () => {
const total = PAGE_SIZE + 5;
const { getItems } = await setup({
conversations: getElements(total),
page: 0,
totalConversations: total,
});
const items = getItems();
expect(items.length).toBe(PAGE_SIZE);
});
it('should returns the current page', async () => {
const page1 = 0;
const page2 = 1;
const total = PAGE_SIZE + 2;
const conversations = getElements(total);
const { rerender, getItems } = await setup({ conversations, totalConversations: total, page: page1 });
let items = getItems();
expect(items.length).toBe(PAGE_SIZE);
await rerender({ page: page2 });
items = getItems();
expect(items.length).toBe(2);
});
it('should returns elements sorted', async () => {
const conversations = [element1, element2];
const sort1: Sort = { sort: 'Size', desc: false };
const sort2: Sort = { sort: 'Size', desc: true };
const { rerender, getItems } = await setup({ conversations, sort: sort1 });
let items = getItems();
expect(items.length).toBe(2);
expect(items[0].getAttribute('data-element-id')).toBe(conversations[1].ID);
expect(items[1].getAttribute('data-element-id')).toBe(conversations[0].ID);
await rerender({ sort: sort2 });
items = getItems();
expect(items.length).toBe(2);
expect(items[0].getAttribute('data-element-id')).toBe(conversations[0].ID);
expect(items[1].getAttribute('data-element-id')).toBe(conversations[1].ID);
});
it('should fallback sorting on Order field', async () => {
const conversations = [
{ ID: 'id1', Labels: [{ ID: labelID, ContextTime: 1 }], LabelIDs: [labelID], Size: 20, Order: 3 },
{ ID: 'id2', Labels: [{ ID: labelID, ContextTime: 1 }], LabelIDs: [labelID], Size: 20, Order: 2 },
{ ID: 'id3', Labels: [{ ID: labelID, ContextTime: 1 }], LabelIDs: [labelID], Size: 20, Order: 4 },
{ ID: 'id4', Labels: [{ ID: labelID, ContextTime: 1 }], LabelIDs: [labelID], Size: 20, Order: 1 },
];
const expectOrder = (items: HTMLElement[], order: number[]) => {
expect(items.length).toBe(order.length);
for (const [i, pos] of order.entries()) {
expect(items[i].getAttribute('data-element-id')).toBe(conversations[pos].ID);
}
};
const { rerender, getItems } = await setup({ conversations });
expectOrder(getItems(), [2, 0, 1, 3]);
await rerender({ sort: { sort: 'Time', desc: false } });
expectOrder(getItems(), [3, 1, 0, 2]);
await rerender({ sort: { sort: 'Size', desc: true } });
expectOrder(getItems(), [0, 1, 2, 3]);
await rerender({ sort: { sort: 'Size', desc: false } });
expectOrder(getItems(), [0, 1, 2, 3]);
});
});
describe('request effect', () => {
it('should send request for conversations current page', async () => {
const page = 0;
const total = PAGE_SIZE + 3;
const expectedRequest = {
...queryConversations({
LabelID: labelID,
Sort: 'Time',
Limit: ELEMENTS_CACHE_REQUEST_SIZE,
PageSize: PAGE_SIZE,
} as any),
signal: new AbortController().signal,
};
const { getItems } = await setup({
conversations: getElements(PAGE_SIZE),
page,
totalConversations: total,
});
expect(api).toHaveBeenCalledWith(expectedRequest);
const items = getItems();
expect(items.length).toBe(PAGE_SIZE);
});
});
describe('filter unread', () => {
it('should only show unread conversations if filter is on', async () => {
const conversations = [element1, element2, element3];
const { getItems } = await setup({ conversations, filter: { Unread: 1 }, totalConversations: 2 });
const items = getItems();
expect(items.length).toBe(2);
});
it('should keep in view the conversations when opened while filter is on', async () => {
const conversations = [element1, element2, element3];
const message = {
ID: 'messageID1',
AddressID: 'AddressID',
Sender: {},
ConversationID: element1.ID,
Flag: MESSAGE_FLAGS.FLAG_RECEIVED,
LabelIDs: [labelID],
Attachments: [],
};
const { rerender, getItems } = await setup({
conversations,
filter: { Unread: 1 },
totalConversations: 2,
});
// A bit complex but the point is to simulate opening the conversation
addApiMock(`mail/v4/conversations/${element1.ID}`, () => ({
Conversation: element1,
Messages: [message],
}));
addApiMock(`mail/v4/messages/messageID1`, () => ({ Message: message }));
addApiMock(`mail/v4/messages/read`, () => ({ UndoToken: { Token: 'Token' } }));
await rerender({ elementID: element1.ID });
const items = getItems();
expect(items.length).toBe(2);
expect(items[1].classList.contains('read')).toBe(true);
expect(items[0].classList.contains('read')).toBe(false);
// Needed because of the message images double render
await tick();
});
});
describe('page navigation', () => {
it('should navigate on the last page when the one asked is too big', async () => {
const conversations = getElements(PAGE_SIZE * 1.5);
apiMocks['mail/v4/conversations'] = [
{
method: 'get',
handler: (args: any) => {
const page = args.params.Page;
if (page === 10) {
return { Total: conversations.length, Conversations: [] };
}
if (page <= 1) {
return { Total: conversations.length, Conversations: conversations.slice(PAGE_SIZE) };
}
},
},
];
// Initialize on page 1
const { rerender, getItems } = await setup({ conversations, page: 0, mockConversations: false });
// Then ask for page 11
await rerender({ page: 10 });
expect(getHistory().location.hash).toBe('#page=2');
await rerender({ page: 1 });
const items = getItems();
expect(items.length).toBe(conversations.length % PAGE_SIZE);
});
it('should navigate on the previous one when the current one is emptied', async () => {
const conversations = getElements(PAGE_SIZE * 1.5);
apiMocks['mail/v4/conversations'] = [
{
method: 'get',
handler: (args: any) => {
const page = args.params.Page;
if (page === 0) {
return { Total: conversations.length, Conversations: conversations.slice(0, PAGE_SIZE) };
}
if (page === 1) {
return { Total: conversations.length, Conversations: conversations.slice(PAGE_SIZE) };
}
},
},
];
const labelRequestSpy = jest.fn(() => ({ UndoToken: { Token: 'Token' } }));
addApiMock(`mail/v4/conversations/label`, labelRequestSpy, 'put');
const { getByTestId } = await setup({ conversations, page: 1, mockConversations: false });
const selectAll = getByTestId('toolbar:select-all-checkbox');
fireEvent.click(selectAll);
const archive = getByTestId('toolbar:movetoarchive');
fireEvent.click(archive);
await sendEvent({ ConversationCounts: [{ LabelID: labelID, Total: PAGE_SIZE, Unread: 0 }] });
await waitForSpyCall(labelRequestSpy);
expect(getHistory().location.hash).toBe('');
});
it('should show correct number of placeholder navigating on last page', async () => {
const conversations = getElements(PAGE_SIZE * 1.5);
apiMocks['mail/v4/conversations'] = [
{
method: 'get',
handler: (args: any) => {
const page = args.params.Page;
if (page === 0) {
return { Total: conversations.length, Conversations: conversations.slice(0, PAGE_SIZE) };
}
if (page === 1) {
return new Promise(() => {});
}
},
},
];
const { rerender, getItems } = await setup({ conversations, mockConversations: false });
await rerender({ page: 1 });
const items = getItems();
expect(items.length).toBe(conversations.length % PAGE_SIZE);
});
});
});
|
3,774 | 0 | petrpan-code/ProtonMail/WebClients/applications/mail/src/app/containers/mailbox | petrpan-code/ProtonMail/WebClients/applications/mail/src/app/containers/mailbox/tests/Mailbox.events.test.tsx | import { act } from '@testing-library/react';
import { EVENT_ACTIONS } from '@proton/shared/lib/constants';
import { Message } from '@proton/shared/lib/interfaces/mail/Message';
import { DEFAULT_PLACEHOLDERS_COUNT, PAGE_SIZE } from '../../../constants';
import { addApiResolver, addToCache, api, clearAll, render } from '../../../helpers/test/helper';
import { Conversation } from '../../../models/conversation';
import { MessageEvent } from '../../../models/event';
import MailboxContainer from '../MailboxContainer';
import { baseApiMocks, expectElements, getElements, getProps, props, sendEvent, setup } from './Mailbox.test.helpers';
jest.setTimeout(20000);
describe('Mailbox elements list reacting to events', () => {
const { labelID } = props;
beforeEach(clearAll);
it('should add to the cache a message which is not existing yet', async () => {
// Usefull to receive incoming mail or draft without having to reload the list
const total = 3;
const { getItems } = await setup({ conversations: getElements(total) });
const element = { ID: 'id3', Labels: [{ ID: labelID }], LabelIDs: [labelID] };
await sendEvent({
ConversationCounts: [{ LabelID: labelID, Total: total + 1, Unread: 0 }],
Conversations: [{ ID: element.ID, Action: EVENT_ACTIONS.CREATE, Conversation: element as Conversation }],
});
expectElements(getItems, total + 1, false);
});
it('should not add to the cache a message which is not existing when a search is active', async () => {
// When a search is active, all the cache will be shown, we can't accept any updated message
// But we will refresh the request each time
const total = 3;
const search = { keyword: 'test' };
const { getItems } = await setup({ messages: getElements(total), search });
const message = { ID: 'id3', Labels: [{ ID: labelID }], LabelIDs: [labelID] } as any as Message;
await sendEvent({
Messages: [{ ID: message.ID, Action: EVENT_ACTIONS.CREATE, Message: message }],
});
expectElements(getItems, total, false);
expect(api.mock.calls.length).toBe(5);
});
it('should not reload the list on an update event if a filter is active', async () => {
const total = 3;
const filter = { Unread: 1 };
const conversations = getElements(total, labelID, { NumUnread: 1 });
const { getItems } = await setup({ conversations, filter });
const ID = 'id0';
await sendEvent({
Conversations: [{ ID, Action: EVENT_ACTIONS.UPDATE, Conversation: { ID } as Conversation }],
});
expectElements(getItems, total, false);
expect(api.mock.calls.length).toBe(4);
});
it('should not reload the list on an update event if has list from start', async () => {
const total = 3;
const { getItems } = await setup({ conversations: getElements(total) });
const ID = 'id0';
await sendEvent({
Conversations: [{ ID, Action: EVENT_ACTIONS.UPDATE, Conversation: { ID } as Conversation }],
});
expectElements(getItems, total, false);
expect(api.mock.calls.length).toBe(4);
});
it('should reload the list on an update event if has not list from start', async () => {
const page = 2;
const total = PAGE_SIZE * 6 + 2;
const { getItems } = await setup({
conversations: getElements(PAGE_SIZE),
page,
totalConversations: total,
});
const ID = 'id0';
await sendEvent({
Conversations: [{ ID, Action: EVENT_ACTIONS.UPDATE, Conversation: { ID } as Conversation }],
});
expectElements(getItems, PAGE_SIZE, false);
expect(api.mock.calls.length).toBe(5);
});
it('should reload the list on an delete event if a search is active', async () => {
const total = 3;
const search = { keyword: 'test' };
const { getItems } = await setup({ messages: getElements(total), search });
const ID = 'id10';
await sendEvent({
Messages: [{ ID, Action: EVENT_ACTIONS.DELETE, Message: { ID } as Message }],
});
expectElements(getItems, total, false);
expect(api.mock.calls.length).toBe(5);
});
it('should not reload the list on count event when a search is active', async () => {
// If a search is active, the expected length computation has no meaning
const total = 3;
const search = { keyword: 'test' };
const messages = getElements(total);
await setup({ messages, search });
await sendEvent({
MessageCounts: [{ LabelID: labelID, Total: 10, Unread: 10 }],
});
expect(api.mock.calls.length).toBe(4);
});
it('should not show the loader if not live cache but params has not changed', async () => {
const total = PAGE_SIZE;
const search = { keyword: 'test' };
const messages = getElements(total);
baseApiMocks();
addToCache('ConversationCounts', []);
addToCache('MessageCounts', [{ LabelID: labelID, Total: total }]);
addToCache('Calendars', []);
const { resolve } = addApiResolver('mail/v4/messages');
const { getAllByTestId } = await render(<MailboxContainer {...getProps({ search })} />);
const getItems = () => getAllByTestId('message-item', { exact: false });
// First load pending
expectElements(getItems, DEFAULT_PLACEHOLDERS_COUNT, true);
await act(async () => {
resolve({ Total: total, Messages: messages });
});
// First load finished
expectElements(getItems, total, false);
const message = messages[0] as Message;
await sendEvent({
Messages: [{ ID: message.ID || '', Action: EVENT_ACTIONS.DELETE } as MessageEvent],
});
// Event triggered a reload, load is pending but it's hidded to the user
expectElements(getItems, total, false);
await act(async () => {
resolve({ Total: total, Messages: messages });
});
// Load finished
expectElements(getItems, total, false);
});
it('should show the loader if not live cache and params has changed', async () => {
const total = PAGE_SIZE;
const search = { keyword: 'test' };
const messages = getElements(total);
baseApiMocks();
addToCache('ConversationCounts', []);
addToCache('MessageCounts', [{ LabelID: labelID, Total: total }]);
let { resolve } = addApiResolver('mail/v4/messages');
const { rerender, getAllByTestId } = await render(<MailboxContainer {...getProps({ search })} />);
const getItems = () => getAllByTestId('message-item', { exact: false });
// First load pending
expectElements(getItems, DEFAULT_PLACEHOLDERS_COUNT, true);
await act(async () => {
resolve({ Total: total, Messages: messages });
});
// First load finished
expectElements(getItems, total, false);
resolve = addApiResolver('mail/v4/messages').resolve;
await rerender(<MailboxContainer {...getProps({ search: { keyword: 'changed' } })} />);
// Params has changed, cache is reset
expectElements(getItems, DEFAULT_PLACEHOLDERS_COUNT, true);
await act(async () => {
resolve({ Total: total, Messages: messages });
});
// Load finished
expectElements(getItems, total, false);
});
});
|
3,775 | 0 | petrpan-code/ProtonMail/WebClients/applications/mail/src/app/containers/mailbox | petrpan-code/ProtonMail/WebClients/applications/mail/src/app/containers/mailbox/tests/Mailbox.hotkeys.test.tsx | import { fireEvent } from '@testing-library/react';
import { MAILBOX_LABEL_IDS } from '@proton/shared/lib/constants';
import { Message } from '@proton/shared/lib/interfaces/mail/Message';
import { addApiMock, assertCheck, assertFocus, clearAll, getHistory, tick } from '../../../helpers/test/helper';
import MailboxContainer from '../MailboxContainer';
import { SetupArgs, setup as generalSetup, getElements, props } from './Mailbox.test.helpers';
describe('Mailbox hotkeys', () => {
const conversations = getElements(4);
beforeEach(clearAll);
const setup = async ({ conversations: inputConversation, ...rest }: SetupArgs = {}) => {
const usedConversations = inputConversation || conversations;
const result = await generalSetup({ conversations: usedConversations, ...rest });
const mailbox = result.getByTestId('mailbox');
return {
...result,
down: () => fireEvent.keyDown(mailbox, { key: 'ArrowDown' }),
up: () => fireEvent.keyDown(mailbox, { key: 'ArrowUp' }),
ctrlDown: () => fireEvent.keyDown(mailbox, { key: 'ArrowDown', ctrlKey: true }),
ctrlUp: () => fireEvent.keyDown(mailbox, { key: 'ArrowUp', ctrlKey: true }),
left: () => fireEvent.keyDown(mailbox, { key: 'ArrowLeft' }),
right: () => fireEvent.keyDown(mailbox, { key: 'ArrowRight' }),
enter: () => fireEvent.keyDown(mailbox, { key: 'Enter' }),
escape: () => fireEvent.keyDown(mailbox, { key: 'Escape' }),
j: () => fireEvent.keyDown(mailbox, { key: 'J' }),
k: () => fireEvent.keyDown(mailbox, { key: 'K' }),
space: () => fireEvent.keyDown(mailbox, { key: ' ' }),
shftSpace: () => fireEvent.keyDown(mailbox, { key: ' ', shiftKey: true }),
ctrlA: () => fireEvent.keyDown(mailbox, { key: 'A', ctrlKey: true }),
x: () => fireEvent.keyDown(mailbox, { key: 'X' }),
shftX: () => fireEvent.keyDown(mailbox, { key: 'X', shiftKey: true }),
a: () => fireEvent.keyDown(mailbox, { key: 'A' }),
i: () => fireEvent.keyDown(mailbox, { key: 'I' }),
s: () => fireEvent.keyDown(mailbox, { key: 'S' }),
star: () => fireEvent.keyDown(mailbox, { key: '*' }),
t: () => fireEvent.keyDown(mailbox, { key: 'T' }),
ctrlBackspace: () => fireEvent.keyDown(mailbox, { key: 'Backspace', ctrlKey: true }),
};
};
it('should navigate through items with arrows', async () => {
const { getItems, down, up, ctrlDown, ctrlUp } = await setup();
const items = getItems();
down();
assertFocus(items[0]);
down();
assertFocus(items[1]);
ctrlDown();
assertFocus(items[3]);
up();
assertFocus(items[2]);
ctrlUp();
assertFocus(items[0]);
});
it('should navigate left and right', async () => {
const TestComponent = (props: any) => {
return (
<>
<div data-shortcut-target="navigation-link" aria-current="page" tabIndex={-1}>
nav test
</div>
<MailboxContainer {...props} />
<div data-shortcut-target="message-container" tabIndex={-1}>
message test
</div>
</>
);
};
const { left, right } = await setup({ Component: TestComponent as any });
const sidebar = document.querySelector('[data-shortcut-target="navigation-link"]');
const message = document.querySelector('[data-shortcut-target="message-container"]');
left();
assertFocus(sidebar);
right();
assertFocus(message);
});
it('should enter a message and leave', async () => {
const { down, enter, escape } = await setup();
const history = getHistory();
down();
enter();
expect(history.length).toBe(3);
expect(history.location.pathname).toBe(`/${props.labelID}/${conversations[3].ID}`);
escape();
expect(history.length).toBe(4);
expect(history.location.pathname).toBe(`/${props.labelID}`);
});
it('should navigate no next message with J', async () => {
const conversation = conversations[2];
const message = { ID: 'MessageID', Subject: 'test', Body: 'test', Flags: 0 } as Message;
addApiMock(`mail/v4/conversations/${conversation.ID}`, () => ({
Conversation: conversation,
Messages: [message],
}));
const { j } = await setup({ conversations, elementID: conversation.ID });
j();
const history = getHistory();
expect(history.length).toBe(3);
expect(history.location.pathname).toBe(`/${props.labelID}/${conversations[1].ID}`);
});
it('should navigate to previous message with K', async () => {
const conversation = conversations[2];
const message = { ID: 'MessageID', Subject: 'test', Body: 'test', Flags: 0 } as Message;
addApiMock(`mail/v4/conversations/${conversation.ID}`, () => ({
Conversation: conversation,
Messages: [message],
}));
const { k } = await setup({ conversations, elementID: conversation.ID });
k();
const history = getHistory();
expect(history.length).toBe(3);
expect(history.location.pathname).toBe(`/${props.labelID}/${conversations[3].ID}`);
});
it('should allow to select elements with keyboard', async () => {
const { getItems, down, space, x, shftSpace, shftX, ctrlA, ctrlUp } = await setup();
const assertChecks = (array: boolean[]) => {
const items = getItems();
for (let i = 0; i < array.length; i++) {
assertCheck(items[i], array[i]);
}
};
down();
space();
assertChecks([true, false, false, false]);
down();
down();
shftSpace();
assertChecks([true, true, true, false]);
ctrlA();
assertChecks([true, true, true, true]);
ctrlA();
assertChecks([false, false, false, false]);
ctrlUp();
x();
assertChecks([true, false, false, false]);
down();
down();
shftX();
assertChecks([true, true, true, false]);
});
it('should allow to move elements with keyboard', async () => {
const labelSpy = jest.fn<any, any>(() => ({ UndoToken: 'token' }));
addApiMock('mail/v4/conversations/label', labelSpy, 'put');
const deleteSpy = jest.fn();
addApiMock('mail/v4/conversations/delete', deleteSpy, 'put');
const conversations = getElements(20, MAILBOX_LABEL_IDS.TRASH);
const { down, space, a, i, s, star, t, ctrlBackspace, getByTestId } = await setup({
labelID: MAILBOX_LABEL_IDS.TRASH,
conversations,
});
let callTimes = 0;
const expectLabelCall = (LabelID: string) => {
callTimes++;
expect(labelSpy).toHaveBeenCalledTimes(callTimes);
expect(labelSpy.mock.calls[callTimes - 1][0].data).toEqual({
LabelID,
IDs: [conversations[conversations.length - (callTimes * 2 - 1)].ID],
});
};
down();
space();
a();
await tick();
expectLabelCall(MAILBOX_LABEL_IDS.ARCHIVE);
down();
space();
i();
await tick();
expectLabelCall(MAILBOX_LABEL_IDS.INBOX);
down();
space();
s();
await tick();
expectLabelCall(MAILBOX_LABEL_IDS.SPAM);
down();
space();
star();
await tick();
expectLabelCall(MAILBOX_LABEL_IDS.STARRED);
// T should do nothing as we already are in trash folder
t();
expect(labelSpy).toHaveBeenCalledTimes(callTimes);
await tick();
ctrlBackspace();
const button = getByTestId('permanent-delete-modal:submit');
fireEvent.click(button as HTMLButtonElement);
await tick();
expect(deleteSpy).toHaveBeenCalled();
});
});
|
3,776 | 0 | petrpan-code/ProtonMail/WebClients/applications/mail/src/app/containers/mailbox | petrpan-code/ProtonMail/WebClients/applications/mail/src/app/containers/mailbox/tests/Mailbox.labels.test.tsx | import { Matcher, fireEvent } from '@testing-library/react';
import { MAILBOX_LABEL_IDS } from '@proton/shared/lib/constants';
import { MailSettings } from '@proton/shared/lib/interfaces';
import { VIEW_MODE } from '@proton/shared/lib/mail/mailSettings';
import { addApiMock, clearAll, waitForSpyCall } from '../../../helpers/test/helper';
import { Element } from '../../../models/element';
import { folders, labels, sendEvent, setup } from './Mailbox.test.helpers';
const [label1, label2, label3, label4] = labels;
const [folder1, folder2] = folders;
describe('Mailbox labels actions', () => {
const conversation1 = {
ID: 'id1',
Labels: [
{ ID: folder1.ID, ContextTime: 3, ContextNumMessages: 1 },
{ ID: label1.ID, ContextTime: 3, ContextNumMessages: 1 },
{ ID: label2.ID, ContextTime: 3, ContextNumMessages: 1 },
],
NumUnread: 1,
NumMessages: 1,
} as Element;
const conversation2 = {
ID: 'id2',
Labels: [
{ ID: folder1.ID, ContextTime: 2, ContextNumMessages: 1 },
{ ID: label1.ID, ContextTime: 2, ContextNumMessages: 1 },
{ ID: label2.ID, ContextTime: 2, ContextNumMessages: 1 },
],
NumUnread: 1,
NumMessages: 1,
} as Element;
const conversation3 = {
ID: 'id3',
Labels: [
{ ID: folder1.ID, ContextTime: 2, ContextNumMessages: 1 },
{ ID: label1.ID, ContextTime: 1, ContextNumMessages: 1 },
{ ID: label2.ID, ContextTime: 1, ContextNumMessages: 1 },
],
NumUnread: 0,
NumMessages: 1,
} as Element;
const conversations = [conversation1, conversation2, conversation3];
beforeEach(clearAll);
describe('labels action', () => {
const useLabelDropdown = (getByTestId: (text: Matcher) => HTMLElement, labelsToClick: string[]) => {
const labelDropdownButton = getByTestId('toolbar:labelas');
fireEvent.click(labelDropdownButton);
const labelDropdownList = getByTestId('label-dropdown-list');
labelsToClick.forEach((labelToClick) => {
const labelCheckbox = labelDropdownList.querySelector(`[id$=${labelToClick}]`);
if (labelCheckbox) {
fireEvent.click(labelCheckbox);
}
});
const labelDropdownApply = getByTestId('label-dropdown:apply');
fireEvent.click(labelDropdownApply);
};
const expectLabels = (
getItems: () => HTMLElement[],
itemLabels: { [itemID: string]: { [labelName: string]: boolean } }
) => {
const items = getItems();
const itemByID = Object.fromEntries(
items.map((item) => [item.getAttribute('data-element-id') || '', item])
);
Object.entries(itemLabels).forEach(([itemID, labels]) => {
Object.entries(labels).forEach(([labelName, action]) => {
if (action) {
expect(itemByID[itemID].textContent).toContain(labelName);
} else {
expect(itemByID[itemID].textContent).not.toContain(labelName);
}
});
});
};
it('should add a label to two conversations', async () => {
const labelRequestSpy = jest.fn(() => ({ UndoToken: { Token: 'Token' } }));
addApiMock(`mail/v4/conversations/label`, labelRequestSpy, 'put');
const { getByTestId, getAllByTestId, getItems } = await setup({ conversations, labelID: label1.ID });
const checkboxes = getAllByTestId('item-checkbox');
fireEvent.click(checkboxes[0]);
fireEvent.click(checkboxes[1]);
useLabelDropdown(getByTestId, [label3.ID]);
await waitForSpyCall(labelRequestSpy);
expectLabels(getItems, {
[conversation1.ID as string]: { [label1.Name]: true, [label3.Name]: true },
[conversation2.ID as string]: { [label1.Name]: true, [label3.Name]: true },
[conversation3.ID as string]: { [label1.Name]: true, [label3.Name]: false },
});
expect(labelRequestSpy).toHaveBeenCalled();
// @ts-ignore
const { url, method, data } = labelRequestSpy.mock.calls[0][0];
expect({ url, method, data }).toEqual({
url: 'mail/v4/conversations/label',
method: 'put',
data: { IDs: [conversation1.ID, conversation2.ID], LabelID: label3.ID },
});
});
it('should remove a label to two conversations', async () => {
const labelRequestSpy = jest.fn(() => ({ UndoToken: { Token: 'Token' } }));
addApiMock(`mail/v4/conversations/unlabel`, labelRequestSpy, 'put');
const { getByTestId, getAllByTestId, getItems } = await setup({ conversations, labelID: label1.ID });
const checkboxes = getAllByTestId('item-checkbox');
fireEvent.click(checkboxes[1]);
fireEvent.click(checkboxes[2]);
useLabelDropdown(getByTestId, [label2.ID]);
await waitForSpyCall(labelRequestSpy);
expectLabels(getItems, {
[conversation1.ID as string]: { [label2.Name]: true },
[conversation2.ID as string]: { [label2.Name]: false },
[conversation3.ID as string]: { [label2.Name]: false },
});
expect(labelRequestSpy).toHaveBeenCalled();
// @ts-ignore
const { url, method, data } = labelRequestSpy.mock.calls[0][0];
expect({ url, method, data }).toEqual({
url: 'mail/v4/conversations/unlabel',
method: 'put',
data: { IDs: [conversation2.ID, conversation3.ID], LabelID: label2.ID },
});
});
it('should add and remove a label of a conversation', async () => {
const labelRequestSpy = jest.fn(() => ({ UndoToken: { Token: 'Token' } }));
const unlabelRequestSpy = jest.fn(() => ({ UndoToken: { Token: 'Token' } }));
addApiMock(`mail/v4/conversations/label`, labelRequestSpy, 'put');
addApiMock(`mail/v4/conversations/unlabel`, unlabelRequestSpy, 'put');
const { getByTestId, getAllByTestId, getItems } = await setup({ conversations, labelID: label1.ID });
const checkboxes = getAllByTestId('item-checkbox');
fireEvent.click(checkboxes[0]);
useLabelDropdown(getByTestId, [label2.ID, label3.ID]);
await waitForSpyCall(labelRequestSpy);
await waitForSpyCall(unlabelRequestSpy);
expectLabels(getItems, {
[conversation1.ID as string]: {
[label1.Name]: true,
[label2.Name]: false,
[label3.Name]: true,
[label4.Name]: false,
},
[conversation2.ID as string]: {
[label1.Name]: true,
[label2.Name]: true,
[label3.Name]: false,
[label4.Name]: false,
},
});
});
});
describe('folders action', () => {
const useMoveDropdown = (getByTestId: (text: Matcher) => HTMLElement, folderID: string) => {
const moveDropdownButton = getByTestId('toolbar:moveto');
fireEvent.click(moveDropdownButton);
const moveDropdownList = getByTestId('move-dropdown-list');
const folderButton = moveDropdownList.querySelector(`[id$=${folderID}]`);
if (folderButton) {
fireEvent.click(folderButton);
}
const moveDropdownApply = getByTestId('move-dropdown:apply');
fireEvent.click(moveDropdownApply);
};
it('should move two conversations in a another folder', async () => {
const labelRequestSpy = jest.fn(() => ({ UndoToken: { Token: 'Token' } }));
addApiMock(`mail/v4/conversations/label`, labelRequestSpy, 'put');
const { getByTestId, getAllByTestId, getItems } = await setup({ conversations, labelID: folder1.ID });
const checkboxes = getAllByTestId('item-checkbox');
fireEvent.click(checkboxes[0]);
fireEvent.click(checkboxes[1]);
addApiMock('mail/v4/conversations', () => ({ Total: 1, Conversations: [conversation3] }));
useMoveDropdown(getByTestId, folder2.ID);
await sendEvent({ ConversationCounts: [{ LabelID: folder1.ID, Total: 1, Unread: 0 }] });
await waitForSpyCall(labelRequestSpy);
const items = getItems();
expect(items.length).toBe(1);
});
});
describe('empty folder', () => {
it('should empty a folder', async () => {
const emptyRequestSpy = jest.fn();
addApiMock(`mail/v4/messages/empty`, emptyRequestSpy, 'delete');
const { getByTestId, getItems, findByTestId, queryAllByTestId } = await setup({
conversations,
labelID: folder1.ID,
});
let items = getItems();
expect(items.length).toBe(3);
const moreDropdown = getByTestId('toolbar:more-dropdown');
fireEvent.click(moreDropdown);
const emptyButton = await findByTestId('toolbar:more-empty');
fireEvent.click(emptyButton);
const confirmButton = await findByTestId('confirm-empty-folder');
fireEvent.click(confirmButton);
await waitForSpyCall(emptyRequestSpy);
items = queryAllByTestId('message-item', { exact: false });
expect(items.length).toBe(0);
});
});
describe('delete elements', () => {
const deleteFirstTwo = async ({
getAllByTestId,
getByTestId,
deleteRequestSpy,
}: {
getAllByTestId: (text: Matcher) => HTMLElement[];
getByTestId: (text: Matcher) => HTMLElement;
deleteRequestSpy: jest.Mock;
}) => {
const checkboxes = getAllByTestId('item-checkbox');
fireEvent.click(checkboxes[0]);
fireEvent.click(checkboxes[1]);
const deleteButton = getByTestId('toolbar:deletepermanently');
fireEvent.click(deleteButton);
const submitButton = getByTestId('permanent-delete-modal:submit');
fireEvent.click(submitButton);
await waitForSpyCall(deleteRequestSpy);
};
it('should delete permamently conversations', async () => {
const deleteRequestSpy = jest.fn(() => {});
addApiMock(`mail/v4/conversations/delete`, deleteRequestSpy, 'put');
const trashedConversations = conversations.map((conversation) => {
return {
...conversation,
Labels: [{ ID: MAILBOX_LABEL_IDS.TRASH, ContextTime: 0, ContextNumMessages: 0 }],
};
});
const { getAllByTestId, getByTestId, getItems } = await setup({
conversations: trashedConversations,
labelID: MAILBOX_LABEL_IDS.TRASH,
});
await deleteFirstTwo({ getAllByTestId, getByTestId, deleteRequestSpy });
const items = getItems();
expect(items.length).toBe(1);
});
it('should delete permamently messages', async () => {
const deleteRequestSpy = jest.fn(() => {});
addApiMock(`mail/v4/messages/delete`, deleteRequestSpy, 'put');
const trashedMessages = conversations.map((conversation) => {
return { ...conversation, ConversationID: 'id', LabelIDs: [MAILBOX_LABEL_IDS.TRASH] };
});
const { getByTestId, getAllByTestId, getItems } = await setup({
mailSettings: { ViewMode: VIEW_MODE.SINGLE } as MailSettings,
messages: trashedMessages,
labelID: MAILBOX_LABEL_IDS.TRASH,
});
await deleteFirstTwo({ getAllByTestId, getByTestId, deleteRequestSpy });
const items = getItems();
expect(items.length).toBe(1);
});
it('should delete permamently conversations and rollback', async () => {
const deleteRequestSpy = jest.fn(() => {
throw new Error('failed');
});
addApiMock(`mail/v4/conversations/delete`, deleteRequestSpy, 'put');
const trashedConversations = conversations.map((conversation) => {
return {
...conversation,
Labels: [{ ID: MAILBOX_LABEL_IDS.TRASH, ContextTime: 0, ContextNumMessages: 0 }],
};
});
const { getByTestId, getAllByTestId, getItems } = await setup({
conversations: trashedConversations,
labelID: MAILBOX_LABEL_IDS.TRASH,
});
await deleteFirstTwo({ getAllByTestId, getByTestId, deleteRequestSpy });
const items = getItems();
expect(items.length).toBe(3);
});
});
});
|
3,777 | 0 | petrpan-code/ProtonMail/WebClients/applications/mail/src/app/containers/mailbox | petrpan-code/ProtonMail/WebClients/applications/mail/src/app/containers/mailbox/tests/Mailbox.perf.test.tsx | import { EVENT_ACTIONS } from '@proton/shared/lib/constants';
import { clearAll, getHistory } from '../../../helpers/test/helper';
import * as useStarModule from '../../../hooks/actions/useStar';
import { getElements, sendEvent, setup } from './Mailbox.test.helpers';
jest.spyOn(useStarModule, 'useStar');
// Spying useStar is a trick to count the number of renders on the component ItemStar
// Beware, useStar is also used on the hotkeys management
const useStar = useStarModule.useStar as jest.Mock;
describe('Mailbox performance loss check', () => {
beforeEach(clearAll);
/**
* ItemStar is a pretext to detect item re-rendering
* The point of this test is to trigger some common event on the app like an element update event and a location change
* Count the number of render of the ItemStar component which is present inside each line of the element list
* And verify that this low level component has never been re-rerendered
* We're spying on the useStar hook to count the number of render
*/
it('should not render ItemStar on a conversation events nor a location change', async () => {
const total = 3;
const SomeNonMatchingID = 'SomeNonMatchingID';
const conversations = getElements(total);
const { getItems } = await setup({ conversations });
const items = getItems();
expect(items.length).toBe(total);
const callsAfterInitialization = useStar.mock.calls.length;
// Send event though the event manager + change location to trigger common app change
await sendEvent({
Conversations: [
{ ID: SomeNonMatchingID, Action: EVENT_ACTIONS.CREATE, Conversation: { ID: SomeNonMatchingID } },
],
});
getHistory().push('/elsewhere');
// There will be a few more call but it has to be in limited amount
expect(useStar.mock.calls.length).toBeLessThan(callsAfterInitialization + 6);
});
});
|
3,778 | 0 | petrpan-code/ProtonMail/WebClients/applications/mail/src/app/containers/mailbox | petrpan-code/ProtonMail/WebClients/applications/mail/src/app/containers/mailbox/tests/Mailbox.retries.test.tsx | import { act, fireEvent } from '@testing-library/react';
import { MAILBOX_LABEL_IDS } from '@proton/shared/lib/constants';
import { wait } from '@proton/shared/lib/helpers/promise';
import { PAGE_SIZE } from '../../../constants';
import { addApiMock, clearAll, tick } from '../../../helpers/test/helper';
import { expectElements, getElements, setup } from './Mailbox.test.helpers';
jest.setTimeout(20000);
describe('Mailbox retries and waitings', () => {
beforeEach(clearAll);
it('should retry when API call fails', async () => {
const conversations = getElements(3);
let callNumber = 0;
const conversationRequestSpy = jest.fn(() => {
callNumber++;
if (callNumber === 1) {
throw new Error('Test error');
}
return { Total: conversations.length, Conversations: conversations };
});
addApiMock(`mail/v4/conversations`, conversationRequestSpy, 'get');
const { getItems } = await setup({ totalConversations: conversations.length });
expect(conversationRequestSpy).toHaveBeenCalledTimes(1);
expectElements(getItems, conversations.length, true);
await act(async () => {
await wait(2000);
});
expect(conversationRequestSpy).toHaveBeenCalledTimes(2);
expectElements(getItems, conversations.length, false);
});
it('should retry when API respond with stale flag', async () => {
const conversations = getElements(3);
let callNumber = 0;
const conversationRequestSpy = jest.fn(() => {
callNumber++;
return { Total: conversations.length, Conversations: conversations, Stale: callNumber === 1 ? 1 : 0 };
});
addApiMock(`mail/v4/conversations`, conversationRequestSpy, 'get');
const { getItems } = await setup({ totalConversations: conversations.length });
expect(conversationRequestSpy).toHaveBeenCalledTimes(1);
expectElements(getItems, conversations.length, false);
await act(async () => {
await wait(10000);
});
expect(conversationRequestSpy).toHaveBeenCalledTimes(2);
expectElements(getItems, conversations.length, false);
});
it('should wait for all API actions to be finished before loading elements', async () => {
const conversations = getElements(PAGE_SIZE * 2, MAILBOX_LABEL_IDS.INBOX);
const totalConversations = PAGE_SIZE * 3;
const conversationRequestSpy = jest.fn(() => {
return { Total: totalConversations, Conversations: conversations };
});
addApiMock(`mail/v4/conversations`, conversationRequestSpy, 'get');
let resolvers: ((value: any) => void)[] = [];
const labelRequestSpy = jest.fn(() => {
return new Promise((resolver) => {
resolvers.push(resolver as any);
});
});
addApiMock('mail/v4/conversations/label', labelRequestSpy, 'put');
const { getItems, getByTestId } = await setup({
labelID: MAILBOX_LABEL_IDS.INBOX,
totalConversations,
mockConversations: false,
});
const checkAll = getByTestId('toolbar:select-all-checkbox');
await act(async () => {
fireEvent.click(checkAll);
await tick();
let trash = getByTestId('toolbar:movetotrash');
fireEvent.click(trash);
await tick();
fireEvent.click(checkAll);
await tick();
trash = getByTestId('toolbar:movetotrash');
fireEvent.click(trash);
await tick();
});
expect(conversationRequestSpy).toHaveBeenCalledTimes(1);
expectElements(getItems, PAGE_SIZE, true);
await act(async () => {
resolvers[0]({ UndoToken: 'fake' });
});
expect(conversationRequestSpy).toHaveBeenCalledTimes(1);
expectElements(getItems, PAGE_SIZE, true);
await act(async () => {
resolvers[1]({ UndoToken: 'fake' });
});
expect(conversationRequestSpy).toHaveBeenCalledTimes(2);
expectElements(getItems, PAGE_SIZE, false);
});
});
|
3,779 | 0 | petrpan-code/ProtonMail/WebClients/applications/mail/src/app/containers/mailbox | petrpan-code/ProtonMail/WebClients/applications/mail/src/app/containers/mailbox/tests/Mailbox.selection.test.tsx | import { fireEvent } from '@testing-library/react';
import { clearAll } from '../../../helpers/test/helper';
import { props, setup } from './Mailbox.test.helpers';
describe('Mailbox elements selection', () => {
const conversations = [
{ ID: '1', Labels: [{ ID: props.labelID }] },
{ ID: '2', Labels: [{ ID: props.labelID }] },
];
beforeEach(clearAll);
it('should show list when elements finish loading', async () => {
const { getItems } = await setup({ conversations });
const items = getItems();
expect(items.length === conversations.length).toBe(true);
});
it('should select all', async () => {
const { getByTestId, getAllByTestId } = await setup({ conversations });
const checkAll = getByTestId('toolbar:select-all-checkbox');
fireEvent.click(checkAll);
const allChecks = getAllByTestId('item-checkbox') as HTMLInputElement[];
expect(allChecks.length > 0).toBe(true);
const checked = [...allChecks].every((oneCheck) => oneCheck.checked);
expect(checked).toBe(true);
});
});
|
3,781 | 0 | petrpan-code/ProtonMail/WebClients/applications/mail/src/app/containers/mailbox | petrpan-code/ProtonMail/WebClients/applications/mail/src/app/containers/mailbox/tests/MailboxContainerPlaceholder.test.tsx | import { screen } from '@testing-library/react';
import { CHECKLIST_DISPLAY_TYPE } from '@proton/shared/lib/interfaces';
import {
ContextState,
useGetStartedChecklist,
} from '../../../containers/onboardingChecklist/provider/GetStartedChecklistProvider';
import { render } from '../../../helpers/test/helper';
import MailboxContainerPlaceholder from '../MailboxContainerPlaceholder';
jest.mock('../../../containers/onboardingChecklist/provider/GetStartedChecklistProvider', () => ({
__esModule: true,
useGetStartedChecklist: jest.fn(),
default: ({ children }: { children: any }) => <>{children}</>,
}));
jest.mock('../../../containers/onboardingChecklist/provider/GetStartedChecklistProvider');
const mockedReturn = useGetStartedChecklist as jest.MockedFunction<typeof useGetStartedChecklist>;
describe('MailboxContainerPlaceholder', () => {
it('Should display checklist when no mails are present', async () => {
mockedReturn.mockReturnValue({ displayState: CHECKLIST_DISPLAY_TYPE.FULL, items: new Set() } as ContextState);
await render(
<MailboxContainerPlaceholder
showPlaceholder={true}
welcomeFlag={false}
labelID="labelID"
checkedIDs={[]}
handleCheckAll={jest.fn()}
/>
);
screen.getByTestId('onboarding-checklist');
});
it('Should display section pane when checklist is reduced', async () => {
mockedReturn.mockReturnValue({
displayState: CHECKLIST_DISPLAY_TYPE.REDUCED,
items: new Set(),
} as ContextState);
await render(
<MailboxContainerPlaceholder
showPlaceholder={true}
welcomeFlag={false}
labelID="labelID"
checkedIDs={[]}
handleCheckAll={jest.fn()}
/>
);
screen.getByTestId('section-pane--wrapper');
});
it('Should display section pane when checklist is hidden', async () => {
mockedReturn.mockReturnValue({
displayState: CHECKLIST_DISPLAY_TYPE.HIDDEN,
items: new Set(),
} as ContextState);
await render(
<MailboxContainerPlaceholder
showPlaceholder={true}
welcomeFlag={false}
labelID="labelID"
checkedIDs={[]}
handleCheckAll={jest.fn()}
/>
);
screen.getByTestId('section-pane--wrapper');
});
});
|
3,782 | 0 | petrpan-code/ProtonMail/WebClients/applications/mail/src/app/containers/onboardingChecklist | petrpan-code/ProtonMail/WebClients/applications/mail/src/app/containers/onboardingChecklist/hooks/useChecklist.test.ts | import { useUserSettings } from '@proton/components/hooks';
import { addApiMock, renderHook } from 'proton-mail/helpers/test/helper';
import useChecklist from './useChecklist';
const getChecklist = jest.fn(() => {
return {
Code: 10,
Items: [],
};
});
const paidChecklist = jest.fn(() => {
return {
Code: 20,
Items: [],
};
});
const defaultReturnValue = {
Code: 0,
Items: [],
CreatedAt: 0,
ExpiresAt: 0,
UserWasRewarded: false,
Display: 'Hidden',
};
jest.mock('@proton/components/hooks/useUserSettings');
const mockedUserSettings = useUserSettings as jest.MockedFunction<any>;
describe('useChecklist', () => {
beforeAll(() => {
addApiMock(`core/v4/checklist/get-started`, getChecklist);
addApiMock(`core/v4/checklist/paying-user`, paidChecklist);
});
afterEach(() => {
getChecklist.mockClear();
paidChecklist.mockClear();
});
it('Should fetch the get-started checklist', async () => {
mockedUserSettings.mockReturnValue([{ Checklists: ['get-started'] }]);
const { result } = await renderHook(() => useChecklist('get-started'));
expect(getChecklist).toHaveBeenCalled();
expect(paidChecklist).not.toHaveBeenCalled();
expect(result.current[0]).toEqual({ Code: 10, Items: [] });
});
it('Should fetch the paying-user checklist', async () => {
mockedUserSettings.mockReturnValue([{ Checklists: ['paying-user'] }]);
const { result } = await renderHook(() => useChecklist('paying-user'));
expect(getChecklist).not.toHaveBeenCalled();
expect(paidChecklist).toHaveBeenCalled();
expect(result.current[0]).toEqual({ Code: 20, Items: [] });
});
it('Should not fetch get started when checklist not present', async () => {
mockedUserSettings.mockReturnValue([{}]);
const { result } = await renderHook(() => useChecklist('get-started'));
expect(getChecklist).not.toHaveBeenCalled();
expect(paidChecklist).not.toHaveBeenCalled();
expect(result.current[0]).toEqual(defaultReturnValue);
});
it('Should not fetch paying user when checklist not present', async () => {
mockedUserSettings.mockReturnValue([{}]);
const { result } = await renderHook(() => useChecklist('paying-user'));
expect(getChecklist).not.toHaveBeenCalled();
expect(paidChecklist).not.toHaveBeenCalled();
expect(result.current[0]).toEqual(defaultReturnValue);
});
it('Should not fetch get started when checklist empty', async () => {
mockedUserSettings.mockReturnValue([{ Checklists: [] }]);
const { result } = await renderHook(() => useChecklist('get-started'));
expect(getChecklist).not.toHaveBeenCalled();
expect(paidChecklist).not.toHaveBeenCalled();
expect(result.current[0]).toEqual(defaultReturnValue);
});
it('Should not fetch paying user when checklist empty', async () => {
mockedUserSettings.mockReturnValue([{ Checklists: [] }]);
const { result } = await renderHook(() => useChecklist('paying-user'));
expect(getChecklist).not.toHaveBeenCalled();
expect(paidChecklist).not.toHaveBeenCalled();
expect(result.current[0]).toEqual(defaultReturnValue);
});
});
|
3,785 | 0 | petrpan-code/ProtonMail/WebClients/applications/mail/src/app/containers/onboardingChecklist | petrpan-code/ProtonMail/WebClients/applications/mail/src/app/containers/onboardingChecklist/provider/GetStartedChecklistProvider.test.tsx | import useLoading from '@proton/hooks/useLoading';
import { CHECKLIST_DISPLAY_TYPE, ChecklistId, ChecklistKey } from '@proton/shared/lib/interfaces';
import { renderHook } from 'proton-mail/helpers/test/render';
import useChecklist from '../hooks/useChecklist';
import { useGetStartedChecklist } from './GetStartedChecklistProvider';
jest.mock('@proton/hooks/useLoading');
const mockLoading = useLoading as jest.MockedFunction<any>;
jest.mock('../hooks/useChecklist');
const mockChecklist = useChecklist as jest.MockedFunction<any>;
interface ChecklistBuilderProps {
checklistId: ChecklistId;
isPaid: boolean;
items?: ChecklistKey[];
createdAt?: number;
expiresAt?: number;
userWasRewarded?: boolean;
display?: CHECKLIST_DISPLAY_TYPE;
}
const nonAvailableChecklist = {
Code: 0,
Items: [] as ChecklistKey[],
CreatedAt: 0,
ExpiresAt: 0,
RewardInGB: 0,
UserWasRewarded: false,
Display: CHECKLIST_DISPLAY_TYPE.HIDDEN,
};
const checklistBuilder = ({
checklistId,
isPaid,
items,
createdAt,
expiresAt,
userWasRewarded,
display,
}: ChecklistBuilderProps) => {
if (checklistId === 'paying-user' && isPaid) {
return {
paidChecklist: [
{
Code: 1000,
Items: [...(items || [])],
CreatedAt: createdAt || 0,
ExpiresAt: expiresAt || 0,
RewardInGB: 0,
UserWasRewarded: userWasRewarded || false,
Display: display || CHECKLIST_DISPLAY_TYPE.HIDDEN,
},
false,
],
freeChecklist: [nonAvailableChecklist, false],
};
}
return {
freeChecklist: [
{
Code: 1000,
Items: [...(items || [])],
CreatedAt: createdAt || 0,
ExpiresAt: expiresAt || 0,
RewardInGB: 0,
UserWasRewarded: userWasRewarded || false,
Display: display || CHECKLIST_DISPLAY_TYPE.HIDDEN,
},
false,
],
paidChecklist: [nonAvailableChecklist, false],
};
};
describe('GetStartedChecklistProvider', () => {
it('Very basic test to see if default return values are correct for free users', async () => {
const itemsList = [
ChecklistKey.MobileApp,
ChecklistKey.SendMessage,
ChecklistKey.Import,
ChecklistKey.AccountLogin,
];
mockLoading.mockReturnValue([false, jest.fn()]);
const { freeChecklist, paidChecklist } = checklistBuilder({
checklistId: 'get-started',
isPaid: false,
items: itemsList,
});
mockChecklist.mockImplementation((checklistId: any) => {
if (checklistId === 'get-started') {
return freeChecklist;
} else {
return paidChecklist;
}
});
const { result } = await renderHook(() => useGetStartedChecklist());
const { isUserPaid, loading, isChecklistFinished, userWasRewarded, items, displayState } = result.current;
expect({ isUserPaid, loading, isChecklistFinished, userWasRewarded, items, displayState }).toStrictEqual({
isUserPaid: false,
loading: false,
isChecklistFinished: false,
userWasRewarded: false,
items: new Set([...itemsList]),
displayState: 'Hidden',
});
});
it('Very basic test to see if default return values are correct for free users', async () => {
const itemsList = [
ChecklistKey.MobileApp,
ChecklistKey.MobileApp,
ChecklistKey.MobileApp,
ChecklistKey.SendMessage,
ChecklistKey.Import,
ChecklistKey.AccountLogin,
];
mockLoading.mockReturnValue([false, jest.fn()]);
const { freeChecklist, paidChecklist } = checklistBuilder({
checklistId: 'paying-user',
isPaid: true,
items: itemsList,
});
mockChecklist.mockImplementation((checklistId: any) => {
if (checklistId === 'get-started') {
return freeChecklist;
} else {
return paidChecklist;
}
});
const { result } = await renderHook(() => useGetStartedChecklist());
const { isUserPaid, loading, isChecklistFinished, userWasRewarded, items, displayState } = result.current;
expect({ isUserPaid, loading, isChecklistFinished, userWasRewarded, items, displayState }).toStrictEqual({
isUserPaid: true,
loading: false,
isChecklistFinished: false,
userWasRewarded: false,
items: new Set([...itemsList]),
displayState: 'Hidden',
});
});
it('Test if checklist is marked as finished if all the items are present', async () => {
const itemsList = [
ChecklistKey.MobileApp,
ChecklistKey.Import,
ChecklistKey.AccountLogin,
ChecklistKey.ProtectInbox,
];
mockLoading.mockReturnValue([false, jest.fn()]);
const { freeChecklist, paidChecklist } = checklistBuilder({
checklistId: 'get-started',
isPaid: false,
items: itemsList,
});
mockChecklist.mockImplementation((checklistId: any) => {
if (checklistId === 'get-started') {
return freeChecklist;
} else {
return paidChecklist;
}
});
const { result } = await renderHook(() => useGetStartedChecklist());
const { isUserPaid, loading, isChecklistFinished, userWasRewarded, items, displayState } = result.current;
expect({
isUserPaid,
loading,
isChecklistFinished,
userWasRewarded,
items,
displayState,
}).toStrictEqual({
isUserPaid: false,
loading: false,
isChecklistFinished: true,
userWasRewarded: false,
items: new Set([...itemsList]),
displayState: 'Hidden',
});
});
});
|
3,792 | 0 | petrpan-code/ProtonMail/WebClients/applications/mail/src/app | petrpan-code/ProtonMail/WebClients/applications/mail/src/app/helpers/counter.test.ts | import { MAILBOX_LABEL_IDS } from '@proton/shared/lib/constants';
import { LabelCount } from '@proton/shared/lib/interfaces/Label';
import { Message } from '@proton/shared/lib/interfaces/mail/Message';
import { getCountersByLabelId, updateCounters, updateCountersForMarkAs } from './counter';
describe('counters', () => {
describe('updateCounters', () => {
it('should update counters', () => {
const message = { Unread: 1, ConversationID: 'ConversationID' } as Message;
const counters = [
{ LabelID: MAILBOX_LABEL_IDS.INBOX, Total: 1, Unread: 1 },
{ LabelID: MAILBOX_LABEL_IDS.ARCHIVE, Total: 0, Unread: 0 },
] as LabelCount[];
const changes = { [MAILBOX_LABEL_IDS.ARCHIVE]: true, [MAILBOX_LABEL_IDS.INBOX]: false };
const newCounters = updateCounters(message, counters, changes);
const inboxCounter = newCounters.find(({ LabelID }) => LabelID === MAILBOX_LABEL_IDS.INBOX);
const archiveCounter = newCounters.find(({ LabelID }) => LabelID === MAILBOX_LABEL_IDS.ARCHIVE);
expect(inboxCounter?.Total).toEqual(0);
expect(inboxCounter?.Unread).toEqual(0);
expect(archiveCounter?.Total).toEqual(1);
expect(archiveCounter?.Unread).toEqual(1);
});
it('should not change unmodifiable label', () => {
const message = { ConversationID: 'ConversationID' } as Message;
const counters = [] as LabelCount[];
const changes = {
[MAILBOX_LABEL_IDS.ALL_DRAFTS]: false,
[MAILBOX_LABEL_IDS.ALL_SENT]: false,
[MAILBOX_LABEL_IDS.ALL_MAIL]: false,
};
const newCounters = updateCounters(message, counters, changes);
const allDraftsCounter = newCounters.some(({ LabelID }) => LabelID === MAILBOX_LABEL_IDS.ALL_DRAFTS);
const allSentCounter = newCounters.some(({ LabelID }) => LabelID === MAILBOX_LABEL_IDS.ALL_SENT);
const allMailCounter = newCounters.some(({ LabelID }) => LabelID === MAILBOX_LABEL_IDS.ALL_MAIL);
expect(allDraftsCounter).toEqual(false);
expect(allSentCounter).toEqual(false);
expect(allMailCounter).toEqual(false);
});
it('should not change unread counter for trash location', () => {
const message = { Unread: 1, ConversationID: 'ConversationID' } as Message;
const counters = [] as LabelCount[];
const changes = { [MAILBOX_LABEL_IDS.TRASH]: true };
const newCounters = updateCounters(message, counters, changes);
const trashCounter = newCounters.find(({ LabelID }) => LabelID === MAILBOX_LABEL_IDS.TRASH);
expect(trashCounter?.Total).toEqual(1);
expect(trashCounter?.Unread).toEqual(0);
});
});
describe('updateCountersForMarkAs', () => {
const LabelIDs = [MAILBOX_LABEL_IDS.INBOX, MAILBOX_LABEL_IDS.ARCHIVE];
it('should update counters for read an unread message', () => {
const before = { Unread: 1, ConversationID: 'ConversationID', LabelIDs } as Message;
const after = { Unread: 0, ConversationID: 'ConversationID', LabelIDs } as Message;
const counters = [
{ LabelID: MAILBOX_LABEL_IDS.INBOX, Total: 1, Unread: 1 },
{ LabelID: MAILBOX_LABEL_IDS.ARCHIVE, Total: 1, Unread: 1 },
] as LabelCount[];
const newCounters = updateCountersForMarkAs(before, after, counters);
const inboxCounter = newCounters.find(({ LabelID }) => LabelID === MAILBOX_LABEL_IDS.INBOX);
const archiveCounter = newCounters.find(({ LabelID }) => LabelID === MAILBOX_LABEL_IDS.ARCHIVE);
expect(inboxCounter?.Total).toEqual(1);
expect(inboxCounter?.Unread).toEqual(0);
expect(archiveCounter?.Total).toEqual(1);
expect(archiveCounter?.Unread).toEqual(0);
});
it('should not update counters for read an read message', () => {
const before = { Unread: 0, ConversationID: 'ConversationID', LabelIDs } as Message;
const after = { Unread: 0, ConversationID: 'ConversationID', LabelIDs } as Message;
const counters = [
{ LabelID: MAILBOX_LABEL_IDS.INBOX, Total: 1, Unread: 0 },
{ LabelID: MAILBOX_LABEL_IDS.ARCHIVE, Total: 1, Unread: 0 },
] as LabelCount[];
const newCounters = updateCountersForMarkAs(before, after, counters);
const inboxCounter = newCounters.find(({ LabelID }) => LabelID === MAILBOX_LABEL_IDS.INBOX);
const archiveCounter = newCounters.find(({ LabelID }) => LabelID === MAILBOX_LABEL_IDS.ARCHIVE);
expect(inboxCounter?.Total).toEqual(1);
expect(inboxCounter?.Unread).toEqual(0);
expect(archiveCounter?.Total).toEqual(1);
expect(archiveCounter?.Unread).toEqual(0);
});
it('should update counters for unread an read message', () => {
const before = { Unread: 0, ConversationID: 'ConversationID', LabelIDs } as Message;
const after = { Unread: 1, ConversationID: 'ConversationID', LabelIDs } as Message;
const counters = [
{ LabelID: MAILBOX_LABEL_IDS.INBOX, Total: 1, Unread: 0 },
{ LabelID: MAILBOX_LABEL_IDS.ARCHIVE, Total: 1, Unread: 0 },
] as LabelCount[];
const newCounters = updateCountersForMarkAs(before, after, counters);
const inboxCounter = newCounters.find(({ LabelID }) => LabelID === MAILBOX_LABEL_IDS.INBOX);
const archiveCounter = newCounters.find(({ LabelID }) => LabelID === MAILBOX_LABEL_IDS.ARCHIVE);
expect(inboxCounter?.Total).toEqual(1);
expect(inboxCounter?.Unread).toEqual(1);
expect(archiveCounter?.Total).toEqual(1);
expect(archiveCounter?.Unread).toEqual(1);
});
it('should not update counters for unread an unread message', () => {
const before = { Unread: 1, ConversationID: 'ConversationID', LabelIDs } as Message;
const after = { Unread: 1, ConversationID: 'ConversationID', LabelIDs } as Message;
const counters = [
{ LabelID: MAILBOX_LABEL_IDS.INBOX, Total: 1, Unread: 1 },
{ LabelID: MAILBOX_LABEL_IDS.ARCHIVE, Total: 1, Unread: 1 },
] as LabelCount[];
const newCounters = updateCountersForMarkAs(before, after, counters);
const inboxCounter = newCounters.find(({ LabelID }) => LabelID === MAILBOX_LABEL_IDS.INBOX);
const archiveCounter = newCounters.find(({ LabelID }) => LabelID === MAILBOX_LABEL_IDS.ARCHIVE);
expect(inboxCounter?.Total).toEqual(1);
expect(inboxCounter?.Unread).toEqual(1);
expect(archiveCounter?.Total).toEqual(1);
expect(archiveCounter?.Unread).toEqual(1);
});
it('should not update counters where the message is not', () => {
const before = { Unread: 1, ConversationID: 'ConversationID', LabelIDs: ['anyID'] } as Message;
const after = { Unread: 0, ConversationID: 'ConversationID', LabelIDs: ['anyID'] } as Message;
const counters = [
{ LabelID: MAILBOX_LABEL_IDS.INBOX, Total: 1, Unread: 1 },
{ LabelID: MAILBOX_LABEL_IDS.ARCHIVE, Total: 1, Unread: 1 },
] as LabelCount[];
const newCounters = updateCountersForMarkAs(before, after, counters);
const inboxCounter = newCounters.find(({ LabelID }) => LabelID === MAILBOX_LABEL_IDS.INBOX);
const archiveCounter = newCounters.find(({ LabelID }) => LabelID === MAILBOX_LABEL_IDS.ARCHIVE);
expect(inboxCounter?.Total).toEqual(1);
expect(inboxCounter?.Unread).toEqual(1);
expect(archiveCounter?.Total).toEqual(1);
expect(archiveCounter?.Unread).toEqual(1);
});
});
describe('getCountersByLabelId', () => {
it('should return a map of counters by labelId', () => {
const counters: LabelCount[] = [
{ LabelID: MAILBOX_LABEL_IDS.INBOX, Total: 1, Unread: 1 },
{ LabelID: MAILBOX_LABEL_IDS.OUTBOX, Total: 3, Unread: 0 },
{ LabelID: MAILBOX_LABEL_IDS.SPAM, Total: 12, Unread: 0 },
{ LabelID: MAILBOX_LABEL_IDS.ARCHIVE, Total: 0, Unread: 0 },
];
expect(getCountersByLabelId(counters)).toEqual({
[MAILBOX_LABEL_IDS.INBOX]: { LabelID: MAILBOX_LABEL_IDS.INBOX, Total: 1, Unread: 1 },
[MAILBOX_LABEL_IDS.OUTBOX]: { LabelID: MAILBOX_LABEL_IDS.OUTBOX, Total: 3, Unread: 0 },
[MAILBOX_LABEL_IDS.SPAM]: { LabelID: MAILBOX_LABEL_IDS.SPAM, Total: 12, Unread: 0 },
[MAILBOX_LABEL_IDS.ARCHIVE]: { LabelID: MAILBOX_LABEL_IDS.ARCHIVE, Total: 0, Unread: 0 },
});
});
});
});
|
3,794 | 0 | petrpan-code/ProtonMail/WebClients/applications/mail/src/app | petrpan-code/ProtonMail/WebClients/applications/mail/src/app/helpers/date.test.ts | import {
formatDateToHuman,
formatDistanceToNow,
formatFileNameDate,
formatFullDate,
formatScheduledTimeString,
formatSimpleDate,
} from './date';
describe('formatSimpleDate', () => {
afterEach(() => {
jest.useRealTimers();
});
it('should return today date correctly formatted', function () {
// Sunday 1 2023
const fakeNow = new Date(2023, 0, 1, 10, 0, 0);
jest.useFakeTimers().setSystemTime(fakeNow.getTime());
const expected = '10:00 AM';
expect(formatSimpleDate(fakeNow)).toEqual(expected);
});
it('should return yesterday date correctly formatted', () => {
// Monday 2 2023
const fakeNow = new Date(2023, 0, 2, 10, 0, 0);
// Sunday 1 2023
const yesterday = new Date(2023, 0, 1, 10, 0, 0);
jest.useFakeTimers().setSystemTime(fakeNow.getTime());
const expected = 'Yesterday';
expect(formatSimpleDate(yesterday)).toEqual(expected);
});
it('should return is this week date correctly formatted', function () {
// Monday 2 2023
const fakeNow = new Date(2023, 0, 2, 10, 0, 0);
// Wednesday 4 2023
const inTheWeek = new Date(2023, 0, 4, 10, 0, 0);
jest.useFakeTimers().setSystemTime(fakeNow.getTime());
const expected = 'Wednesday';
expect(formatSimpleDate(inTheWeek)).toEqual(expected);
});
it('should return a normal date correctly formatted', () => {
// Sunday 1 2023
const fakeNow = new Date(2023, 0, 1, 10, 0, 0);
// Tuesday 10 2023
const inTheWeek = new Date(2023, 0, 10, 10, 0, 0);
jest.useFakeTimers().setSystemTime(fakeNow.getTime());
const expected = 'Jan 10, 2023';
expect(formatSimpleDate(inTheWeek)).toEqual(expected);
});
});
describe('formatFullDate', () => {
it('should format the date with the correct format', () => {
// Sunday 1 2023
const date = new Date(2023, 0, 1, 10, 0, 0);
const expected = 'Sunday, January 1st, 2023 at 10:00 AM';
expect(formatFullDate(date)).toEqual(expected);
});
});
describe('formatDistanceToNow', () => {
afterEach(() => {
jest.useRealTimers();
});
it('should format distance date', () => {
// Sunday 1 2023
const fakeNow = new Date(2023, 0, 1, 10, 0, 0);
// Saturday 1 2022
const lastyear = new Date(2022, 0, 1, 10, 0, 0);
jest.useFakeTimers().setSystemTime(fakeNow.getTime());
const expected = 'about 1 year ago';
expect(formatDistanceToNow(lastyear)).toEqual(expected);
});
});
describe('formatFileNameDate', () => {
it('should format the date in a filename format', () => {
// Sunday 1 2023
const date = new Date(2023, 0, 1, 10, 0, 0);
const expected = '2023-01-01T';
expect(formatFileNameDate(date)).toMatch(expected);
});
});
describe('formatScheduledTimeString', () => {
it('should format scheduled time string', () => {
// Sunday 1 2023
const date = new Date(2023, 0, 1, 10, 0, 0);
const expected = '10:00 AM';
expect(formatScheduledTimeString(date)).toEqual(expected);
});
});
describe('formatDateToHuman', () => {
it('should format date to human format', function () {
// Sunday 1 2023
const date = new Date(2023, 0, 1, 10, 0, 0);
const expected = {
dateString: 'Sunday, January 1st, 2023',
formattedTime: '10:00 AM',
};
expect(formatDateToHuman(date)).toEqual(expected);
});
});
|
3,798 | 0 | petrpan-code/ProtonMail/WebClients/applications/mail/src/app | petrpan-code/ProtonMail/WebClients/applications/mail/src/app/helpers/dom.test.ts | import { isElement, isHTMLEmpty, matches, parseInDiv } from './dom';
describe('isElement', () => {
it('should be an element', () => {
const el = document.createElement('p');
expect(isElement(el)).toBeTruthy();
});
it('should not be an element', () => {
const el = null;
expect(isElement(el)).toBeFalsy();
});
});
describe('matches', () => {
it('should match a selector', () => {
const link = document.createElement('a');
link.setAttribute('href', '#link');
expect(matches(link, '[href^="#"]')).toBeTruthy();
});
});
describe('parseInDiv', () => {
it('should add the content in a div', () => {
const content = 'This is some content';
const result = parseInDiv(content);
expect(result.innerHTML).toEqual(content);
});
});
describe('isHTMLEmpty', () => {
it('should be an empty element', () => {
const html1 = '';
const html2 = ' ';
expect(isHTMLEmpty(html1)).toBeTruthy();
expect(isHTMLEmpty(html2)).toBeTruthy();
});
it('should not be an empty element', () => {
const html1 = 'hello';
const html2 = ' hello';
expect(isHTMLEmpty(html1)).toBeFalsy();
expect(isHTMLEmpty(html2)).toBeFalsy();
});
});
describe('createErrorHandler', () => {});
|
3,800 | 0 | petrpan-code/ProtonMail/WebClients/applications/mail/src/app | petrpan-code/ProtonMail/WebClients/applications/mail/src/app/helpers/elements.test.ts | import { MAILBOX_LABEL_IDS } from '@proton/shared/lib/constants';
import { MailSettings } from '@proton/shared/lib/interfaces';
import { Message } from '@proton/shared/lib/interfaces/mail/Message';
import { Conversation, ConversationLabel } from '../models/conversation';
import { getCounterMap, getDate, isConversation, isMessage, isUnread, sort } from './elements';
describe('elements', () => {
describe('isConversation / isMessage', () => {
it('should return conversation when there is no conversationID in message', () => {
const element: Conversation = { ID: 'conversationID' };
expect(isConversation(element)).toBe(true);
expect(isMessage(element)).toBe(false);
});
it('should return message when there is a conversationID in message', () => {
const element = { ConversationID: 'something' } as Message;
expect(isConversation(element)).toBe(false);
expect(isMessage(element)).toBe(true);
});
});
describe('sort', () => {
it('should sort by time', () => {
const elements = [
{ Time: 1, ID: '1' },
{ Time: 2, ID: '2' },
{ Time: 3, ID: '3' },
];
expect(sort(elements, { sort: 'Time', desc: false }, 'labelID')).toEqual(elements);
});
it('should sort by time desc', () => {
const elements = [
{ Time: 1, ID: '1' },
{ Time: 2, ID: '2' },
{ Time: 3, ID: '3' },
];
expect(sort(elements, { sort: 'Time', desc: true }, 'labelID')).toEqual([...elements].reverse());
});
it('should fallback on order', () => {
const elements = [
{ ID: '1', Time: 1, Order: 3 },
{ ID: '2', Time: 1, Order: 2 },
{ ID: '3', Time: 1, Order: 1 },
];
expect(sort(elements, { sort: 'Time', desc: true }, 'labelID')).toEqual([...elements]);
});
it('should sort by order reversed for time asc', () => {
const elements = [
{ ID: '1', Time: 1, Order: 3 },
{ ID: '2', Time: 1, Order: 2 },
{ ID: '3', Time: 1, Order: 1 },
];
expect(sort(elements, { sort: 'Time', desc: false }, 'labelID')).toEqual([...elements].reverse());
});
it('should sort by size', () => {
const elements = [
{ ID: '1', Size: 1 },
{ ID: '2', Size: 2 },
{ ID: '3', Size: 3 },
];
expect(sort(elements, { sort: 'Size', desc: false }, 'labelID')).toEqual(elements);
});
});
describe('getCounterMap', () => {
it('should use conversation or message count depending the label type', () => {
const inboxCount = { LabelID: MAILBOX_LABEL_IDS.INBOX, Unread: 5 };
const sentConversationCount = { LabelID: MAILBOX_LABEL_IDS.SENT, Unread: 5 };
const sentMessageCount = { LabelID: MAILBOX_LABEL_IDS.SENT, Unread: 10 };
const result = getCounterMap(
[],
[inboxCount, sentConversationCount],
[sentMessageCount],
{} as MailSettings
);
expect(result[MAILBOX_LABEL_IDS.INBOX]?.Unread).toBe(inboxCount.Unread);
expect(result[MAILBOX_LABEL_IDS.SENT]?.Unread).toBe(sentMessageCount.Unread);
expect(result[MAILBOX_LABEL_IDS.STARRED]).toBeUndefined();
});
});
describe('getDate', () => {
const Time = 42;
const WrongTime = 43;
const expected = new Date(Time * 1000);
it('should not fail for an undefined element', () => {
expect(getDate(undefined, '') instanceof Date).toBe(true);
});
it('should take the Time property of a message', () => {
const message = { ConversationID: '', Time } as Message;
expect(getDate(message, '')).toEqual(expected);
});
it('should take the right label ContextTime of a conversation', () => {
const LabelID = 'LabelID';
const conversation = {
ID: 'conversationID',
Labels: [
{ ID: 'something', ContextTime: WrongTime } as ConversationLabel,
{ ID: LabelID, ContextTime: Time } as ConversationLabel,
],
};
expect(getDate(conversation, LabelID)).toEqual(expected);
});
it('should take the Time property of a conversation', () => {
const conversation = { Time, ID: 'conversationID' };
expect(getDate(conversation, '')).toEqual(expected);
});
it('should take the label time in priority for a conversation', () => {
const LabelID = 'LabelID';
const conversation = {
ID: 'conversationID',
Time: WrongTime,
Labels: [{ ID: LabelID, ContextTime: Time } as ConversationLabel],
};
expect(getDate(conversation, LabelID)).toEqual(expected);
});
});
describe('isUnread', () => {
it('should not fail for an undefined element', () => {
expect(isUnread(undefined, '')).toBe(false);
});
it('should take the Unread property of a message', () => {
const message = { ConversationID: '', Unread: 0 } as Message;
expect(isUnread(message, '')).toBe(false);
});
it('should take the right label ContextNumUnread of a conversation', () => {
const LabelID = 'LabelID';
const conversation = {
ID: 'conversationID',
Labels: [
{ ID: 'something', ContextNumUnread: 1 } as ConversationLabel,
{ ID: LabelID, ContextNumUnread: 0 } as ConversationLabel,
],
};
expect(isUnread(conversation, LabelID)).toBe(false);
});
it('should take the ContextNumUnread property of a conversation', () => {
const conversation = { ContextNumUnread: 0, ID: 'conversationID' };
expect(isUnread(conversation, '')).toBe(false);
});
it('should take the NumUnread property of a conversation', () => {
const conversation = { NumUnread: 0, ID: 'conversationID' };
expect(isUnread(conversation, '')).toBe(false);
});
it('should take the value when all are present for a conversation', () => {
const LabelID = 'LabelID';
const conversation = {
ID: 'conversationID',
ContextNumUnread: 1,
NumUnread: 1,
Labels: [{ ID: LabelID, ContextNumUnread: 0 } as ConversationLabel],
};
expect(isUnread(conversation, LabelID)).toBe(false);
});
});
});
|
3,803 | 0 | petrpan-code/ProtonMail/WebClients/applications/mail/src/app | petrpan-code/ProtonMail/WebClients/applications/mail/src/app/helpers/encryptionType.test.ts | import { Message } from '@proton/shared/lib/interfaces/mail/Message';
import { MESSAGE_FLAGS } from '@proton/shared/lib/mail/constants';
import { I18N, getEncryptionType, getFromType } from './encryptionType';
describe('getFromType', () => {
it('should be sent encrypted', () => {
const message = {
Flags: MESSAGE_FLAGS.FLAG_E2E | MESSAGE_FLAGS.FLAG_SENT,
} as Message;
expect(getFromType(message)).toEqual(I18N.sentEncrypted);
});
it('should be auto', () => {
const message = {
Flags: MESSAGE_FLAGS.FLAG_AUTO,
} as Message;
expect(getFromType(message)).toEqual(I18N.auto);
});
it('should be sent', () => {
const message = {
Flags: MESSAGE_FLAGS.FLAG_SENT,
} as Message;
expect(getFromType(message)).toEqual(I18N.sentClear);
});
it('should be a draft', () => {
const message = {
Flags: 0,
} as Message;
expect(getFromType(message)).toEqual(I18N.draft);
});
it('should be internal encrypted', () => {
const message = {
Flags: MESSAGE_FLAGS.FLAG_E2E | MESSAGE_FLAGS.FLAG_INTERNAL | MESSAGE_FLAGS.FLAG_RECEIVED,
} as Message;
expect(getFromType(message)).toEqual(I18N.pm);
});
it('should be external encrypted', () => {
const message = {
Flags: MESSAGE_FLAGS.FLAG_E2E | MESSAGE_FLAGS.FLAG_RECEIVED,
} as Message;
expect(getFromType(message)).toEqual(I18N.pgp);
});
it('should be clear', () => {
const message = {
Flags: MESSAGE_FLAGS.FLAG_RECEIVED,
} as Message;
expect(getFromType(message)).toEqual(I18N.clear);
});
});
describe('getEncryptionType', () => {
it('should return the encryption type', () => {
const message = {
Flags: MESSAGE_FLAGS.FLAG_RECEIVED,
} as Message;
expect(getEncryptionType({ data: message, verified: 1 })).toEqual(I18N.clear[1]);
});
it('should return encryption type for old messages', () => {
const message = {
Time: 0,
Flags: MESSAGE_FLAGS.FLAG_E2E | MESSAGE_FLAGS.FLAG_SENT,
} as Message;
expect(getEncryptionType({ data: message, verified: 2 })).toEqual(I18N.sentEncrypted[0]);
});
it('should return default encryption type when verified is to big', () => {
const message = {
Flags: MESSAGE_FLAGS.FLAG_RECEIVED,
} as Message;
expect(getEncryptionType({ data: message, verified: 10 })).toEqual(I18N.clear[0]);
});
});
|
3,804 | 0 | petrpan-code/ProtonMail/WebClients/applications/mail/src/app | petrpan-code/ProtonMail/WebClients/applications/mail/src/app/helpers/errors.test.ts | import { ConversationErrors } from '../logic/conversations/conversationsTypes';
import { MessageErrors, MessageState } from '../logic/messages/messagesTypes';
import { hasError, hasErrorType, isDecryptionError, isNetworkError, pickMessageInfosForSentry } from './errors';
import { createDocument } from './test/message';
describe('isNetworkError', () => {
it('should be a network error', () => {
const error1 = {
name: 'NetworkError',
};
const error2 = {
name: 'OfflineError',
};
const error3 = {
name: 'TimeoutError',
};
expect(isNetworkError(error1)).toBeTruthy();
expect(isNetworkError(error2)).toBeTruthy();
expect(isNetworkError(error3)).toBeTruthy();
});
it('should not be a network error', () => {
const error1 = {};
const error2 = {
name: 'Something else',
};
expect(isNetworkError(error1)).toBeFalsy();
expect(isNetworkError(error2)).toBeFalsy();
});
});
describe('isDecryptionError', () => {
it('should be a decryption error', function () {
const error = {
message: 'Error decrypting something',
};
expect(isDecryptionError(error)).toBeTruthy();
});
it('should not be a decryption error', function () {
const error1 = {
message: 'something Error decrypting something',
};
const error2 = {
message: 'something else',
};
const error3 = {};
expect(isDecryptionError(error1)).toBeFalsy();
expect(isDecryptionError(error2)).toBeFalsy();
expect(isDecryptionError(error3)).toBeFalsy();
});
});
describe('hasError', () => {
it('should have errors', function () {
const messageErrors = {
network: [{ message: 'something failed' }],
} as MessageErrors;
const conversationErrors = {
network: [{ message: 'something failed' }],
} as ConversationErrors;
expect(hasError(messageErrors)).toBeTruthy();
expect(hasError(conversationErrors)).toBeTruthy();
});
it('should not have errors', () => {
const messageErrors1 = {
network: [],
} as MessageErrors;
const messageErrors2 = {} as MessageErrors;
const conversationErrors1 = {
network: [],
} as ConversationErrors;
const conversationErrors2 = {} as ConversationErrors;
expect(hasError(messageErrors1)).toBeFalsy();
expect(hasError(messageErrors2)).toBeFalsy();
expect(hasError(conversationErrors1)).toBeFalsy();
expect(hasError(conversationErrors2)).toBeFalsy();
expect(hasError(undefined)).toBeFalsy();
});
});
describe('hasErrorType', () => {
it('should have error from type network', function () {
const messageErrors = {
network: [{ message: 'something failed' }],
} as MessageErrors;
const conversationErrors = {
network: [{ message: 'something failed' }],
} as ConversationErrors;
expect(hasErrorType(messageErrors, 'network')).toBeTruthy();
expect(hasErrorType(conversationErrors, 'network')).toBeTruthy();
});
it('should not have error from type network', function () {
const messageErrors1 = {
decryption: [{ message: 'something failed' }],
} as MessageErrors;
const messageErrors2 = {} as MessageErrors;
const conversationErrors1 = {
notExist: [{ message: 'something failed' }],
} as ConversationErrors;
const conversationErrors2 = {} as ConversationErrors;
expect(hasErrorType(messageErrors1, 'network')).toBeFalsy();
expect(hasErrorType(messageErrors2, 'network')).toBeFalsy();
expect(hasErrorType(conversationErrors1, 'network')).toBeFalsy();
expect(hasErrorType(conversationErrors2, 'network')).toBeFalsy();
expect(hasErrorType(undefined, 'network')).toBeFalsy();
});
});
describe('pickMessageInfosForSentry', () => {
it('should not send sensitive infos to Sentry', () => {
const message = {
localID: 'localID',
loadRetry: 2,
errors: {
network: [{ message: 'something failed' }],
},
data: {
Subject: 'Mail subject',
ToList: [{ Name: 'Name', Address: '[email protected]' }],
},
decryption: {
decryptedBody: 'Message body',
},
messageDocument: {
document: createDocument('Message body'),
},
} as MessageState;
const expected = {
localID: 'localID',
loadRetry: 2,
errors: {
network: [{ message: 'something failed' }],
},
};
expect(pickMessageInfosForSentry(message)).toEqual(expected);
});
});
|
3,806 | 0 | petrpan-code/ProtonMail/WebClients/applications/mail/src/app | petrpan-code/ProtonMail/WebClients/applications/mail/src/app/helpers/expiration.test.ts | import { add, addDays, differenceInMinutes, getUnixTime, sub } from 'date-fns';
import { MAILBOX_LABEL_IDS } from '@proton/shared/lib/constants';
import { UserModel } from '@proton/shared/lib/interfaces';
import { MessageState } from '../logic/messages/messagesTypes';
import { canSetExpiration, getExpirationTime, getMinExpirationTime, isExpired } from './expiration';
describe('canSetExpiration', () => {
const messageState = {
data: {
LabelIDs: ['label1', 'label2'],
},
} as MessageState;
const incorrectMessageState = {
data: {
LabelIDs: [MAILBOX_LABEL_IDS.SPAM, MAILBOX_LABEL_IDS.TRASH],
},
} as MessageState;
it('should return false if feature flag is false', () => {
expect(canSetExpiration(false, { hasPaidMail: true } as UserModel, messageState)).toBe(false);
});
it('should return false if user is free', () => {
expect(canSetExpiration(true, { isFree: true } as UserModel, messageState)).toBe(false);
});
it('should return false if user is paid but not paid mail', () => {
expect(canSetExpiration(true, { isPaid: true, hasPaidMail: false } as UserModel, messageState)).toBe(false);
});
it('should return true if feature flag is true and user is paid mail', () => {
expect(canSetExpiration(true, { hasPaidMail: true } as UserModel, messageState)).toBe(true);
});
it('should return false if labelIDs contains spam or trash', () => {
expect(canSetExpiration(true, { hasPaidMail: true } as UserModel, incorrectMessageState)).toBe(false);
});
});
describe('getExpirationTime', () => {
it('should return null if days is undefined', () => {
expect(getExpirationTime(undefined)).toBe(null);
});
it('should return a Unix timestamp if days is > 0', () => {
expect(getExpirationTime(addDays(new Date(), 1))).toBeGreaterThan(0);
});
});
describe('isExpired', () => {
it('should return false', () => {
expect(isExpired({ ExpirationTime: getUnixTime(add(new Date(), { hours: 1 })) })).toBeFalsy();
});
describe('when message expiration is before now', () => {
it('should return true', () => {
expect(isExpired({ ExpirationTime: getUnixTime(sub(new Date(), { hours: 1 })) })).toBeTruthy();
});
});
describe('when date is provided', () => {
const timestamp = getUnixTime(new Date(2023, 7, 27, 0, 0, 0, 0));
describe('when message expiration is after provided date', () => {
it('should return false', () => {
expect(
isExpired({ ExpirationTime: getUnixTime(sub(new Date(), { hours: 1 })) }, timestamp)
).toBeFalsy();
});
});
describe('when message expiration is before provided date', () => {
it('should return true', () => {
expect(
isExpired({ ExpirationTime: getUnixTime(sub(new Date(timestamp), { hours: 1 })) }, timestamp)
).toBeTruthy();
});
});
});
});
describe('getMinExpirationTime', () => {
it('should return undefined if date is not today', () => {
expect(getMinExpirationTime(addDays(new Date(), 1))).toBe(undefined);
});
it('should return a Date if date is today', () => {
expect(getMinExpirationTime(new Date())).toBeInstanceOf(Date);
});
it('should return a Date with minutes set to 0 or 30', () => {
const date = getMinExpirationTime(new Date());
const minutes = date?.getMinutes();
expect(minutes === 0 || minutes === 30).toBe(true);
});
it('should return a older next interval from now with a difference of at least 15 minutes', () => {
const now = new Date();
const interval = getMinExpirationTime(now);
if (!interval) {
throw new Error('Interval is undefined');
}
expect(interval > now).toBe(true);
expect(differenceInMinutes(interval, now)).toBeGreaterThanOrEqual(15);
});
});
|
3,808 | 0 | petrpan-code/ProtonMail/WebClients/applications/mail/src/app | petrpan-code/ProtonMail/WebClients/applications/mail/src/app/helpers/labels.test.ts | import { MAILBOX_LABEL_IDS } from '@proton/shared/lib/constants';
import { MessageWithOptionalBody } from '../logic/messages/messagesTypes';
import { Conversation } from '../models/conversation';
import {
applyLabelChangesOnConversation,
applyLabelChangesOnMessage,
applyLabelChangesOnOneMessageOfAConversation,
canMoveAll,
shouldDisplayTotal,
} from './labels';
const { INBOX, TRASH, SPAM, ARCHIVE, SENT, ALL_SENT, DRAFTS, ALL_DRAFTS, SCHEDULED, ALL_MAIL } = MAILBOX_LABEL_IDS;
const labelID = 'LabelID';
describe('labels', () => {
describe('applyLabelChangesOnMessage', () => {
it('should remove a label from a message', () => {
const input = {
LabelIDs: [labelID],
} as unknown as MessageWithOptionalBody;
const changes = { [labelID]: false };
const message = applyLabelChangesOnMessage(input, changes);
expect(message.LabelIDs?.length).toBe(0);
});
it('should add a label for a message', () => {
const input = {
LabelIDs: [],
} as unknown as MessageWithOptionalBody;
const changes = { [labelID]: true };
const message = applyLabelChangesOnMessage(input, changes);
expect(message.LabelIDs?.length).toBe(1);
expect(message.LabelIDs[0]).toBe(labelID);
});
});
describe('applyLabelChangesOnConversation', () => {
it('should remove a label from a conversation', () => {
const input = {
Labels: [{ ID: labelID, ContextNumMessages: 5 }],
} as Conversation;
const changes = { [labelID]: false };
const conversation = applyLabelChangesOnConversation(input, changes);
expect(conversation.Labels?.length).toBe(0);
});
it('should add a label for a conversation', () => {
const input = {
ID: 'conversationID',
Labels: [],
} as Conversation;
const changes = { [labelID]: true };
const conversation = applyLabelChangesOnConversation(input, changes);
expect(conversation.Labels?.length).toBe(1);
});
});
describe('applyLabelChangesOnOneMessageOfAConversation', () => {
it('should remove a label from a conversation when remove the label on the last message having it', () => {
const input = {
Labels: [{ ID: labelID, ContextNumMessages: 1 }],
} as Conversation;
const changes = { [labelID]: false };
const { updatedConversation } = applyLabelChangesOnOneMessageOfAConversation(input, changes);
expect(updatedConversation.Labels?.length).toBe(0);
});
it('should keep a label from a conversation when remove the label on a message but not the last having it', () => {
const numMessages = 3;
const input = {
Labels: [{ ID: labelID, ContextNumMessages: numMessages }],
} as Conversation;
const changes = { [labelID]: false };
const { updatedConversation } = applyLabelChangesOnOneMessageOfAConversation(input, changes);
expect(updatedConversation.Labels?.length).toBe(1);
expect(updatedConversation.Labels?.[0].ContextNumMessages).toBe(numMessages - 1);
});
it('should add a label to a conversation when adding the label to the first message having it', () => {
const input = {
ID: 'conversationID',
Labels: [],
} as Conversation;
const changes = { [labelID]: true };
const { updatedConversation } = applyLabelChangesOnOneMessageOfAConversation(input, changes);
expect(updatedConversation.Labels?.length).toBe(1);
expect(updatedConversation.Labels?.[0].ContextNumMessages).toBe(1);
});
it('should keep a label to a conversation when adding the label to a message but not the first having it', () => {
const numMessages = 3;
const input = {
Labels: [{ ID: labelID, ContextNumMessages: numMessages }],
} as Conversation;
const changes = { [labelID]: true };
const { updatedConversation } = applyLabelChangesOnOneMessageOfAConversation(input, changes);
expect(updatedConversation.Labels?.length).toBe(1);
expect(updatedConversation.Labels?.[0].ContextNumMessages).toBe(numMessages + 1);
});
});
describe('shouldDisplayTotal', () => {
it.each`
label | expectedShouldDisplayTotal
${SCHEDULED} | ${true}
${INBOX} | ${false}
${TRASH} | ${false}
${SPAM} | ${false}
${ARCHIVE} | ${false}
${SENT} | ${false}
${ALL_SENT} | ${false}
${DRAFTS} | ${false}
${ALL_DRAFTS} | ${false}
`(
'should display the total: [$expectedShouldDisplayTotal] in [$label]',
async ({ label, expectedShouldDisplayTotal }) => {
const needsToDisplayTotal = shouldDisplayTotal(label);
expect(expectedShouldDisplayTotal).toEqual(needsToDisplayTotal);
}
);
});
describe('canMoveAll', () => {
it('should not be possible to move all from some locations', () => {
const locations = [ALL_MAIL, SCHEDULED, ALL_DRAFTS, ALL_SENT];
locations.forEach((location) => {
expect(canMoveAll(location, TRASH, ['elementID'], [], false));
});
});
it('should not be possible to move all when no elements in location', () => {
expect(canMoveAll(SENT, TRASH, [], [], false));
});
it('should not be possible to move all when some elements are selected', () => {
expect(canMoveAll(SENT, TRASH, ['elementID'], ['elementID'], false));
});
it('should be possible to move all', () => {
expect(canMoveAll(SENT, TRASH, ['elementID'], [], false));
});
});
});
|
3,810 | 0 | petrpan-code/ProtonMail/WebClients/applications/mail/src/app | petrpan-code/ProtonMail/WebClients/applications/mail/src/app/helpers/mail.test.ts | import { combineHeaders, splitMail } from './mail';
describe('combineHeaders', () => {
it('should combine headers', async () => {
const baseHeader = `Return-Path: <[email protected]>
X-Original-To: [email protected]
Delivered-To: [email protected]
Content-Type: text/html
Date: Mon, 6 Feb 2023 16:47:37 +0100`;
const extraHeaders = `Content-Type: multipart/mixed;boundary=---------------------something`;
const expected = `Return-Path: <[email protected]>
X-Original-To: [email protected]
Delivered-To: [email protected]
Content-Type: multipart/mixed;boundary=---------------------something
Date: Mon, 6 Feb 2023 16:47:37 +0100`;
const result = await combineHeaders(baseHeader, extraHeaders);
expect(result).toEqual(expected);
});
});
describe('splitMail', () => {
it('should split the mail into header and body', function () {
const mailHeaders = `Content-Type: multipart/mixed;boundary=---------------------something1`;
const mailBody = `-----------------------something1
Content-Type: multipart/related;boundary=---------------------something2
-----------------------something2
Content-Type: text/html;charset=utf-8
Content-Transfer-Encoding: base64
messageContenthlYWQ+CgogICAgPG1ldGEgaHR0cC1lcXVpdj0iY29udGVudC10eXBlIiBjb250
ZW50PSJ0ZXh0L2h0bWw7IGNoYXJzZXQ9VVRGLTgiPgogIDwvaGVhZD4KICA8Ym9keT4KICAgIDxw
PjxhIGhyZWY9Im1haWx0bzpTbGFjawombHQ7ZWItVDAzRFA0QzRDLVU3VjRaRlFLQi1ibXVzNmxw
M3dzamVwajNzbjJ3dWt1ZHY2dUBzbGFjay1tYWlsLmNvbSZndDs/c3ViamVjdD1SZXBseQogICAg
ICAgIHRvIFZvam8gSWxpZXZza2kiPlJlcGx5PC9hPgogICAgICA8YSBocmVmPSJtYWlsdG86Uk9S
TwogICAgICAgICZsdDtyb3JvdGVzdDVAcHJvdG9ubWFpbC5jb20mZ3Q7P3N1YmplY3Q9UmVwbHkg
dG8gcm9ybyI+UmVwbHk8L2E+PC9wPgogIDwvYm9keT4KPC9odG1sPgo=
-----------------------something2--
-----------------------something1--`;
const mailString = `${mailHeaders}
${mailBody}`;
const { headers, body } = splitMail(mailString);
expect(headers).toEqual(mailHeaders);
expect(body).toEqual(mailBody);
});
});
|
3,812 | 0 | petrpan-code/ProtonMail/WebClients/applications/mail/src/app | petrpan-code/ProtonMail/WebClients/applications/mail/src/app/helpers/mailSettings.test.ts | import { MAILBOX_LABEL_IDS } from '@proton/shared/lib/constants';
import { VIEW_MODE } from '@proton/shared/lib/mail/mailSettings';
import { isConversationMode } from './mailSettings';
describe('mailSettings', () => {
describe('isConversationMode', () => {
const emptyLocation = { pathname: '', search: '', state: {}, hash: '' };
const locationWithParameters = { pathname: '', search: '', state: {}, hash: '#keyword=panda' };
it('should be false if labelID is single only', () => {
expect(isConversationMode(MAILBOX_LABEL_IDS.ALL_DRAFTS, { ViewMode: VIEW_MODE.GROUP }, emptyLocation)).toBe(
false
);
});
it('should be false if mail settings is single', () => {
expect(
isConversationMode(MAILBOX_LABEL_IDS.ALL_DRAFTS, { ViewMode: VIEW_MODE.SINGLE }, emptyLocation)
).toBe(false);
});
it('should be true if mail settings is group and label is not single only', () => {
expect(isConversationMode(MAILBOX_LABEL_IDS.INBOX, { ViewMode: VIEW_MODE.GROUP }, emptyLocation)).toBe(
true
);
});
it('should be false if search parameters are defined', () => {
expect(
isConversationMode(MAILBOX_LABEL_IDS.INBOX, { ViewMode: VIEW_MODE.GROUP }, locationWithParameters)
).toBe(false);
});
});
});
|
3,815 | 0 | petrpan-code/ProtonMail/WebClients/applications/mail/src/app | petrpan-code/ProtonMail/WebClients/applications/mail/src/app/helpers/moveToFolder.test.ts | import { MAILBOX_LABEL_IDS } from '@proton/shared/lib/constants';
import { Label, MailSettings } from '@proton/shared/lib/interfaces';
import { SPAM_ACTION } from '@proton/shared/lib/mail/mailSettings';
import { addApiMock, apiMock } from '@proton/testing/lib/api';
import {
askToUnsubscribe,
getNotificationTextMoved,
getNotificationTextUnauthorized,
searchForScheduled,
} from '../helpers/moveToFolder';
import { Element } from '../models/element';
const { SPAM, TRASH, SENT, ALL_SENT, DRAFTS, ALL_DRAFTS, INBOX, SCHEDULED } = MAILBOX_LABEL_IDS;
describe('moveToFolder', () => {
describe('getNotificationTextMoved', () => {
it.each`
folderID | isMessage | elementsCount | messagesNotAuthorizedToMove | folderName | fromLabelID | expectedText
${SPAM} | ${true} | ${1} | ${1} | ${`Spam`} | ${undefined} | ${`Message moved to spam and sender added to your spam list.`}
${SPAM} | ${true} | ${2} | ${0} | ${`Spam`} | ${undefined} | ${`2 messages moved to spam and senders added to your spam list.`}
${SPAM} | ${true} | ${2} | ${1} | ${`Spam`} | ${undefined} | ${`2 messages moved to spam and senders added to your spam list. 1 message could not be moved.`}
${SPAM} | ${false} | ${1} | ${1} | ${`Spam`} | ${undefined} | ${`Conversation moved to spam and sender added to your spam list.`}
${SPAM} | ${false} | ${2} | ${1} | ${`Spam`} | ${undefined} | ${`2 conversations moved to spam and senders added to your spam list.`}
${INBOX} | ${true} | ${1} | ${1} | ${`Inbox`} | ${SPAM} | ${`Message moved to Inbox and sender added to your not spam list.`}
${INBOX} | ${true} | ${2} | ${0} | ${`Inbox`} | ${SPAM} | ${`2 messages moved to Inbox and senders added to your not spam list.`}
${INBOX} | ${true} | ${2} | ${1} | ${`Inbox`} | ${SPAM} | ${`2 messages moved to Inbox and senders added to your not spam list. 1 message could not be moved.`}
${INBOX} | ${false} | ${1} | ${1} | ${`Inbox`} | ${SPAM} | ${`Conversation moved to Inbox and sender added to your not spam list.`}
${INBOX} | ${false} | ${2} | ${1} | ${`Inbox`} | ${SPAM} | ${`2 conversations moved to Inbox and senders added to your not spam list.`}
${TRASH} | ${true} | ${1} | ${1} | ${`Trash`} | ${INBOX} | ${`Message moved to Trash.`}
${TRASH} | ${true} | ${2} | ${0} | ${`Trash`} | ${INBOX} | ${`2 messages moved to Trash.`}
${TRASH} | ${true} | ${2} | ${1} | ${`Trash`} | ${INBOX} | ${`2 messages moved to Trash. 1 message could not be moved.`}
${TRASH} | ${false} | ${1} | ${1} | ${`Trash`} | ${INBOX} | ${`Conversation moved to Trash.`}
${TRASH} | ${false} | ${2} | ${1} | ${`Trash`} | ${INBOX} | ${`2 conversations moved to Trash.`}
`(
'should return expected text [$expectedText]',
({
isMessage,
elementsCount,
messagesNotAuthorizedToMove,
folderName,
folderID,
fromLabelID,
expectedText,
}) => {
expect(
getNotificationTextMoved(
isMessage,
elementsCount,
messagesNotAuthorizedToMove,
folderName,
folderID,
fromLabelID
)
).toEqual(expectedText);
}
);
});
describe('getNotificationTextUnauthorized', () => {
it.each`
folderID | fromLabelID | expectedText
${INBOX} | ${SENT} | ${`Sent messages cannot be moved to Inbox`}
${INBOX} | ${ALL_SENT} | ${`Sent messages cannot be moved to Inbox`}
${SPAM} | ${SENT} | ${`Sent messages cannot be moved to Spam`}
${SPAM} | ${ALL_SENT} | ${`Sent messages cannot be moved to Spam`}
${INBOX} | ${DRAFTS} | ${`Drafts cannot be moved to Inbox`}
${INBOX} | ${ALL_DRAFTS} | ${`Drafts cannot be moved to Inbox`}
${SPAM} | ${DRAFTS} | ${`Drafts cannot be moved to Spam`}
${SPAM} | ${ALL_DRAFTS} | ${`Drafts cannot be moved to Spam`}
`(`should return expected text [$expectedText]} `, ({ folderID, fromLabelID, expectedText }) => {
expect(getNotificationTextUnauthorized(folderID, fromLabelID)).toEqual(expectedText);
});
});
describe('searchForScheduled', () => {
it('should show move schedule modal when moving scheduled messages', async () => {
const folderID = TRASH;
const isMessage = true;
const elements: Element[] = [{ LabelIDs: [SCHEDULED] } as Element];
const setCanUndo = jest.fn();
const handleShowModal = jest.fn();
await searchForScheduled(folderID, isMessage, elements, setCanUndo, handleShowModal);
expect(handleShowModal).toHaveBeenCalled();
});
it('should not show move schedule modal when moving other type of messages', async () => {
const folderID = TRASH;
const isMessage = true;
const elements: Element[] = [{ LabelIDs: [SPAM] } as Element];
const setCanUndo = jest.fn();
const handleShowModal = jest.fn();
await searchForScheduled(folderID, isMessage, elements, setCanUndo, handleShowModal);
expect(handleShowModal).not.toHaveBeenCalled();
});
it('should show move schedule modal when moving scheduled conversations', async () => {
const folderID = TRASH;
const isMessage = false;
const elements: Element[] = [
{
ID: 'conversation',
Labels: [{ ID: SCHEDULED } as Label],
} as Element,
];
const setCanUndo = jest.fn();
const handleShowModal = jest.fn();
await searchForScheduled(folderID, isMessage, elements, setCanUndo, handleShowModal);
expect(handleShowModal).toHaveBeenCalled();
});
it('should not show move schedule modal when moving other types of conversations', async () => {
const folderID = TRASH;
const isMessage = false;
const elements: Element[] = [
{
ID: 'conversation',
Labels: [{ ID: SPAM } as Label],
} as Element,
];
const setCanUndo = jest.fn();
const handleShowModal = jest.fn();
await searchForScheduled(folderID, isMessage, elements, setCanUndo, handleShowModal);
expect(handleShowModal).not.toHaveBeenCalled();
});
});
describe('askToUnsubscribe', () => {
it('should not open the unsubscribe modal when SpamAction in setting is set', async () => {
const folderID = SPAM;
const isMessage = true;
const elements = [{} as Element];
const api = apiMock;
const handleShowSpamModal = jest.fn();
const mailSettings = { SpamAction: SPAM_ACTION.SpamAndUnsub } as MailSettings;
await askToUnsubscribe(folderID, isMessage, elements, api, handleShowSpamModal, mailSettings);
expect(handleShowSpamModal).not.toHaveBeenCalled();
});
it('should not open the unsubscribe modal when no message can be unsubscribed', async () => {
const folderID = SPAM;
const isMessage = true;
const elements = [{} as Element];
const api = apiMock;
const handleShowSpamModal = jest.fn();
const mailSettings = { SpamAction: null } as MailSettings;
await askToUnsubscribe(folderID, isMessage, elements, api, handleShowSpamModal, mailSettings);
expect(handleShowSpamModal).not.toHaveBeenCalled();
});
it('should open the unsubscribe modal and unsubscribe', async () => {
const folderID = SPAM;
const isMessage = true;
const elements = [
{
UnsubscribeMethods: {
OneClick: 'OneClick',
},
} as Element,
];
const api = apiMock;
const handleShowSpamModal = jest.fn(() => {
return Promise.resolve({ unsubscribe: true, remember: false });
});
const mailSettings = { SpamAction: null } as MailSettings;
const result = await askToUnsubscribe(
folderID,
isMessage,
elements,
api,
handleShowSpamModal,
mailSettings
);
expect(result).toEqual(SPAM_ACTION.SpamAndUnsub);
expect(handleShowSpamModal).toHaveBeenCalled();
});
it('should open the unsubscribe modal but not unsubscribe', async () => {
const folderID = SPAM;
const isMessage = true;
const elements = [
{
UnsubscribeMethods: {
OneClick: 'OneClick',
},
} as Element,
];
const api = apiMock;
const handleShowSpamModal = jest.fn(() => {
return Promise.resolve({ unsubscribe: false, remember: false });
});
const mailSettings = { SpamAction: null } as MailSettings;
const result = await askToUnsubscribe(
folderID,
isMessage,
elements,
api,
handleShowSpamModal,
mailSettings
);
expect(result).toEqual(SPAM_ACTION.JustSpam);
expect(handleShowSpamModal).toHaveBeenCalled();
});
it('should remember to always unsubscribe', async () => {
const updateSettingSpy = jest.fn();
addApiMock(`mail/v4/settings/spam-action`, updateSettingSpy, 'put');
const folderID = SPAM;
const isMessage = true;
const elements = [
{
UnsubscribeMethods: {
OneClick: 'OneClick',
},
} as Element,
];
const api = apiMock;
const handleShowSpamModal = jest.fn(() => {
return Promise.resolve({ unsubscribe: true, remember: true });
});
const mailSettings = { SpamAction: null } as MailSettings;
const result = await askToUnsubscribe(
folderID,
isMessage,
elements,
api,
handleShowSpamModal,
mailSettings
);
expect(result).toEqual(SPAM_ACTION.SpamAndUnsub);
expect(handleShowSpamModal).toHaveBeenCalled();
expect(updateSettingSpy).toHaveBeenCalled();
});
});
});
|
3,817 | 0 | petrpan-code/ProtonMail/WebClients/applications/mail/src/app | petrpan-code/ProtonMail/WebClients/applications/mail/src/app/helpers/paging.test.ts | import { expectedPageLength, pageCount } from './paging';
describe('paging helper', () => {
describe('pageCount', () => {
it('should be 1 when total is less than size', () => {
expect(pageCount(10)).toBe(1);
});
it('should be the number of pages the user can see', () => {
expect(pageCount(125)).toBe(3);
});
});
describe('expectedPageLength', () => {
it('should be 0 if total is 0', () => {
expect(expectedPageLength(0, 0, 0)).toBe(0);
});
it('should be size if total is a multiple of the size', () => {
expect(expectedPageLength(0, 150, 0)).toBe(50);
});
it('should be the rest on last page', () => {
expect(expectedPageLength(2, 125, 0)).toBe(25);
});
it('should be the size if not last page', () => {
expect(expectedPageLength(1, 125, 0)).toBe(50);
});
it('should be 0 if page is after the total', () => {
expect(expectedPageLength(2, 100, 0)).toBe(0);
});
it('should deal with bypass filter when less than a page', () => {
expect(expectedPageLength(0, 25, 2)).toBe(27);
});
it('should deal with bypass filter even if there is no more elements', () => {
expect(expectedPageLength(0, 0, 2)).toBe(2);
});
it('should deal with bypass filter in a middle of a list', () => {
expect(expectedPageLength(1, 125, 2)).toBe(50);
});
it('should deal with bypass filter in the last page', () => {
expect(expectedPageLength(2, 125, 2)).toBe(27);
});
it('should deal with bypass filter if it changes the page cont', () => {
expect(expectedPageLength(0, 40, 20)).toBe(50);
});
it("should deal with bypass filter if it's huge", () => {
expect(expectedPageLength(0, 20, 60)).toBe(50);
});
});
});
|
3,819 | 0 | petrpan-code/ProtonMail/WebClients/applications/mail/src/app | petrpan-code/ProtonMail/WebClients/applications/mail/src/app/helpers/parserHtml.test.ts | import { toText } from './parserHtml';
describe('toText', () => {
it('should not escape single underline', () => {
const string = 'MONO_TLS_PROVIDER';
expect(toText(string)).toEqual(string);
});
it('should not escape multiple underlines', () => {
const string = '___';
expect(toText(string)).toEqual(string);
});
it('should convert to the right format if there are LIs', () => {
const input = `
<div class="protonmail_signature_block">
<div class="protonmail_signature_block-user">
<div>jeanne mange <b>une boule de glace</b> <i>à la vanille.</i><br></div>
<ul>
<li>Une vache<br></li>
<li>Un ane<br></li>
<li>Une brebis<br></li>
</ul>
<div>A table<br></div>
</div>
<div><br></div>
<div class="protonmail_signature_block-proton">Sent with <a href="https://proton.me/?utm_campaign=ww-all-2a-mail-pmm_mail-protonmail_signature&utm_source=proton_users&utm_medium=cta&utm_content=sent_with_protonmail_secure_email" target="_blank">ProtonMail</a> Secure Email.<br></div>
</div>`;
const result = `jeanne mange\xa0une boule de glace\xa0à la vanille.
- Une vache
- Un ane
- Une brebis
A table
Sent with ProtonMail Secure Email.`;
expect(toText(input)).toEqual(result);
});
it('should convert to the right format', () => {
const input = `
<div class="protonmail_signature_block">
<div class="protonmail_signature_block-user">
<div>: <a href="http://anothercoffee.net">http://anothercoffee.net</a><br></div>
<div>: Drupal to WordPress migration specialists<br></div>
<div>:<br></div>
<div>: Another Cup of Coffee Limited<br></div>
<div>: Registered in England and Wales number 05992203<br></div>
</div>
<div><br></div>
<div class="protonmail_signature_block-proton">Sent with <a href="https://proton.me/?utm_campaign=ww-all-2a-mail-pmm_mail-protonmail_signature&utm_source=proton_users&utm_medium=cta&utm_content=sent_with_protonmail_secure_email" target="_blank">ProtonMail</a> Secure Email.<br></div>
</div>`;
const result = `: http://anothercoffee.net
: Drupal to WordPress migration specialists
:
: Another Cup of Coffee Limited
: Registered in England and Wales number 05992203
Sent with ProtonMail Secure Email.`;
expect(toText(input)).toEqual(result);
});
it('should keep the lines in signature', () => {
const input = `
<div class="protonmail_signature_block">
<div class="protonmail_signature_block-user">
<div>---<br></div><div>This is a test account<br></div><div><br></div><div>[email protected]<br></div>
</div>
<div class="protonmail_signature_block-proton protonmail_signature_block-empty">
</div>
</div>
`;
const result = `---
This is a test account
[email protected]`;
expect(toText(input)).toBe(result);
});
it('should keep the lines in original message', () => {
const input = `
<blockquote class="protonmail_quote" type="cite">
<div>Hey, this is a plain text message!<br>
<br>
Even with no less than 2 lines!</div>
</blockquote>
`;
const result = `> Hey, this is a plain text message!
>
> Even with no less than 2 lines!`;
expect(toText(input)).toBe(result);
});
it('should keep the lines in list', () => {
const input = `
<ul>
<li>content 1<br> content<br></li>
<li>content 2<br> content</li>
</ul>
`;
const result = `- content 1
content
- content 2
content`;
expect(toText(input)).toBe(result);
});
it('should keep empty lines in the beginning', () => {
const input = `
<div style="font-family: verdana; font-size: 20px;"><br></div>
<div style="font-family: verdana; font-size: 20px;"><br></div>
<div style="font-family: verdana; font-size: 20px;">test<br></div>
<div style="font-family: verdana; font-size: 20px;"><br></div>
<div style="font-family: verdana; font-size: 20px;"><br></div>
<div style="font-family: verdana; font-size: 20px;"><br></div>
<div style="font-family: verdana; font-size: 20px;"><br></div>
<div style="font-family: verdana; font-size: 20px;"><br></div>
<div class="protonmail_signature_block" style="font-family: verdana; font-size: 20px;">
<div class="protonmail_signature_block-user">
<div style="font-family:arial;font-size:14px;color:rgb(34,34,34);">my signature</div>
</div>
<div class="protonmail_signature_block-proton protonmail_signature_block-empty">
</div>
</div>
`;
const result = `
test
my signature`;
expect(toText(input)).toBe(result);
});
it('should keep empty lines in the content and the signature', () => {
const input = `
<div style="font-family: verdana; font-size: 20px;">Testcontent1</div>
<div style="font-family: verdana; font-size: 20px;"><br></div>
<div style="font-family: verdana; font-size: 20px;">Testcontent2</div>
<div style="font-family: verdana; font-size: 20px;"><br></div>
<div style="font-family: verdana; font-size: 20px;">Testcontent3</div>
<div style="font-family: verdana; font-size: 20px;"><br></div>
<div class="protonmail_signature_block" style="font-family: verdana; font-size: 20px;">
<div class="protonmail_signature_block-user">
<div style="font-family:arial;font-size:14px;color:rgb(34,34,34);">Test1</div>
<div style="font-family:arial;font-size:14px;color:rgb(34,34,34);"><br></div>
<div style="font-family:arial;font-size:14px;color:rgb(34,34,34);">Testtest2</div>
<div style="font-family:arial;font-size:14px;color:rgb(34,34,34);"><br></div>
<div style="font-family:arial;font-size:14px;color:rgb(34,34,34);">Testtesttest3</div>
<div style="font-family:arial;font-size:14px;color:rgb(34,34,34);"><br></div>
<div style="font-family:arial;font-size:14px;color:rgb(34,34,34);">Testtesttesttest4</div>
</div>
<div class="protonmail_signature_block-proton protonmail_signature_block-empty"></div>
</div>
`;
const result = `Testcontent1
Testcontent2
Testcontent3
Test1
Testtest2
Testtesttest3
Testtesttesttest4`;
expect(toText(input)).toBe(result);
});
});
|
3,821 | 0 | petrpan-code/ProtonMail/WebClients/applications/mail/src/app | petrpan-code/ProtonMail/WebClients/applications/mail/src/app/helpers/recipients.test.ts | import { Recipient } from '@proton/shared/lib/interfaces';
import { Message } from '@proton/shared/lib/interfaces/mail/Message';
import { Conversation } from '../models/conversation';
import { getElementSenders } from './recipients';
describe('recipients helpers', () => {
const sender: Recipient = {
Address: '[email protected]',
Name: 'Sender',
};
const recipient: Recipient = {
Address: '[email protected]',
Name: 'Recipient',
};
it('should give the sender of a message', () => {
const message = {
Sender: sender,
} as Message;
const result = getElementSenders(message, false, false);
const expected: Recipient[] = [sender];
expect(result).toEqual(expected);
});
it('should give the recipients of a message', () => {
const message = {
Sender: sender,
ToList: [recipient],
} as Message;
const result = getElementSenders(message, false, true);
const expected: Recipient[] = [recipient];
expect(result).toEqual(expected);
});
it('should give the senders of a conversation', () => {
const conversation = {
Senders: [sender],
} as Conversation;
const result = getElementSenders(conversation, true, false);
const expected: Recipient[] = [sender];
expect(result).toEqual(expected);
});
it('should give the recipients of a conversation', () => {
const conversation = {
Senders: [sender],
Recipients: [recipient],
} as Conversation;
const result = getElementSenders(conversation, true, true);
const expected: Recipient[] = [recipient];
expect(result).toEqual(expected);
});
});
|
3,823 | 0 | petrpan-code/ProtonMail/WebClients/applications/mail/src/app | petrpan-code/ProtonMail/WebClients/applications/mail/src/app/helpers/schedule.test.ts | import { getMinScheduleTime } from './schedule';
describe('getMinScheduleTime', () => {
afterEach(() => {
jest.useRealTimers();
});
it('should get the correct min scheduled time if selected date is not today', () => {
const fakeNow = new Date(2021, 0, 1, 9, 20, 0);
jest.useFakeTimers().setSystemTime(fakeNow.getTime());
// Date which is currently selected is not today
const date = new Date(2021, 0, 5, 9, 20, 0);
const minTimeDate = getMinScheduleTime(date);
// We expect the function to return undefined because if not today,
// there is no min time (we want the whole interval from 00:00 to 23:30)
const expectedMinTimeDate = undefined;
expect(minTimeDate).toEqual(expectedMinTimeDate);
});
it('should get the correct min scheduled time if time < XX:30 and still in 2 minutes limit', () => {
const fakeNow = new Date(2021, 0, 1, 9, 20, 0);
jest.useFakeTimers().setSystemTime(fakeNow.getTime());
const minTimeDate = getMinScheduleTime(fakeNow);
const expectedMinTimeDate = new Date(2021, 0, 1, 9, 30, 0);
expect(minTimeDate).toEqual(expectedMinTimeDate);
});
it('should get the correct min scheduled time if time < XX:30 and not in 2 minutes limit', () => {
const fakeNow = new Date(2021, 0, 1, 9, 28, 30);
jest.useFakeTimers().setSystemTime(fakeNow.getTime());
const minTimeDate = getMinScheduleTime(fakeNow);
// We cannot schedule a message within the next 2 minutes, so if it's 9:28, we should return 10:00
const expectedMinTimeDate = new Date(2021, 0, 1, 10, 0, 0);
expect(minTimeDate).toEqual(expectedMinTimeDate);
});
it('should get the correct min scheduled time if time > XX:30 and still in 2 minutes limit', () => {
const fakeNow = new Date(2021, 0, 1, 9, 55, 0);
jest.useFakeTimers().setSystemTime(fakeNow.getTime());
const minTimeDate = getMinScheduleTime(fakeNow);
const expectedMinTimeDate = new Date(2021, 0, 1, 10, 0, 0);
expect(minTimeDate).toEqual(expectedMinTimeDate);
});
it('should get the correct min scheduled time if time > XX:30 and not in 2 minutes limit', () => {
const fakeNow = new Date(2021, 0, 1, 9, 58, 30);
jest.useFakeTimers().setSystemTime(fakeNow.getTime());
const minTimeDate = getMinScheduleTime(fakeNow);
// We cannot schedule a message within the next 2 minutes, so if it's 9:58, we should return 10:30
const expectedMinTimeDate = new Date(2021, 0, 1, 10, 30, 0);
expect(minTimeDate).toEqual(expectedMinTimeDate);
});
});
|
3,825 | 0 | petrpan-code/ProtonMail/WebClients/applications/mail/src/app | petrpan-code/ProtonMail/WebClients/applications/mail/src/app/helpers/sidebar.test.ts | import { FolderWithSubFolders } from '@proton/shared/lib/interfaces/Folder';
import { UnreadCounts } from '../components/sidebar/MailSidebarList';
import { getUnreadCount } from './sidebar';
const EXPANDED = 1;
const COLLAPSED = 0;
describe('getUnreadCount', () => {
const counterMap = { A: 3, B: 1, C: 2, D: 0 } as UnreadCounts;
const folder = {
ID: 'A',
Expanded: EXPANDED,
subfolders: [
{
ID: 'B',
Expanded: EXPANDED,
subfolders: [
{
ID: 'C',
Expanded: EXPANDED,
subfolders: [
{
ID: 'D',
Expanded: EXPANDED,
} as FolderWithSubFolders,
],
} as FolderWithSubFolders,
],
} as FolderWithSubFolders,
],
} as FolderWithSubFolders;
it('should accumulate unread total when collapsed', () => {
expect(getUnreadCount(counterMap, { ...folder, Expanded: COLLAPSED })).toEqual(6);
});
it('should display display individual unreal total', () => {
expect(getUnreadCount(counterMap, folder)).toEqual(3);
});
});
|
3,827 | 0 | petrpan-code/ProtonMail/WebClients/applications/mail/src/app | petrpan-code/ProtonMail/WebClients/applications/mail/src/app/helpers/string.test.ts | import { extractChevrons, htmlEntities, replaceLineBreaks, toUnsignedString, ucFirst } from './string';
describe('toUnsignedString', () => {
it('should convert integer to unsigned string', () => {
const value = 1000;
const result = toUnsignedString(value, 1);
expect(result).not.toContain('-');
expect(result.length).toEqual(10);
expect(result).toEqual('1111101000');
});
});
describe('ucFirst', () => {
it('should uppercase the first character in a string', () => {
const string = 'hello welcome at Proton';
const expected = 'Hello welcome at Proton';
expect(ucFirst(string)).toEqual(expected);
});
});
describe('extractChevrons', () => {
it('should extract chevrons from string', () => {
const string1 = '<[email protected]>';
const string2 = 'Address <[email protected]>';
const string3 = 'no chevrons here';
expect(extractChevrons(string1)).toEqual('[email protected]');
expect(extractChevrons(string2)).toEqual('[email protected]');
expect(extractChevrons(string3)).toEqual('');
});
});
describe('htmlEntities', () => {
it('should add HTML entities in string', () => {
const string = 'chevrons=<> and=& quote=" rest should be okay#@!$%^*()_-';
const expected = 'chevrons=<> and=& quote=" rest should be okay#@!$%^*()_-';
expect(htmlEntities(string)).toEqual(expected);
});
});
describe('replaceLineBreaks', () => {
it('should replace line breaks from string', () => {
const string = `<div>Hello\nHow\rare\r\nyou?</div>`;
const expected = `<div>Hello<br />How<br />are<br />you?</div>`;
expect(replaceLineBreaks(string)).toEqual(expected);
});
});
|
3,829 | 0 | petrpan-code/ProtonMail/WebClients/applications/mail/src/app | petrpan-code/ProtonMail/WebClients/applications/mail/src/app/helpers/textToHtml.test.ts | import { MailSettings } from '@proton/shared/lib/interfaces';
import { textToHtml } from './textToHtml';
describe('textToHtml', () => {
it('should convert simple string from plain text to html', () => {
expect(textToHtml('This a simple string', '', undefined, undefined)).toEqual('This a simple string');
});
it('should convert multiline string too', () => {
const html = textToHtml(
`Hello
this is a multiline string`,
'',
undefined,
undefined
);
expect(html).toEqual(`Hello<br>
this is a multiline string`);
});
it('Multi line', () => {
// Add a little
const html = textToHtml(
`a title
## hello
this is a multiline string`,
'<p>My signature</p>',
{
Signature: '<p>My signature</p>',
FontSize: 16,
FontFace: 'Arial',
} as MailSettings,
undefined
);
expect(html).toEqual(`a title<br>
## hello<br>
this is a multiline string`);
});
it('should not convert markdown line headings ', () => {
/**
* Here the "--" represents a h2 title in markdown
*/
const html = textToHtml(
`a title
--
this is a multiline string`,
'',
undefined,
undefined
);
expect(html).toEqual(`a title<br>
--<br>
this is a multiline string`);
});
});
|
3,832 | 0 | petrpan-code/ProtonMail/WebClients/applications/mail/src/app | petrpan-code/ProtonMail/WebClients/applications/mail/src/app/helpers/url.test.ts | import { protonizer } from '@proton/shared/lib/sanitize';
import { removeLineBreaks } from './test/message';
import { mailtoParser, toAddresses } from './url';
const address1 = '[email protected]';
const address2 = '[email protected]';
const address3 = '[email protected]';
const address4 = '[email protected]';
const addressName1 = 'Address1';
const addressName2 = 'Address2';
const htmlEntity = '%C2%AD'; // Test when mailto contains HTML entity "­"
const subject = 'Mail subject';
const body = 'Mail body';
const bodyWithImages = `<div>
Body of the email
<img src="imageUrl" style="width:auto;">
</div>`;
describe('toAddresses', () => {
it('should split an addresses string to a list of recipients', function () {
const inputString1 = `${address1}, ${address2}`;
const inputString2 = `${addressName1} <${address1}>`;
const expectedResult1 = [
{ Name: address1, Address: address1 },
{ Name: address2, Address: address2 },
];
const expectedResult2 = [{ Name: addressName1, Address: address1 }];
expect(toAddresses(inputString1)).toEqual(expectedResult1);
expect(toAddresses(inputString2)).toEqual(expectedResult2);
});
});
describe('mailtoParser', () => {
it.each`
toList | expectedToList
${address1} | ${[{ Name: address1, Address: address1 }]}
${`${address1},${address2}`} | ${[{ Name: address1, Address: address1 }, { Name: address2, Address: address2 }]}
${`${addressName1} <${address1}>`} | ${[{ Name: addressName1, Address: address1 }]}
${`${addressName1} <${address1}>, ${addressName2} <${address2}>`} | ${[{ Name: addressName1, Address: address1 }, { Name: addressName2, Address: address2 }]}
${`address${htmlEntity}[email protected]`} | ${[{ Name: address1, Address: address1 }]}
`('should detect the TO list in a mailto string with TO = $toList', ({ toList, expectedToList }) => {
const mailto = `mailto:${toList}?subject=${subject}`;
const { data } = mailtoParser(mailto);
expect(data?.ToList).toEqual(expectedToList);
});
it.each`
ccList | expectedCCList
${address1} | ${[{ Name: address1, Address: address1 }]}
${`${address1},${address2}`} | ${[{ Name: address1, Address: address1 }, { Name: address2, Address: address2 }]}
${`${addressName1} <${address1}>`} | ${[{ Name: addressName1, Address: address1 }]}
${`${addressName1} <${address1}>, ${addressName2} <${address2}>`} | ${[{ Name: addressName1, Address: address1 }, { Name: addressName2, Address: address2 }]}
${`address${htmlEntity}[email protected]`} | ${[{ Name: address1, Address: address1 }]}
`('should detect the CC list in a mailto string with CC = $ccList', ({ ccList, expectedCCList }) => {
const mailto = `mailto:${address3}?subject=${subject}&cc=${ccList}`;
const { data } = mailtoParser(mailto);
expect(data?.CCList).toEqual(expectedCCList);
});
it.each`
bccList | expectedBCCList
${address1} | ${[{ Name: address1, Address: address1 }]}
${`${address1},${address2}`} | ${[{ Name: address1, Address: address1 }, { Name: address2, Address: address2 }]}
${`${addressName1} <${address1}>`} | ${[{ Name: addressName1, Address: address1 }]}
${`${addressName1} <${address1}>, ${addressName2} <${address2}>`} | ${[{ Name: addressName1, Address: address1 }, { Name: addressName2, Address: address2 }]}
${`address${htmlEntity}[email protected]`} | ${[{ Name: address1, Address: address1 }]}
`('should detect the BCC list in a mailto string with BCC = $bccList', ({ bccList, expectedBCCList }) => {
const mailto = `mailto:${address3}?subject=${subject}&bcc=${bccList}`;
const { data } = mailtoParser(mailto);
expect(data?.BCCList).toEqual(expectedBCCList);
});
it('should detect the subject in a mailto string', () => {
const mailto = `mailto:${address1}?subject=${subject}`;
const { data } = mailtoParser(mailto);
expect(data?.Subject).toEqual(subject);
});
it.each`
messageBody
${body}
${bodyWithImages}
`('should detect the body in a mailto string with Subject = $messagebody', ({ messageBody }) => {
const mailto = `mailto:${address1}?subject=${subject}&body=${messageBody}`;
const { decryption } = mailtoParser(mailto);
const decodedBody = decodeURIComponent(protonizer(messageBody, true).innerHTML);
expect(removeLineBreaks(decryption?.decryptedBody || '')).toEqual(removeLineBreaks(decodedBody));
});
it('should detect all fields in a mailto string', () => {
const mailto = `mailto:${address1}?subject=${subject}&cc=${address2},${address3}&bcc=${address4}&body=${body}`;
const { data, decryption } = mailtoParser(mailto);
const decodedBody = decodeURIComponent(protonizer(body, true).innerHTML);
expect(data?.ToList).toEqual([{ Name: address1, Address: address1 }]);
expect(data?.Subject).toEqual(subject);
expect(data?.CCList).toEqual([
{ Name: address2, Address: address2 },
{ Name: address3, Address: address3 },
]);
expect(data?.BCCList).toEqual([{ Name: address4, Address: address4 }]);
expect(removeLineBreaks(decryption?.decryptedBody || '')).toEqual(removeLineBreaks(decodedBody));
});
});
|
3,841 | 0 | petrpan-code/ProtonMail/WebClients/applications/mail/src/app/helpers/attachment | petrpan-code/ProtonMail/WebClients/applications/mail/src/app/helpers/attachment/test/attachmentConverter.test.ts | import { MIMEAttachment, WorkerDecryptionResult } from '@proton/crypto';
import { stringToUint8Array } from '@proton/shared/lib/helpers/encoding';
import { Message } from '@proton/shared/lib/interfaces/mail/Message';
import { ATTACHMENT_DISPOSITION } from '@proton/shared/lib/mail/constants';
import { ENCRYPTED_STATUS } from '../../../constants';
import { ID_PREFIX, convert, convertSingle, convertToFile, getHeaders, getId } from '../attachmentConverter';
const fileName = 'fileName';
const messageID = 'messageID';
const contentID = 'contentID';
const contentDisposition = ATTACHMENT_DISPOSITION.INLINE;
const message = { ID: messageID } as Message;
const originalHeaders = {
'content-id': [contentID],
};
const attachmentSize = 222;
const mimeAttachment = {
contentId: contentID,
fileName,
contentDisposition,
contentType: '',
headers: originalHeaders,
size: attachmentSize,
content: stringToUint8Array('content'),
} as MIMEAttachment;
describe('getId', () => {
it('should return the expected attachment ID', function () {
const number = 1;
const parsedAttachment = { contentId: contentID } as MIMEAttachment;
const expected = `${ID_PREFIX}_${messageID}_${contentID}_${number}`;
expect(getId(message, parsedAttachment, number)).toEqual(expected);
});
});
describe('getHeaders', () => {
it('should return attachment headers', () => {
const expected = {
'content-disposition': `${contentDisposition}; filename="${fileName}"`,
'content-id': contentID,
'content-type': `; filename="${fileName}"`,
embedded: 1,
};
expect(getHeaders(mimeAttachment)).toEqual(expected);
});
});
describe('convertSingle', () => {
it('should convert a single parsed attachment to an attachment', () => {
const spy = jest.fn((ID: string, attachment: WorkerDecryptionResult<Uint8Array>) => {
console.log(ID, attachment);
});
const attachment = convertSingle(message, mimeAttachment, 1, 0, spy);
const expectedAttachment = {
Encrypted: ENCRYPTED_STATUS.PGP_MIME,
ID: getId(message, mimeAttachment, 1),
Headers: {
'content-disposition': `${contentDisposition}; filename="${fileName}"`,
'content-id': contentID,
'content-type': `; filename="${fileName}"`,
embedded: 1,
},
Name: fileName,
KeyPackets: null,
MIMEType: '',
Size: attachmentSize,
};
expect(attachment).toEqual(expectedAttachment);
expect(spy).toHaveBeenCalled();
});
});
describe('convert', () => {
it('should convert multiple parsed attachments to attachment', function () {
const spy = jest.fn((ID: string, attachment: WorkerDecryptionResult<Uint8Array>) => {
console.log(ID, attachment);
});
const mimeAttachment2 = {
contentId: `${contentID}-2`,
fileName: `${fileName}-2`,
contentDisposition,
contentType: '',
headers: originalHeaders,
size: attachmentSize,
content: stringToUint8Array('content-2'),
} as MIMEAttachment;
const attachments = convert(message, [mimeAttachment, mimeAttachment2], 0, spy);
const expectedAttachments = [
{
Encrypted: ENCRYPTED_STATUS.PGP_MIME,
ID: getId(message, mimeAttachment, 0),
Headers: {
'content-disposition': `${contentDisposition}; filename="${fileName}"`,
'content-id': contentID,
'content-type': `; filename="${fileName}"`,
embedded: 1,
},
Name: fileName,
KeyPackets: null,
MIMEType: '',
Size: attachmentSize,
},
{
Encrypted: ENCRYPTED_STATUS.PGP_MIME,
ID: getId(message, mimeAttachment2, 1),
Headers: {
'content-disposition': `${contentDisposition}; filename="${fileName}-2"`,
'content-id': contentID,
'content-type': `; filename="${fileName}-2"`,
embedded: 1,
},
Name: `${fileName}-2`,
KeyPackets: null,
MIMEType: '',
Size: attachmentSize,
},
];
expect(attachments).toEqual(expectedAttachments);
expect(spy).toHaveBeenCalledTimes(2);
});
});
describe('convertToFile', () => {
it('should return normal attachments and convert to file pgp attachments', () => {
const spy = jest.fn((ID: string) => {
return {
filename: 'attachment-2',
verified: 1,
data: stringToUint8Array(`content-${ID}`),
signatures: [stringToUint8Array(`content-${ID}`)],
} as WorkerDecryptionResult<Uint8Array>;
});
const attachments = [
{ ID: 'attachment-1' },
{
ID: `${ID_PREFIX}-attachment-2`,
Name: 'attachment-2',
MIMEType: 'attachment',
},
];
const expected = [{ ID: 'attachment-1' }];
const result = convertToFile(attachments, spy);
expect(result[0]).toEqual(expected);
expect(result[1][0].name).toEqual('attachment-2');
});
});
|
3,842 | 0 | petrpan-code/ProtonMail/WebClients/applications/mail/src/app/helpers/attachment | petrpan-code/ProtonMail/WebClients/applications/mail/src/app/helpers/attachment/test/attachmentDownloader.test.ts | import { encodeBase64 } from '@proton/crypto/lib/utils';
import * as browser from '@proton/shared/lib/helpers/browser';
import * as downloadFile from '@proton/shared/lib/helpers/downloadFile';
import { stringToUint8Array } from '@proton/shared/lib/helpers/encoding';
import { Attachment } from '@proton/shared/lib/interfaces/mail/Message';
import { VERIFICATION_STATUS } from '@proton/shared/lib/mail/constants';
import { MessageKeys, MessageVerification } from '../../../logic/messages/messagesTypes';
import { api } from '../../test/api';
import { GeneratedKey, generateKeys, releaseCryptoProxy, setupCryptoProxyForTesting } from '../../test/crypto';
import {
Download,
formatDownload,
formatDownloadAll,
generateDownload,
generateDownloadAll,
getZipAttachmentName,
} from '../attachmentDownloader';
const subject = 'Message subject';
const message = { Subject: subject };
const me = '[email protected]';
const attachmentName = 'Attachment Name';
const attachment1 = {
ID: '1',
Name: attachmentName,
Preview: stringToUint8Array('message preview'),
KeyPackets: encodeBase64('keypackets'),
} as Attachment;
const verification = {} as MessageVerification;
const getAttachment = jest.fn();
const onUpdateAttachment = jest.fn();
describe('formatDownload', () => {
let toKeys: GeneratedKey;
let messageKeys: MessageKeys;
beforeAll(async () => {
await setupCryptoProxyForTesting();
toKeys = await generateKeys('me', me);
messageKeys = {
type: 'publicPrivate',
publicKeys: toKeys.publicKeys,
privateKeys: toKeys.privateKeys,
};
});
afterAll(async () => {
await releaseCryptoProxy();
});
it('should format download', async () => {
const result = await formatDownload(
attachment1,
verification,
messageKeys,
api,
getAttachment,
onUpdateAttachment
);
expect(result.data).toBeDefined();
expect(result.attachment).toEqual(attachment1);
expect(result.verified).toEqual(VERIFICATION_STATUS.NOT_SIGNED);
});
it('should return an error while formatting download when attachment is broken', async () => {
const verificationWithError = {
verificationErrors: [{ message: 'there is an issue' }],
} as MessageVerification;
const result = await formatDownload(
{ ...attachment1, Preview: undefined },
verificationWithError,
messageKeys,
api,
getAttachment,
onUpdateAttachment
);
const expectedAttachment = {
Name: `${attachmentName}.pgp`,
MIMEType: 'application/pgp-encrypted',
ID: '1',
};
expect(result.attachment).toEqual(expectedAttachment);
expect(result.isError).toBeTruthy();
expect(result.verified).toEqual(VERIFICATION_STATUS.NOT_VERIFIED);
});
});
describe('generateDownload', () => {
afterEach(() => {
jest.clearAllMocks();
});
it('should generate a download', async () => {
const downloadFileSpy = jest.spyOn(downloadFile, 'default').mockReturnValue();
const download = {
attachment: {
Name: 'attachment1',
},
data: stringToUint8Array('download 1 data'),
verified: 1,
} as Download;
await generateDownload(download);
const downloadAll = downloadFileSpy.mock.calls[0];
expect(downloadFileSpy).toHaveBeenCalled();
// Check that the spy has been called with a blob of type zip and the correct filename
expect(downloadAll[1]).toEqual('attachment1');
});
it('should generate a download with the correct mimeType for firefox', async () => {
const downloadFileSpy = jest.spyOn(downloadFile, 'default').mockReturnValue();
jest.spyOn(browser, 'isFirefox').mockReturnValue(true);
const download = {
attachment: {
Name: 'attachment1',
},
data: stringToUint8Array('download 1 data'),
verified: 1,
} as Download;
await generateDownload(download);
const downloadAll = downloadFileSpy.mock.calls[0];
expect(downloadFileSpy).toHaveBeenCalled();
// Check that the spy has been called with a blob of type zip and the correct filename
expect(downloadAll[0]?.type).toEqual('application/octet-stream');
expect(downloadAll[1]).toEqual('attachment1');
});
});
describe('formatDownloadALl', () => {
let toKeys: GeneratedKey;
let messageKeys: MessageKeys;
beforeAll(async () => {
await setupCryptoProxyForTesting();
toKeys = await generateKeys('me', me);
messageKeys = {
type: 'publicPrivate',
publicKeys: toKeys.publicKeys,
privateKeys: toKeys.privateKeys,
};
});
afterAll(async () => {
await releaseCryptoProxy();
});
it('should format download all', async () => {
const result = await formatDownloadAll(
[attachment1],
verification,
messageKeys,
onUpdateAttachment,
api,
getAttachment
);
expect(result[0]?.data).toBeDefined();
expect(result[0]?.attachment).toEqual(attachment1);
expect(result[0]?.verified).toEqual(VERIFICATION_STATUS.NOT_SIGNED);
});
});
describe('getZipAttachmentName', () => {
it('should generate a zip name for attachments', () => {
expect(getZipAttachmentName(message)).toEqual(`Attachments-${subject}.zip`);
});
});
describe('generateDownloadAll', () => {
afterEach(() => {
jest.clearAllMocks();
});
it('should generate a download all', async () => {
const downloadFileSpy = jest.spyOn(downloadFile, 'default').mockReturnValue();
const downloads = [
{
attachment: {
Name: 'attachment1',
},
data: stringToUint8Array('download 1 data'),
verified: 1,
} as Download,
{
attachment: {
Name: 'attachment2',
},
data: stringToUint8Array('download 2 data'),
verified: 1,
} as Download,
];
await generateDownloadAll(message, downloads);
const downloadAll = downloadFileSpy.mock.calls[0];
expect(downloadFileSpy).toHaveBeenCalled();
// Check that the spy has been called with a blob of type zip and the correct filename
expect(downloadAll[0]?.type).toEqual('application/zip');
expect(downloadAll[1]).toEqual(`Attachments-${subject}.zip`);
});
});
|
3,843 | 0 | petrpan-code/ProtonMail/WebClients/applications/mail/src/app/helpers/attachment | petrpan-code/ProtonMail/WebClients/applications/mail/src/app/helpers/attachment/test/attachmentLoader.test.ts | import { encodeBase64 } from '@proton/crypto/lib/utils';
import { stringToUint8Array } from '@proton/shared/lib/helpers/encoding';
import { Attachment } from '@proton/shared/lib/interfaces/mail/Message';
import { MessageKeys, MessageVerification } from '../../../logic/messages/messagesTypes';
import { addApiMock, api } from '../../test/api';
import { GeneratedKey, generateKeys, releaseCryptoProxy, setupCryptoProxyForTesting } from '../../test/crypto';
import { get, getAndVerify, getDecryptedAttachment, getRequest } from '../attachmentLoader';
const me = '[email protected]';
const attachmentID = 'attachmentID';
const attachmentName = 'attachmentName';
const attachmentMimeType = 'application/pdf';
const attachment1 = {
ID: attachmentID,
Name: attachmentName,
Preview: stringToUint8Array('message preview'),
KeyPackets: encodeBase64('keypackets'),
MIMEType: attachmentMimeType,
} as Attachment;
const outsideMessageKeys = {
type: 'outside',
password: 'password',
id: 'id',
decryptedToken: 'token',
} as MessageKeys;
// TODO Test decrypt function
describe('getRequest', () => {
let toKeys: GeneratedKey;
let messageKeys: MessageKeys;
beforeAll(async () => {
await setupCryptoProxyForTesting();
toKeys = await generateKeys('me', me);
messageKeys = {
type: 'publicPrivate',
publicKeys: toKeys.publicKeys,
privateKeys: toKeys.privateKeys,
};
});
afterAll(async () => {
await releaseCryptoProxy();
});
it('should make an api request for a normal attachment', async () => {
const spy = jest.fn();
addApiMock(`mail/v4/attachments/${attachmentID}`, spy, 'get');
await getRequest({ ID: attachmentID }, api, messageKeys);
expect(spy).toHaveBeenCalled();
});
it('should make an api request for a EO attachment', async () => {
const spy = jest.fn();
addApiMock(`mail/v4/eo/attachment/${attachmentID}`, spy, 'get');
await getRequest({ ID: attachmentID }, api, outsideMessageKeys);
expect(spy).toHaveBeenCalled();
});
});
describe('getDecryptedAttachment', () => {
let toKeys: GeneratedKey;
let messageKeys: MessageKeys;
beforeAll(async () => {
await setupCryptoProxyForTesting();
toKeys = await generateKeys('me', me);
messageKeys = {
type: 'publicPrivate',
publicKeys: toKeys.publicKeys,
privateKeys: toKeys.privateKeys,
};
});
afterAll(async () => {
await releaseCryptoProxy();
});
// TODO Need to test case where we get the decrypted attachment, for normal and EO attachments
it('should throw an error when the attachment is broken', async () => {
addApiMock(`mail/v4/attachments/${attachmentID}`, jest.fn(), 'get');
const verificationWithError = {
verificationErrors: [{ message: 'there is an issue' }],
} as MessageVerification;
const result = getDecryptedAttachment(attachment1, verificationWithError, messageKeys, api);
expect(result).rejects.toThrow('Attachment decryption error');
});
});
describe('getAndVerify', () => {
let toKeys: GeneratedKey;
let messageKeys: MessageKeys;
const getAttachment = jest.fn();
const onUpdateAttachment = jest.fn();
beforeAll(async () => {
await setupCryptoProxyForTesting();
toKeys = await generateKeys('me', me);
messageKeys = {
type: 'publicPrivate',
publicKeys: toKeys.publicKeys,
privateKeys: toKeys.privateKeys,
};
});
afterAll(async () => {
await releaseCryptoProxy();
});
it('should return the attachment Preview', async () => {
const result = await getAndVerify(
attachment1,
{} as MessageVerification,
messageKeys,
api,
getAttachment,
onUpdateAttachment
);
expect(result.filename).toEqual('preview');
});
// TODO need to test case where we can get the attachment, for normal and EO attachments
});
describe('get + reverify', () => {
let toKeys: GeneratedKey;
let messageKeys: MessageKeys;
const getAttachment = jest.fn();
const onUpdateAttachment = jest.fn();
beforeAll(async () => {
await setupCryptoProxyForTesting();
toKeys = await generateKeys('me', me);
messageKeys = {
type: 'publicPrivate',
publicKeys: toKeys.publicKeys,
privateKeys: toKeys.privateKeys,
};
});
afterAll(async () => {
await releaseCryptoProxy();
});
it('should get the attachment', async () => {
const getResult = await get(
attachment1,
{} as MessageVerification,
messageKeys,
api,
getAttachment,
onUpdateAttachment
);
expect(getResult.filename).toEqual('preview');
});
});
|
3,844 | 0 | petrpan-code/ProtonMail/WebClients/applications/mail/src/app/helpers/attachment | petrpan-code/ProtonMail/WebClients/applications/mail/src/app/helpers/attachment/test/attachmentThumbnails.test.ts | import { MAILBOX_LABEL_IDS, MIME_TYPES } from '@proton/shared/lib/constants';
import { AttachmentsMetadata, Message } from '@proton/shared/lib/interfaces/mail/Message';
import {
canShowAttachmentThumbnails,
filterAttachmentToPreview,
getOtherAttachmentsTitle,
} from 'proton-mail/helpers/attachment/attachmentThumbnails';
import { Conversation } from 'proton-mail/models/conversation';
const { SPAM, INBOX } = MAILBOX_LABEL_IDS;
const getConversation = (isSpam = false) => {
return {
AttachmentsMetadata: [
{ ID: '1' } as AttachmentsMetadata,
{ ID: '2' } as AttachmentsMetadata,
] as AttachmentsMetadata[],
Labels: isSpam ? [{ ID: SPAM }] : [{ ID: INBOX }],
} as Conversation;
};
const getMessage = (isSpam = false) => {
return {
AttachmentsMetadata: [
{ ID: '1' } as AttachmentsMetadata,
{ ID: '2' } as AttachmentsMetadata,
] as AttachmentsMetadata[],
LabelIDs: isSpam ? [SPAM] : [INBOX],
ConversationID: 'conversationID',
} as Message;
};
const attachmentsMetadata = [{ ID: '1' } as AttachmentsMetadata];
describe('attachmentThumbnails', () => {
describe('canShowAttachmentThumbnails', () => {
it('should show attachment thumbnails', () => {
expect(canShowAttachmentThumbnails(false, getConversation(), attachmentsMetadata, true)).toBeTruthy();
expect(canShowAttachmentThumbnails(false, getMessage(), attachmentsMetadata, true)).toBeTruthy();
});
it('should not show attachment thumbnails when feature flag is off', () => {
expect(canShowAttachmentThumbnails(false, getConversation(), attachmentsMetadata, false)).toBeFalsy();
expect(canShowAttachmentThumbnails(false, getMessage(), attachmentsMetadata, false)).toBeFalsy();
});
it('should not show attachment thumbnails on compact view', () => {
expect(canShowAttachmentThumbnails(true, getConversation(), attachmentsMetadata, true)).toBeFalsy();
expect(canShowAttachmentThumbnails(true, getMessage(), attachmentsMetadata, true)).toBeFalsy();
});
it('should not show attachment thumbnails when no attachment metadata is attached to the element', () => {
expect(canShowAttachmentThumbnails(false, {} as Conversation, [], true)).toBeFalsy();
expect(canShowAttachmentThumbnails(false, {} as Message, [], true)).toBeFalsy();
});
it('should not show attachment thumbnails when element is in SPAM', () => {
expect(canShowAttachmentThumbnails(false, getConversation(true), attachmentsMetadata, true)).toBeFalsy();
expect(canShowAttachmentThumbnails(false, getMessage(true), attachmentsMetadata, true)).toBeFalsy();
});
});
describe('getOtherAttachmentsTitle', () => {
const attachmentMetadata = [
{ ID: '1', Name: 'attachment1.png' } as AttachmentsMetadata,
{ ID: '2', Name: 'attachment2.jpg' } as AttachmentsMetadata,
{ ID: '3', Name: 'attachment3.pdf' } as AttachmentsMetadata,
{ ID: '4', Name: 'attachment4.txt' } as AttachmentsMetadata,
] as AttachmentsMetadata[];
it('should return the expected title', () => {
const res = getOtherAttachmentsTitle(attachmentMetadata, 2);
expect(res).toEqual('attachment3.pdf, attachment4.txt');
});
});
describe('filterAttachmentToPreview', () => {
it('should filter attachments correctly', () => {
const pdfAttachment = {
MIMEType: 'application/pdf',
} as AttachmentsMetadata;
const imageAttachment = {
MIMEType: 'image/png',
} as AttachmentsMetadata;
const attachmentsMetada: AttachmentsMetadata[] = [
{ MIMEType: MIME_TYPES.ICS } as AttachmentsMetadata,
{ MIMEType: MIME_TYPES.APPLICATION_ICS } as AttachmentsMetadata,
{ MIMEType: MIME_TYPES.PGP_KEYS } as AttachmentsMetadata,
{ MIMEType: 'whatever', Name: 'attachment.ics' } as AttachmentsMetadata,
{ MIMEType: 'whatever', Name: 'attachment.ical' } as AttachmentsMetadata,
{ MIMEType: 'whatever', Name: 'attachment.ifb' } as AttachmentsMetadata,
{ MIMEType: 'whatever', Name: 'attachment.icalendar' } as AttachmentsMetadata,
{ MIMEType: 'whatever', Name: 'attachment.asc' } as AttachmentsMetadata,
pdfAttachment,
imageAttachment,
];
const expected: AttachmentsMetadata[] = [pdfAttachment, imageAttachment];
expect(filterAttachmentToPreview(attachmentsMetada)).toEqual(expected);
});
});
});
|
3,845 | 0 | petrpan-code/ProtonMail/WebClients/applications/mail/src/app/helpers/attachment | petrpan-code/ProtonMail/WebClients/applications/mail/src/app/helpers/attachment/test/attachments.test.ts | import { Attachment } from '@proton/shared/lib/interfaces/mail/Message';
import { ATTACHMENT_DISPOSITION } from '@proton/shared/lib/mail/constants';
import { MessageState } from '../../../logic/messages/messagesTypes';
import { getPureAttachments, updateKeyPackets } from '../attachment';
describe('updateKeyPackets', () => {
const attachments = [
{
ID: 'attachment-1',
KeyPackets: 'random-key-packet-1',
},
];
const modelMessage = {
localID: 'modelMessage',
data: {
Attachments: attachments,
},
} as MessageState;
it('should update attachment key packets', () => {
const expectedAttachments = [
{
ID: 'attachment-1',
KeyPackets: 'different-key-packet',
},
];
const syncedMessage = {
localID: 'syncedMessage',
data: {
Attachments: expectedAttachments,
},
} as MessageState;
const { changed, Attachments } = updateKeyPackets(modelMessage, syncedMessage);
expect(changed).toBeTruthy();
expect(Attachments).toEqual(expectedAttachments);
});
it('should not update KeyPackets when attachments are up to date', function () {
const { changed, Attachments } = updateKeyPackets(modelMessage, modelMessage);
expect(changed).toBeFalsy();
expect(Attachments).toEqual(attachments);
});
});
describe('getPureAttachments', () => {
const attachments = [
{
Name: 'normal attachment',
Headers: {
'content-disposition': ATTACHMENT_DISPOSITION.ATTACHMENT,
},
} as Attachment,
{
Name: 'invalid inline image',
Headers: {
'content-disposition': ATTACHMENT_DISPOSITION.INLINE,
},
} as Attachment,
{
Name: 'inline image',
Headers: {
'content-disposition': ATTACHMENT_DISPOSITION.INLINE,
'content-id': 'content-id',
},
} as Attachment,
] as Attachment[];
it('should return all attachments when embedded images must displayed', () => {
expect(getPureAttachments(attachments, false)).toEqual(attachments);
});
it('should return only pure attachments when embedded images are hidden', () => {
expect(getPureAttachments(attachments, true)).toEqual([...attachments.slice(0, 2)]);
});
});
|
3,847 | 0 | petrpan-code/ProtonMail/WebClients/applications/mail/src/app/helpers | petrpan-code/ProtonMail/WebClients/applications/mail/src/app/helpers/calendar/invite.test.ts | import { generateAttendeeToken } from '@proton/shared/lib/calendar/attendees';
import { ICAL_ATTENDEE_RSVP, ICAL_ATTENDEE_STATUS, ICAL_METHOD } from '@proton/shared/lib/calendar/constants';
import { generateVeventHashUID } from '@proton/shared/lib/calendar/helper';
import {
EVENT_INVITATION_ERROR_TYPE,
EventInvitationError,
} from '@proton/shared/lib/calendar/icsSurgery/EventInvitationError';
import { getIsRruleSupported } from '@proton/shared/lib/calendar/recurrence/rrule';
import { parse } from '@proton/shared/lib/calendar/vcal';
import { getIsTimezoneComponent } from '@proton/shared/lib/calendar/vcalHelper';
import { Recipient } from '@proton/shared/lib/interfaces';
import { Attendee, CalendarEvent, Participant } from '@proton/shared/lib/interfaces/calendar';
import { VcalVcalendar, VcalVeventComponent } from '@proton/shared/lib/interfaces/calendar/VcalModel';
import { Message } from '@proton/shared/lib/interfaces/mail/Message';
import { RequireSome } from '@proton/shared/lib/interfaces/utils';
import { MessageStateWithData } from 'proton-mail/logic/messages/messagesTypes';
import { releaseCryptoProxy, setupCryptoProxyForTesting } from '../test/crypto';
import { EventInvitation, getIsPartyCrasher, getSupportedEventInvitation, parseVcalendar } from './invite';
describe('Invitations', () => {
beforeAll(async () => {
await setupCryptoProxyForTesting();
});
afterAll(async () => {
await releaseCryptoProxy();
});
describe('getIsRruleSupported for invitations', () => {
test('should accept events with daily recurring rules valid for invitations', () => {
const vevents = [
`BEGIN:VEVENT\r\nRRULE:FREQ=DAILY;UNTIL=20200330T150000Z;INTERVAL=100;BYMONTH=3\r\nEND:VEVENT`,
`BEGIN:VEVENT\r\nRRULE:FREQ=DAILY;INTERVAL=2;BYSECOND=30;BYMINUTE=5,10,15;BYHOUR=10\r\nEND:VEVENT`,
`BEGIN:VEVENT\r\nRRULE:FREQ=DAILY;INTERVAL=2;BYWEEKNO=13;COUNT=499;WKST=TH\r\nEND:VEVENT`,
];
const rrules = vevents.map((vevent) => {
const parsedVevent = parse(vevent) as RequireSome<VcalVeventComponent, 'rrule'>;
return parsedVevent.rrule.value;
});
expect(rrules.map((rrule) => getIsRruleSupported(rrule, true))).toEqual(vevents.map(() => true));
});
test('should refuse events with invalid daily recurring rules', () => {
const vevents = [
`BEGIN:VEVENT\r\nRRULE:FREQ=DAILY;COUNT=500\r\nEND:VEVENT`,
`BEGIN:VEVENT\r\nRRULE:FREQ=DAILY;INTERVAL=1000;BYMONTHDAY=11,22\r\nEND:VEVENT`,
];
const rrules = vevents.map((vevent) => {
const parsedVevent = parse(vevent) as RequireSome<VcalVeventComponent, 'rrule'>;
return parsedVevent.rrule.value;
});
expect(rrules.map((rrule) => getIsRruleSupported(rrule, true))).toEqual(vevents.map(() => false));
});
test('should accept events with yearly recurring rules valid for invitations', () => {
const vevents = [
`BEGIN:VEVENT\r\nRRULE:FREQ=YEARLY;UNTIL=20200330T150000Z;INTERVAL=1;BYDAY=MO,SU,TH;BYMONTHDAY=30,31;BYMONTH=3\r\nEND:VEVENT`,
`BEGIN:VEVENT\r\nRRULE:FREQ=YEARLY;INTERVAL=2;BYSECOND=30;BYHOUR=10;BYMONTH=5\r\nEND:VEVENT`,
`BEGIN:VEVENT\r\nRRULE:FREQ=YEARLY;INTERVAL=2;BYMONTH=3;BYMONTHDAY=17,22;COUNT=499\r\nEND:VEVENT`,
`BEGIN:VEVENT\r\nRRULE:FREQ=YEARLY;INTERVAL=1;BYDAY=2TU;BYMONTH=7\r\nEND:VEVENT`,
];
const rrules = vevents.map((vevent) => {
const parsedVevent = parse(vevent) as RequireSome<VcalVeventComponent, 'rrule'>;
return parsedVevent.rrule.value;
});
expect(rrules.map((rrule) => getIsRruleSupported(rrule, true))).toEqual(vevents.map(() => true));
});
test('should refuse events with invalid yearly recurring rules', () => {
const vevents = [
`BEGIN:VEVENT\r\nRRULE:FREQ=YEARLY;COUNT=500\r\nEND:VEVENT`,
`BEGIN:VEVENT\r\nRRULE:FREQ=YEARLY;INTERVAL=100;BYMONTHDAY=11,22\r\nEND:VEVENT`,
`BEGIN:VEVENT\r\nRRULE:FREQ=YEARLY;BYMONTHDAY=11\r\nEND:VEVENT`,
];
const rrules = vevents.map((vevent) => {
const parsedVevent = parse(vevent) as RequireSome<VcalVeventComponent, 'rrule'>;
return parsedVevent.rrule.value;
});
expect(rrules.map((rrule) => getIsRruleSupported(rrule, true))).toEqual(vevents.map(() => false));
});
});
describe('getSupportedEvent for invitations', () => {
test('should not import alarms for invites and keep recurrence id', async () => {
const invitation = `BEGIN:VCALENDAR
CALSCALE:GREGORIAN
VERSION:2.0
METHOD:REQUEST
PRODID:-//Apple Inc.//Mac OS X 10.13.6//EN
BEGIN:VTIMEZONE
TZID:/Europe/Vilnius
BEGIN:DAYLIGHT
TZOFFSETFROM:+0200
RRULE:FREQ=YEARLY;BYMONTH=3;BYDAY=-1SU
DTSTART:20030330T030000
TZNAME:EEST
TZOFFSETTO:+0300
END:DAYLIGHT
BEGIN:STANDARD
TZOFFSETFROM:+0300
RRULE:FREQ=YEARLY;BYMONTH=10;BYDAY=-1SU
DTSTART:20031026T040000
TZNAME:EET
TZOFFSETTO:+0200
END:STANDARD
END:VTIMEZONE
BEGIN:VEVENT
ATTENDEE;CUTYPE=INDIVIDUAL;EMAIL="[email protected]";PARTSTAT=NEED
S-ACTION;RSVP=TRUE:mailto:[email protected]
ATTENDEE;CN="testKrt";CUTYPE=INDIVIDUAL;EMAIL="[email protected]
m";PARTSTAT=ACCEPTED;ROLE=CHAIR:mailto:[email protected]
TRANSP:OPAQUE
UID:BA3017ED-889A-4BCB-B9CB-11CE30586021
DTSTAMP:20200821T081914Z
SEQUENCE:1
CREATED:20200821T081842Z
DTSTART;TZID=Europe/Vilnius:20200915T090000
DTEND;TZID=Europe/Vilnius:20200915T100000
TRANSP:OPAQUE
ORGANIZER;CN="testKrt":mailto:[email protected]
UID:BA3017ED-889A-4BCB-B9CB-11CE30586021
SUMMARY:Yearly single edit
RECURRENCE-ID;TZID=Europe/Vilnius:20220915T090000
BEGIN:VALARM
TRIGGER:-PT15H
ACTION:DISPLAY
END:VALARM
BEGIN:VALARM
TRIGGER:-PT1W2D
ACTION:EMAIL
END:VALARM
END:VEVENT
END:VCALENDAR`;
const parsedInvitation = parseVcalendar(invitation) as VcalVcalendar;
const message = { Time: Math.round(Date.now() / 1000) } as Message;
expect(
await getSupportedEventInvitation({
vcalComponent: parsedInvitation,
message,
icsBinaryString: invitation,
icsFileName: 'test.ics',
primaryTimezone: 'America/Sao_Paulo',
})
).toMatchObject({
method: 'REQUEST',
vevent: {
component: 'vevent',
uid: { value: 'BA3017ED-889A-4BCB-B9CB-11CE30586021' },
dtstamp: {
value: { year: 2020, month: 8, day: 21, hours: 8, minutes: 19, seconds: 14, isUTC: true },
},
dtstart: {
value: { year: 2020, month: 9, day: 15, hours: 9, minutes: 0, seconds: 0, isUTC: false },
parameters: { tzid: 'Europe/Vilnius' },
},
dtend: {
value: { year: 2020, month: 9, day: 15, hours: 10, minutes: 0, seconds: 0, isUTC: false },
parameters: { tzid: 'Europe/Vilnius' },
},
'recurrence-id': {
value: { year: 2022, month: 9, day: 15, hours: 9, minutes: 0, seconds: 0, isUTC: false },
parameters: { tzid: 'Europe/Vilnius' },
},
},
vtimezone: parsedInvitation.components?.find((component) => getIsTimezoneComponent(component)),
originalVcalInvitation: parsedInvitation,
originalUniqueIdentifier: 'BA3017ED-889A-4BCB-B9CB-11CE30586021',
hasMultipleVevents: false,
fileName: 'test.ics',
});
});
test('should refuse invitations with inconsistent custom yearly recurrence rules', async () => {
const invitation = `BEGIN:VCALENDAR
CALSCALE:GREGORIAN
VERSION:2.0
METHOD:REQUEST
PRODID:-//Apple Inc.//Mac OS X 10.13.6//EN
BEGIN:VTIMEZONE
TZID:Europe/Vilnius
BEGIN:DAYLIGHT
TZOFFSETFROM:+0200
RRULE:FREQ=YEARLY;BYMONTH=3;BYDAY=-1SU
DTSTART:20030330T030000
TZNAME:EEST
TZOFFSETTO:+0300
END:DAYLIGHT
BEGIN:STANDARD
TZOFFSETFROM:+0300
RRULE:FREQ=YEARLY;BYMONTH=10;BYDAY=-1SU
DTSTART:20031026T040000
TZNAME:EET
TZOFFSETTO:+0200
END:STANDARD
END:VTIMEZONE
BEGIN:VEVENT
ATTENDEE;CUTYPE=INDIVIDUAL;EMAIL="[email protected]";PARTSTAT=NEED
S-ACTION;RSVP=TRUE:mailto:[email protected]
ATTENDEE;CN="testKrt";CUTYPE=INDIVIDUAL;EMAIL="[email protected]
m";PARTSTAT=ACCEPTED;ROLE=CHAIR:mailto:[email protected]
DTEND;TZID=Europe/Vilnius:20200915T100000
TRANSP:OPAQUE
ORGANIZER;CN="testKrt":mailto:[email protected]
UID:BA3017ED-889A-4BCB-B9CB-11CE30586021
DTSTAMP:20200821T081914Z
SEQUENCE:1
SUMMARY:Yearly custom 2
DTSTART;TZID=Europe/Vilnius:20200915T090000
X-APPLE-TRAVEL-ADVISORY-BEHAVIOR:AUTOMATIC
CREATED:20200821T081842Z
RRULE:FREQ=YEARLY;INTERVAL=1;BYMONTH=9;BYDAY=1TU
END:VEVENT
END:VCALENDAR`;
const parsedInvitation = parseVcalendar(invitation) as VcalVcalendar;
const message = { Time: Math.round(Date.now() / 1000) } as Message;
await expect(
getSupportedEventInvitation({
vcalComponent: parsedInvitation,
message,
icsBinaryString: invitation,
icsFileName: 'test.ics',
primaryTimezone: 'America/Sao_Paulo',
})
).rejects.toMatchObject(
new EventInvitationError(EVENT_INVITATION_ERROR_TYPE.INVITATION_INVALID, {
method: ICAL_METHOD.REQUEST,
})
);
});
test('should refuse invitations with non-yearly recurrence rules that contain a byyearday', async () => {
const invitation = `BEGIN:VCALENDAR
CALSCALE:GREGORIAN
VERSION:2.0
METHOD:REQUEST
BEGIN:VEVENT
ATTENDEE;CUTYPE=INDIVIDUAL;EMAIL="[email protected]";PARTSTAT=NEED
S-ACTION;RSVP=TRUE:mailto:[email protected]
ATTENDEE;CN="testKrt";CUTYPE=INDIVIDUAL;EMAIL="[email protected]
m";PARTSTAT=ACCEPTED;ROLE=CHAIR:mailto:[email protected]
DTEND;TZID=Europe/Vilnius:20200915T100000
ORGANIZER;CN="testKrt":mailto:[email protected]
UID:BA3017ED-889A-4BCB-B9CB-11CE30586021
DTSTAMP:20200121T081914Z
SEQUENCE:1
SUMMARY:Non-yearly with byyearday
DTSTART;TZID=Europe/Vilnius:20200915T090000
X-APPLE-TRAVEL-ADVISORY-BEHAVIOR:AUTOMATIC
CREATED:20200821T081842Z
RRULE:FREQ=MONTHLY;INTERVAL=1;BYYEARDAY=21
END:VEVENT
END:VCALENDAR`;
const parsedInvitation = parseVcalendar(invitation) as VcalVcalendar;
const message = { Time: Math.round(Date.now() / 1000) } as Message;
await expect(
getSupportedEventInvitation({
vcalComponent: parsedInvitation,
message,
icsBinaryString: invitation,
icsFileName: 'test.ics',
primaryTimezone: 'America/Sao_Paulo',
})
).rejects.toMatchObject(
new EventInvitationError(EVENT_INVITATION_ERROR_TYPE.INVITATION_INVALID, {
method: ICAL_METHOD.REQUEST,
})
);
});
test('should generate a hash UID for invitations with no method and drop alarms and recurrence id', async () => {
const invitation = `BEGIN:VCALENDAR
CALSCALE:GREGORIAN
VERSION:2.0
PRODID:-//Apple Inc.//Mac OS X 10.13.6//EN
BEGIN:VEVENT
UID:test-event
DTSTAMP:19980309T231000Z
DTSTART;TZID=/mozilla.org/20050126_1/Europe/Brussels:20021231T203000
DTEND;TZID=/mozilla.org/20050126_1/Europe/Brussels:20030101T003000
RECURRENCE-ID;TZID=Europe/Brussels:20121231T203000
LOCATION:1CP Conference Room 4350
ATTENDEE;CUTYPE=INDIVIDUAL;EMAIL="[email protected]";PARTSTAT=NEED
S-ACTION;RSVP=TRUE:mailto:[email protected]
ATTENDEE;CN="testKrt";CUTYPE=INDIVIDUAL;EMAIL="[email protected]
m";PARTSTAT=ACCEPTED;ROLE=CHAIR:mailto:[email protected]
TRANSP:OPAQUE
ORGANIZER;CN="testKrt":mailto:[email protected]
BEGIN:VALARM
TRIGGER:-PT15H
ACTION:DISPLAY
END:VALARM
BEGIN:VALARM
TRIGGER:-PT1W2D
ACTION:EMAIL
END:VALARM
END:VEVENT
END:VCALENDAR`;
const parsedInvitation = parseVcalendar(invitation) as VcalVcalendar;
const message = { Time: Math.round(Date.now() / 1000) } as Message;
expect(
await getSupportedEventInvitation({
vcalComponent: parsedInvitation,
message,
icsBinaryString: invitation,
icsFileName: 'test.ics',
primaryTimezone: 'America/Sao_Paulo',
})
).toMatchObject({
method: 'PUBLISH',
vevent: {
component: 'vevent',
uid: { value: 'original-uid-test-event-sha1-uid-cba317c4bb79e20bdca567bf6dc80dfce145712b' },
dtstamp: {
value: { year: 1998, month: 3, day: 9, hours: 23, minutes: 10, seconds: 0, isUTC: true },
},
dtstart: {
value: { year: 2002, month: 12, day: 31, hours: 20, minutes: 30, seconds: 0, isUTC: false },
parameters: { tzid: 'Europe/Brussels' },
},
dtend: {
value: { year: 2003, month: 1, day: 1, hours: 0, minutes: 30, seconds: 0, isUTC: false },
parameters: { tzid: 'Europe/Brussels' },
},
},
originalVcalInvitation: parsedInvitation,
originalUniqueIdentifier: 'test-event',
hasMultipleVevents: false,
fileName: 'test.ics',
});
});
test('should generate a DTSTAMP from the message if no DTSTAMP was present', async () => {
const invitation = `BEGIN:VCALENDAR
CALSCALE:GREGORIAN
VERSION:2.0
PRODID:-//Apple Inc.//Mac OS X 10.13.6//EN
BEGIN:VEVENT
UID:test-event
DTSTART;TZID=/mozilla.org/20050126_1/Europe/Brussels:20021231T203000
DTEND;TZID=/mozilla.org/20050126_1/Europe/Brussels:20030101T003000
LOCATION:1CP Conference Room 4350
ATTENDEE;CUTYPE=INDIVIDUAL;EMAIL="[email protected]";PARTSTAT=NEED
S-ACTION;RSVP=TRUE:mailto:[email protected]
ATTENDEE;CN="testKrt";CUTYPE=INDIVIDUAL;EMAIL="[email protected]
m";PARTSTAT=ACCEPTED;ROLE=CHAIR:mailto:[email protected]
TRANSP:OPAQUE
ORGANIZER;CN="testKrt":mailto:[email protected]
BEGIN:VALARM
TRIGGER:-PT15H
ACTION:DISPLAY
END:VALARM
BEGIN:VALARM
TRIGGER:-PT1W2D
ACTION:EMAIL
END:VALARM
END:VEVENT
END:VCALENDAR`;
const parsedInvitation = parseVcalendar(invitation) as VcalVcalendar;
const message = { Time: Date.UTC(2022, 9, 10, 10, 0, 0) / 1000 } as Message;
expect(
await getSupportedEventInvitation({
vcalComponent: parsedInvitation,
message,
icsBinaryString: invitation,
icsFileName: 'test.ics',
primaryTimezone: 'America/Sao_Paulo',
})
).toEqual({
method: 'PUBLISH',
vevent: expect.objectContaining({
component: 'vevent',
uid: { value: 'original-uid-test-event-sha1-uid-1d92b0aa7fed011b07b53161798dfeb45cf4e186' },
dtstamp: {
value: { year: 2022, month: 10, day: 10, hours: 10, minutes: 0, seconds: 0, isUTC: true },
},
dtstart: {
value: { year: 2002, month: 12, day: 31, hours: 20, minutes: 30, seconds: 0, isUTC: false },
parameters: { tzid: 'Europe/Brussels' },
},
dtend: {
value: { year: 2003, month: 1, day: 1, hours: 0, minutes: 30, seconds: 0, isUTC: false },
parameters: { tzid: 'Europe/Brussels' },
},
sequence: { value: 0 },
}),
originalIcsHasNoOrganizer: false,
originalVcalInvitation: parsedInvitation,
originalUniqueIdentifier: 'test-event',
legacyUid: 'sha1-uid-1d92b0aa7fed011b07b53161798dfeb45cf4e186-original-uid-test-event',
hasMultipleVevents: false,
fileName: 'test.ics',
});
});
test('should not throw without version, untrimmed calscale and duration', async () => {
const invitation = `BEGIN:VCALENDAR
CALSCALE: Gregorian
PRODID:-//Apple Inc.//Mac OS X 10.13.6//EN
BEGIN:VEVENT
UID:test-event
DTSTAMP:19980309T231000Z
DTSTART;VALUE=DATE:20021231
DURATION:PT2D
END:VEVENT
END:VCALENDAR`;
const parsedInvitation = parseVcalendar(invitation) as VcalVcalendar;
const message = { Time: Math.round(Date.now() / 1000) } as Message;
await expect(
getSupportedEventInvitation({
vcalComponent: parsedInvitation,
message,
icsBinaryString: invitation,
icsFileName: 'test.ics',
primaryTimezone: 'America/Sao_Paulo',
})
).resolves.not.toThrow();
});
test('should throw for unknown calscales', async () => {
const invitation = `BEGIN:VCALENDAR
CALSCALE:GREGORIANU
VERSION:2.0
METHOD:REQUEST
BEGIN:VEVENT
ATTENDEE;CUTYPE=INDIVIDUAL;EMAIL="[email protected]";PARTSTAT=NEED
S-ACTION;RSVP=TRUE:mailto:[email protected]
ATTENDEE;CN="testKrt";CUTYPE=INDIVIDUAL;EMAIL="[email protected]
m";PARTSTAT=ACCEPTED;ROLE=CHAIR:mailto:[email protected]
DTEND;TZID=Europe/Vilnius:20200915T100000
ORGANIZER;CN="testKrt":mailto:[email protected]
UID:BA3017ED-889A-4BCB-B9CB-11CE30586021
DTSTAMP:20200121T081914Z
SEQUENCE:1
SUMMARY:Non-yearly with byyearday
DTSTART;TZID=Europe/Vilnius:20200915T090000
X-APPLE-TRAVEL-ADVISORY-BEHAVIOR:AUTOMATIC
CREATED:20200821T081842Z
RRULE:FREQ=MONTHLY;INTERVAL=1;BYYEARDAY=21
END:VEVENT
END:VCALENDAR`;
const parsedInvitation = parseVcalendar(invitation) as VcalVcalendar;
const message = { Time: Math.round(Date.now() / 1000) } as Message;
await expect(
getSupportedEventInvitation({
vcalComponent: parsedInvitation,
message,
icsBinaryString: invitation,
icsFileName: 'test.ics',
primaryTimezone: 'America/Sao_Paulo',
})
).rejects.toMatchObject(
new EventInvitationError(EVENT_INVITATION_ERROR_TYPE.INVITATION_UNSUPPORTED, {
method: ICAL_METHOD.REQUEST,
})
);
});
test('should not throw when receiving a VTIMEZONE without TZID', async () => {
const invitation = `BEGIN:VCALENDAR
PRODID:-//Google Inc//Google Calendar 70.9054//EN
VERSION:2.0
CALSCALE:GREGORIAN
METHOD:REQUEST
X-WR-TIMEZONE:Pacific/Niue
BEGIN:VTIMEZONE
X-LIC-LOCATION:Pacific/Niue
BEGIN:STANDARD
TZOFFSETFROM:-1100
TZOFFSETTO:-1100
TZNAME:-11
DTSTART:19700101T000000
END:STANDARD
END:VTIMEZONE
BEGIN:VEVENT
DTSTART:20220403T153000Z
DTEND:20220403T163000Z
DTSTAMP:20220307T132207Z
ORGANIZER;[email protected]:mailto:[email protected]
om
UID:[email protected]
ATTENDEE;CUTYPE=INDIVIDUAL;ROLE=REQ-PARTICIPANT;PARTSTAT=NEEDS-ACTION;RSVP=
TRUE;[email protected];X-NUM-GUESTS=0:mailto:calenda
[email protected]
ATTENDEE;CUTYPE=INDIVIDUAL;ROLE=REQ-PARTICIPANT;PARTSTAT=NEEDS-ACTION;RSVP=
TRUE;[email protected];X-NUM-GUESTS=0:mailto:[email protected]
ATTENDEE;CUTYPE=INDIVIDUAL;ROLE=REQ-PARTICIPANT;PARTSTAT=ACCEPTED;RSVP=TRUE
;[email protected];X-NUM-GUESTS=0:mailto:calendarregression@g
mail.com
ATTENDEE;CUTYPE=INDIVIDUAL;ROLE=REQ-PARTICIPANT;PARTSTAT=NEEDS-ACTION;RSVP=
TRUE;[email protected];X-NUM-GUESTS=0:mailto:visionary@lyse
nko.proton.black
ATTENDEE;CUTYPE=INDIVIDUAL;ROLE=REQ-PARTICIPANT;PARTSTAT=NEEDS-ACTION;RSVP=
TRUE;[email protected];X-NUM-GUESTS=0:mailto:[email protected]
lack
ATTENDEE;CUTYPE=INDIVIDUAL;ROLE=REQ-PARTICIPANT;PARTSTAT=NEEDS-ACTION;RSVP=
TRUE;[email protected];X-NUM-GUESTS=0:mailto:[email protected]
.black
X-GOOGLE-CONFERENCE:https://meet.google.com/aey-yjac-rfe
X-MICROSOFT-CDO-OWNERAPPTID:-1984897430
CREATED:20220307T132206Z
DESCRIPTION:-::~:~::~:~:~:~:~:~:~:~:~:~:~:~:~:~:~:~:~:~:~:~:~:~:~:~:~:~:~:~
:~:~:~:~:~:~:~:~::~:~::-\\nDo not edit this section of the description.\\n\\nT
his event has a video call.\\nJoin: https://meet.google.com/aey-yjac-rfe\\n\\n
View your event at https://calendar.google.com/calendar/event?action=VIEW&e
id=MDkyOGo4OTdicWFoMzVpNDI0ZG52amR1M3YgcHJvQGx5c2Vua28ucHJvdG9uLmJsYWNr&tok
=MjgjY2FsZW5kYXJyZWdyZXNzaW9uQGdtYWlsLmNvbWM0MmE4NGNmZDY5NTBlYzliNzdlY2Q1N2
ZiNDcwYWFmNjc1YWY5NDE&ctz=Europe%2FVilnius&hl=en_GB&es=1.\\n-::~:~::~:~:~:~:
~:~:~:~:~:~:~:~:~:~:~:~:~:~:~:~:~:~:~:~:~:~:~:~:~:~:~:~:~:~:~:~::~:~::-
LAST-MODIFIED:20220307T132206Z
LOCATION:
SEQUENCE:0
STATUS:CONFIRMED
SUMMARY:Pacific / Niue (3)
TRANSP:OPAQUE
END:VEVENT
END:VCALENDAR`;
const parsedInvitation = parseVcalendar(invitation) as VcalVcalendar;
const message = { Time: Math.round(Date.now() / 1000) } as Message;
await expect(
getSupportedEventInvitation({
vcalComponent: parsedInvitation,
message,
icsBinaryString: invitation,
icsFileName: 'test.ics',
primaryTimezone: 'America/Sao_Paulo',
})
).resolves.not.toThrow();
});
test('should reformat break lines properly', async () => {
const invitation = `BEGIN:VCALENDAR
PRODID:-//Google Inc//Google Calendar 70.9054//EN
VERSION:2.0
CALSCALE:GREGORIAN
METHOD:REQUEST
BEGIN:VEVENT
DTSTART;VALUE=DATE:20220111
DTEND;VALUE=DATE:20220112
DTSTAMP:20210108T113223Z
ORGANIZER:mailto:[email protected]
UID:case5544646879321797797898799
X-MICROSOFT-CDO-OWNERAPPTID:-1089749046
ATTENDEE;[email protected];CUTYPE=INDIVIDUAL;[email protected];RSVP=TRUE;PARTSTAT=NEEDS-ACTION:/aMjk2MDIzMDQ4Mjk2MDI
zMIZjbeHD-pCEmJU6loV23jx6n2nXhXA9yXmtoE4a87979dmv46466/principal/
ATTENDEE;[email protected];CUTYPE=INDIVIDUAL;[email protected];RSVP=TRUE;PARTSTAT=NEEDS-ACTION:/aMjk2MDIzMDQ4Mjk2MDI
zMIZjbeHD-pCEmJU6loV23jx6n2nXhXA9yXmtoE4ad7879mv67/principal/
CREATED:20210108T113222Z
DESCRIPTION:Extracting attendee
LAST-MODIFIED:20210108T113222Z
LOCATION:
SEQUENCE:0
STATUS:CONFIRMED
SUMMARY:Attendees - 6 invited apple 2
TRANSP:TRANSPARENT
END:VEVENT
END:VCALENDAR`;
const parsedInvitation = parseVcalendar(invitation) as VcalVcalendar;
const message = { Time: Math.round(Date.now() / 1000) } as Message;
expect(
await getSupportedEventInvitation({
vcalComponent: parsedInvitation,
message,
icsBinaryString: invitation,
icsFileName: 'test.ics',
primaryTimezone: 'America/Sao_Paulo',
})
).toMatchObject({
method: 'REQUEST',
vevent: {
component: 'vevent',
uid: { value: 'case5544646879321797797898799' },
dtstamp: {
value: { year: 2021, month: 1, day: 8, hours: 11, minutes: 32, seconds: 23, isUTC: true },
},
dtstart: {
value: { year: 2022, month: 1, day: 11 },
parameters: { type: 'date' },
},
summary: { value: 'Attendees - 6 invited apple 2' },
description: { value: 'Extracting attendee' },
sequence: { value: 0 },
organizer: { value: 'mailto:[email protected]' },
attendee: [
{
value: 'mailto:[email protected]',
parameters: {
cn: '[email protected]',
rsvp: ICAL_ATTENDEE_RSVP.TRUE,
partstat: ICAL_ATTENDEE_STATUS.NEEDS_ACTION,
},
},
{
value: 'mailto:[email protected]',
parameters: {
cn: '[email protected]',
rsvp: ICAL_ATTENDEE_RSVP.TRUE,
partstat: ICAL_ATTENDEE_STATUS.NEEDS_ACTION,
},
},
],
},
vtimezone: parsedInvitation.components?.find((component) => getIsTimezoneComponent(component)),
originalVcalInvitation: parsedInvitation,
originalUniqueIdentifier: 'case5544646879321797797898799',
hasMultipleVevents: false,
fileName: 'test.ics',
});
});
describe('should fix sequences out of bounds', () => {
test('if they are negative', async () => {
const invitation = `BEGIN:VCALENDAR
CALSCALE:GREGORIAN
VERSION:2.0
PRODID:-//Apple Inc.//Mac OS X 10.13.6//EN
BEGIN:VEVENT
UID:test-event
DTSTART;TZID=/mozilla.org/20050126_1/Europe/Brussels:20021231T203000
DTEND;TZID=/mozilla.org/20050126_1/Europe/Brussels:20030101T003000
SEQUENCE:-1
LOCATION:1CP Conference Room 4350
ATTENDEE;CUTYPE=INDIVIDUAL;EMAIL="[email protected]";PARTSTAT=NEED
S-ACTION;RSVP=TRUE:mailto:[email protected]
ATTENDEE;CN="testKrt";CUTYPE=INDIVIDUAL;EMAIL="[email protected]
m";PARTSTAT=ACCEPTED;ROLE=CHAIR:mailto:[email protected]
TRANSP:OPAQUE
ORGANIZER;CN="testKrt":mailto:[email protected]
BEGIN:VALARM
TRIGGER:-PT15H
ACTION:DISPLAY
END:VALARM
BEGIN:VALARM
TRIGGER:-PT1W2D
ACTION:EMAIL
END:VALARM
END:VEVENT
END:VCALENDAR`;
const parsedInvitation = parseVcalendar(invitation) as VcalVcalendar;
const message = { Time: Date.UTC(2022, 9, 10, 10, 0, 0) / 1000 } as Message;
expect(
await getSupportedEventInvitation({
vcalComponent: parsedInvitation,
message,
icsBinaryString: invitation,
icsFileName: 'test.ics',
primaryTimezone: 'America/Sao_Paulo',
})
).toEqual(
expect.objectContaining({
vevent: expect.objectContaining({
sequence: { value: 0 },
}),
})
);
});
test('if they are too big', async () => {
const invitation = `BEGIN:VCALENDAR
CALSCALE:GREGORIAN
VERSION:2.0
PRODID:-//Apple Inc.//Mac OS X 10.13.6//EN
BEGIN:VEVENT
UID:test-event
DTSTART;TZID=/mozilla.org/20050126_1/Europe/Brussels:20021231T203000
DTEND;TZID=/mozilla.org/20050126_1/Europe/Brussels:20030101T003000
SEQUENCE:2205092022
LOCATION:1CP Conference Room 4350
ATTENDEE;CUTYPE=INDIVIDUAL;EMAIL="[email protected]";PARTSTAT=NEED
S-ACTION;RSVP=TRUE:mailto:[email protected]
ATTENDEE;CN="testKrt";CUTYPE=INDIVIDUAL;EMAIL="[email protected]
m";PARTSTAT=ACCEPTED;ROLE=CHAIR:mailto:[email protected]
TRANSP:OPAQUE
ORGANIZER;CN="testKrt":mailto:[email protected]
BEGIN:VALARM
TRIGGER:-PT15H
ACTION:DISPLAY
END:VALARM
BEGIN:VALARM
TRIGGER:-PT1W2D
ACTION:EMAIL
END:VALARM
END:VEVENT
END:VCALENDAR`;
const parsedInvitation = parseVcalendar(invitation) as VcalVcalendar;
const message = { Time: Date.UTC(2022, 9, 10, 10, 0, 0) / 1000 } as Message;
expect(
await getSupportedEventInvitation({
vcalComponent: parsedInvitation,
message,
icsBinaryString: invitation,
icsFileName: 'test.ics',
primaryTimezone: 'America/Sao_Paulo',
})
).toEqual(
expect.objectContaining({
vevent: expect.objectContaining({
sequence: { value: 57608374 },
}),
})
);
});
});
});
describe('getSupportedEventInvitation should guess a timezone to localize floating dates for invites', () => {
const generateVcalSetup = ({
method = ICAL_METHOD.REQUEST,
primaryTimezone = 'Asia/Seoul',
xWrTimezone = '',
vtimezonesTzids = [],
}: {
method?: ICAL_METHOD;
xWrTimezone?: string;
vtimezonesTzids?: string[];
primaryTimezone?: string;
}) => {
const xWrTimezoneString = xWrTimezone ? `X-WR-TIMEZONE:${xWrTimezone}` : '';
const vtimezonesString = vtimezonesTzids
.map(
(tzid) => `BEGIN:VTIMEZONE
TZID:${tzid}
END:VTIMEZONE`
)
.join('\n');
const vcal = `BEGIN:VCALENDAR
CALSCALE:GREGORIAN
VERSION:2.0
METHOD:${method}
${xWrTimezoneString}
${vtimezonesString}
BEGIN:VEVENT
ATTENDEE;CUTYPE=INDIVIDUAL;EMAIL="[email protected]";PARTSTAT=NEED
S-ACTION;RSVP=TRUE:mailto:[email protected]
ATTENDEE;CN="testKrt";CUTYPE=INDIVIDUAL;EMAIL="[email protected]
m";PARTSTAT=ACCEPTED;ROLE=CHAIR:mailto:[email protected]
DTSTART:20200915T090000
DTEND:20200915T100000
ORGANIZER;CN="testKrt":mailto:[email protected]
UID:BA3017ED-889A-4BCB-B9CB-11CE30586021
DTSTAMP:20200821T081914Z
SEQUENCE:1
SUMMARY:Floating date-time
RRULE:FREQ=DAILY;INTERVAL=2;COUNT=5
END:VEVENT
END:VCALENDAR`;
return {
vcalComponent: parse(vcal) as VcalVcalendar,
message: { Time: Math.round(Date.now() / 1000) } as Message,
icsBinaryString: vcal,
icsFileName: 'test.ics',
primaryTimezone,
};
};
const localizedVevent = (tzid: string) => ({
component: 'vevent',
uid: { value: 'BA3017ED-889A-4BCB-B9CB-11CE30586021' },
dtstamp: {
value: { year: 2020, month: 8, day: 21, hours: 8, minutes: 19, seconds: 14, isUTC: true },
},
dtstart: {
value: { year: 2020, month: 9, day: 15, hours: 9, minutes: 0, seconds: 0, isUTC: false },
parameters: { tzid },
},
dtend: {
value: { year: 2020, month: 9, day: 15, hours: 10, minutes: 0, seconds: 0, isUTC: false },
parameters: { tzid },
},
summary: { value: 'Floating date-time' },
sequence: { value: 1 },
rrule: { value: { freq: 'DAILY', interval: 2, count: 5 } },
organizer: {
value: 'mailto:[email protected]',
parameters: { cn: 'testKrt' },
},
attendee: [
{
value: 'mailto:[email protected]',
parameters: {
partstat: 'NEEDS-ACTION',
rsvp: 'TRUE',
cn: '[email protected]',
},
},
{
value: 'mailto:[email protected]',
parameters: {
partstat: 'ACCEPTED',
cn: 'testKrt',
},
},
],
});
test('when there is both x-wr-timezone and single vtimezone (use x-wr-timezone)', async () => {
const { vevent } =
(await getSupportedEventInvitation(
generateVcalSetup({
xWrTimezone: 'Europe/Brussels',
vtimezonesTzids: ['America/New_York'],
})
)) || {};
expect(vevent).toEqual(localizedVevent('Europe/Brussels'));
});
test('when there is a single vtimezone and no x-wr-timezone', async () => {
const { vevent } =
(await getSupportedEventInvitation(
generateVcalSetup({
vtimezonesTzids: ['Europe/Vilnius'],
})
)) || {};
expect(vevent).toEqual(localizedVevent('Europe/Vilnius'));
});
test('when there is a single vtimezone and x-wr-timezone is not supported', async () => {
await expect(
getSupportedEventInvitation(
generateVcalSetup({
method: ICAL_METHOD.REPLY,
xWrTimezone: 'Moon/Tranquility',
vtimezonesTzids: ['Europe/Vilnius'],
})
)
).rejects.toThrowError('Unsupported response');
});
test('when there is no vtimezone nor x-wr-timezone (reject unsupported event)', async () => {
await expect(
getSupportedEventInvitation(
generateVcalSetup({
method: ICAL_METHOD.CANCEL,
})
)
).rejects.toThrowError('Unsupported invitation');
});
test('when there is no x-wr-timezone and more than one vtimezone (reject unsupported event)', async () => {
await expect(
getSupportedEventInvitation(
generateVcalSetup({
method: ICAL_METHOD.COUNTER,
vtimezonesTzids: ['Europe/Vilnius', 'America/New_York'],
})
)
).rejects.toThrowError('Unsupported response');
});
});
describe('getSupportedEventInvitation should guess a timezone to localize floating dates for invites for import PUBLISH', () => {
const generateVcalSetup = async ({
method = ICAL_METHOD.PUBLISH,
xWrTimezone = '',
vtimezonesTzids = [],
primaryTimezone,
uid = 'BA3017ED-889A-4BCB-B9CB-11CE30586021',
}: {
method?: ICAL_METHOD;
xWrTimezone?: string;
vtimezonesTzids?: string[];
primaryTimezone: string;
uid?: string;
}) => {
const xWrTimezoneString = xWrTimezone ? `X-WR-TIMEZONE:${xWrTimezone}` : '';
const vtimezonesString = vtimezonesTzids
.map(
(tzid) => `BEGIN:VTIMEZONE
TZID:${tzid}
END:VTIMEZONE`
)
.join('\n');
const vcal = `BEGIN:VCALENDAR
CALSCALE:GREGORIAN
VERSION:2.0
METHOD:${method}
${xWrTimezoneString}
${vtimezonesString}
BEGIN:VEVENT
ATTENDEE;CUTYPE=INDIVIDUAL;EMAIL="[email protected]";PARTSTAT=NEED
S-ACTION;RSVP=TRUE:mailto:[email protected]
ATTENDEE;CN="testKrt";CUTYPE=INDIVIDUAL;EMAIL="[email protected]
m";PARTSTAT=ACCEPTED;ROLE=CHAIR:mailto:[email protected]
DTSTART:20200915T090000
DTEND:20200915T100000
ORGANIZER;CN="testKrt":mailto:[email protected]
UID:${uid}
DTSTAMP:20200821T081914Z
SEQUENCE:1
SUMMARY:Floating date-time
RRULE:FREQ=DAILY;INTERVAL=2;COUNT=5
END:VEVENT
END:VCALENDAR`;
const parsedVcal = parse(vcal) as VcalVcalendar;
return {
vcalComponent: parsedVcal,
message: { Time: Math.round(Date.now() / 1000) } as Message,
icsBinaryString: vcal,
icsFileName: 'test.ics',
primaryTimezone,
hashUid: await generateVeventHashUID(vcal, uid),
};
};
const localizedVevent = (tzid: string, hashUid: string) => ({
component: 'vevent',
uid: { value: hashUid },
dtstamp: {
value: { year: 2020, month: 8, day: 21, hours: 8, minutes: 19, seconds: 14, isUTC: true },
},
dtstart: {
value: { year: 2020, month: 9, day: 15, hours: 9, minutes: 0, seconds: 0, isUTC: false },
parameters: { tzid },
},
dtend: {
value: { year: 2020, month: 9, day: 15, hours: 10, minutes: 0, seconds: 0, isUTC: false },
parameters: { tzid },
},
summary: { value: 'Floating date-time' },
sequence: { value: 1 },
rrule: { value: { freq: 'DAILY', interval: 2, count: 5 } },
});
test('when there is both x-wr-timezone and single vtimezone (use x-wr-timezone)', async () => {
const setup = await generateVcalSetup({
primaryTimezone: 'Asia/Seoul',
xWrTimezone: 'Europe/Brussels',
vtimezonesTzids: ['America/New_York'],
});
const { vevent } = (await getSupportedEventInvitation(setup)) || {};
expect(vevent).toEqual(localizedVevent('Europe/Brussels', setup.hashUid));
});
test('when there is a single vtimezone and no x-wr-timezone', async () => {
const setup = await generateVcalSetup({
primaryTimezone: 'Asia/Seoul',
vtimezonesTzids: ['Europe/Vilnius'],
});
const { vevent } = (await getSupportedEventInvitation(setup)) || {};
expect(vevent).toEqual(localizedVevent('Europe/Vilnius', setup.hashUid));
});
test('when there is a single vtimezone and x-wr-timezone is not supported', async () => {
await expect(
getSupportedEventInvitation(
await generateVcalSetup({
primaryTimezone: 'Asia/Seoul',
xWrTimezone: 'Moon/Tranquility',
vtimezonesTzids: ['Europe/Vilnius'],
})
)
).rejects.toThrowError('Unsupported event');
});
test('when there is no vtimezone nor x-wr-timezone (use primary time zone)', async () => {
const setup = await generateVcalSetup({
primaryTimezone: 'Asia/Seoul',
});
const { vevent } = (await getSupportedEventInvitation(setup)) || {};
expect(vevent).toEqual(localizedVevent('Asia/Seoul', setup.hashUid));
});
test('when there is no x-wr-timezone and more than one vtimezone (use primary time zone)', async () => {
const setup = await generateVcalSetup({
primaryTimezone: 'Asia/Seoul',
vtimezonesTzids: ['Europe/Vilnius', 'America/New_York'],
});
const { vevent } = (await getSupportedEventInvitation(setup)) || {};
expect(vevent).toEqual(localizedVevent('Asia/Seoul', setup.hashUid));
});
});
describe('getSupportedEventInvitation should throw', () => {
const generateVcalSetup = async ({
method = ICAL_METHOD.REQUEST,
primaryTimezone,
uid,
}: {
method?: ICAL_METHOD;
xWrTimezone?: string;
vtimezonesTzids?: string[];
primaryTimezone: string;
uid?: string;
}) => {
const vcal = `BEGIN:VCALENDAR
CALSCALE:GREGORIAN
VERSION:2.0
METHOD:${method}
BEGIN:VEVENT
ATTENDEE;CUTYPE=INDIVIDUAL;EMAIL="[email protected]";PARTSTAT=NEED
S-ACTION;RSVP=TRUE:mailto:[email protected]
ATTENDEE;CN="testKrt";CUTYPE=INDIVIDUAL;EMAIL="[email protected]
m";PARTSTAT=ACCEPTED;ROLE=CHAIR:mailto:[email protected]
DTSTART:20200915T090000
DTEND:20200915T100000
ORGANIZER;CN="testKrt":mailto:[email protected]
${uid ? `UID:${uid}` : ''}
DTSTAMP:20200821T081914Z
SEQUENCE:1
SUMMARY:Testing something
RRULE:FREQ=DAILY;INTERVAL=2;COUNT=5
END:VEVENT
END:VCALENDAR`;
const parsedVcal = parse(vcal) as VcalVcalendar;
return {
vcalComponent: parsedVcal,
message: { Time: Math.round(Date.now() / 1000) } as Message,
icsBinaryString: vcal,
icsFileName: 'test.ics',
primaryTimezone,
hashUid: await generateVeventHashUID(vcal, uid),
};
};
test('when invitations do not have UID', async () => {
await expect(
getSupportedEventInvitation(
await generateVcalSetup({
method: ICAL_METHOD.REQUEST,
primaryTimezone: 'Asia/Seoul',
})
)
).rejects.toThrowError('Invalid invitation');
});
});
describe('getIsPartyCrasher', () => {
describe('organizer mode', () => {
const isOrganizerMode = true;
const calendarEventUID = 'calendarEventUID';
const attendeeAddress = '[email protected]';
const organizerAddress = '[email protected]';
const message = {
data: {
Sender: {
Address: attendeeAddress,
} as Recipient,
},
} as MessageStateWithData;
it('should return false when there is no event in the DB', async () => {
const results = await Promise.all(
[true, false].map((isPartyCrasherIcs) =>
getIsPartyCrasher({
isOrganizerMode,
message,
isPartyCrasherIcs,
})
)
);
expect(results.every((result) => result === false)).toBeTruthy();
});
it('should return false when the event in the DB contains the attendee (decryptable event)', async () => {
const results = await Promise.all(
[true, false].map((isPartyCrasherIcs) =>
getIsPartyCrasher({
isOrganizerMode,
invitationApi: {
attendee: {
emailAddress: attendeeAddress,
} as Participant,
organizer: {
emailAddress: organizerAddress,
},
} as RequireSome<EventInvitation, 'calendarEvent'>,
message,
isPartyCrasherIcs,
})
)
);
expect(results.every((result) => result === false)).toBeTruthy();
});
it('should return true when the event in the DB does not contain the attendee (decryptable event)', async () => {
const results = await Promise.all(
[true, false].map((isPartyCrasherIcs) =>
getIsPartyCrasher({
isOrganizerMode,
invitationApi: {
organizer: {
emailAddress: organizerAddress,
},
} as RequireSome<EventInvitation, 'calendarEvent'>,
message,
isPartyCrasherIcs,
})
)
);
expect(results.every((result) => result === true)).toBeTruthy();
});
it('should return false when the event in the DB contains the attendee (undecryptable event)', async () => {
const results = await Promise.all(
[true, false].map(async (isPartyCrasherIcs) =>
getIsPartyCrasher({
isOrganizerMode,
calendarEvent: {
UID: calendarEventUID,
Attendees: [
{
Token: await generateAttendeeToken(attendeeAddress, calendarEventUID),
},
] as Attendee[],
} as CalendarEvent,
message,
isPartyCrasherIcs,
})
)
);
expect(results.every((result) => result === false)).toBeTruthy();
});
it('should return true when the event in the DB does not contain the attendee (undecryptable event)', async () => {
const results = await Promise.all(
[true, false].map((isPartyCrasherIcs) =>
getIsPartyCrasher({
isOrganizerMode,
calendarEvent: {
UID: calendarEventUID,
Attendees: [] as Attendee[],
} as CalendarEvent,
message,
isPartyCrasherIcs,
})
)
);
expect(results.every((result) => result === true)).toBeTruthy();
});
});
describe('attendee mode', () => {
const isOrganizerMode = false;
const attendeeAddress = '[email protected]';
const organizerAddress = '[email protected]';
const message = {
data: {
Sender: {
Address: organizerAddress,
} as Recipient,
},
} as MessageStateWithData;
it('should return the isPartyCrasher value computed from the ics when the invitation is not in the user calendar', async () => {
const [truthyResult, falsyResult] = await Promise.all(
[true, false].map((isPartyCrasherIcs) =>
getIsPartyCrasher({
isOrganizerMode,
message,
isPartyCrasherIcs,
})
)
);
expect(truthyResult).toEqual(true);
expect(falsyResult).toEqual(false);
});
it('should return the isPartyCrasher value computed from the ics when the user is in the invitation attendee list', async () => {
const [truthyResult, falsyResult] = await Promise.all(
[true, false].map((isPartyCrasherIcs) =>
getIsPartyCrasher({
isOrganizerMode,
invitationApi: {
attendee: {
emailAddress: attendeeAddress,
} as Participant,
organizer: {
emailAddress: organizerAddress,
},
} as RequireSome<EventInvitation, 'calendarEvent'>,
message,
isPartyCrasherIcs,
})
)
);
expect(truthyResult).toEqual(true);
expect(falsyResult).toEqual(false);
});
it('should return the isPartyCrasher value computed from the ics when the user is not in the invitation attendee list', async () => {
const [truthyResult, falsyResult] = await Promise.all(
[true, false].map((isPartyCrasherIcs) =>
getIsPartyCrasher({
isOrganizerMode,
invitationApi: {} as RequireSome<EventInvitation, 'calendarEvent'>,
message,
isPartyCrasherIcs,
})
)
);
expect(truthyResult).toEqual(true);
expect(falsyResult).toEqual(false);
});
});
});
});
|
3,852 | 0 | petrpan-code/ProtonMail/WebClients/applications/mail/src/app/helpers | petrpan-code/ProtonMail/WebClients/applications/mail/src/app/helpers/checklist/checkedItemsStorage.test.ts | import { deleteCheckedItemsForUser, getSavedCheckedItemsForUser, saveCheckedItemsForUser } from './checkedItemsStorage';
describe('checkedItemsStorage', () => {
it('Should save checked items', () => {
saveCheckedItemsForUser('testUserId', ['checkedAccount']);
const savedItems = getSavedCheckedItemsForUser('testUserId');
expect(savedItems).toEqual(['checkedAccount']);
});
it('Should delete data for user', () => {
saveCheckedItemsForUser('testUserId', ['checkedAccount']);
deleteCheckedItemsForUser('testUserId');
const savedItems = getSavedCheckedItemsForUser('testUserId');
expect(savedItems).toEqual([]);
});
it('Should return empty array if no data', () => {
const savedItems = getSavedCheckedItemsForUser('testUserId');
expect(savedItems).toEqual([]);
});
it('Should return empty array if no data for user', () => {
saveCheckedItemsForUser('testUserId', ['checkedAccount']);
const savedItems = getSavedCheckedItemsForUser('testOtherUserId');
expect(savedItems).toEqual([]);
});
it('Should not override other users data when present in storage', () => {
saveCheckedItemsForUser('testUserId', ['checkedAccount']);
saveCheckedItemsForUser('testOtherUserId', ['checkedAccount2, checkedAccount3']);
const savedItems = getSavedCheckedItemsForUser('testUserId');
expect(savedItems).toEqual(['checkedAccount']);
});
it('Should not delete other user data when deleting data for one user', () => {
saveCheckedItemsForUser('testUserId', ['checkedAccount']);
saveCheckedItemsForUser('testOtherUserId', ['checkedAccount2, checkedAccount3']);
deleteCheckedItemsForUser('testUserId');
const savedItems = getSavedCheckedItemsForUser('testOtherUserId');
expect(savedItems).toEqual(['checkedAccount2, checkedAccount3']);
});
it('Should return empty array for user not present in storage when multiple other users present', () => {
saveCheckedItemsForUser('testUserId', ['checkedAccount']);
saveCheckedItemsForUser('testOtherUserId', ['checkedAccount2, checkedAccount3']);
const savedItems = getSavedCheckedItemsForUser('testAnotherUserId');
expect(savedItems).toEqual([]);
});
});
|
3,864 | 0 | petrpan-code/ProtonMail/WebClients/applications/mail/src/app/helpers | petrpan-code/ProtonMail/WebClients/applications/mail/src/app/helpers/message/icon.test.ts | import { PublicKeyReference } from '@proton/crypto';
import { MIME_TYPES } from '@proton/shared/lib/constants';
import { KeyTransparencyActivation } from '@proton/shared/lib/interfaces';
import { Message } from '@proton/shared/lib/interfaces/mail/Message';
import { SIGNATURE_START, VERIFICATION_STATUS } from '@proton/shared/lib/mail/constants';
import {
ENCRYPTION_PREFERENCES_ERROR_TYPES,
EncryptionPreferencesError,
} from '@proton/shared/lib/mail/encryptionPreferences';
import { PACKAGE_TYPE } from '@proton/shared/lib/mail/mailSettings';
import { MessageState, MessageVerification } from '../../logic/messages/messagesTypes';
import { STATUS_ICONS_FILLS, StatusIcon, X_PM_HEADERS } from '../../models/crypto';
import {
getReceivedStatusIcon,
getSendStatusIcon,
getSentStatusIcon,
getSentStatusIconInfo,
getStatusIconName,
} from './icon';
const { NOT_SIGNED, NOT_VERIFIED, SIGNED_AND_VALID, SIGNED_AND_INVALID } = VERIFICATION_STATUS;
const fakeKey1: PublicKeyReference = {
getFingerprint() {
return 'fakeKey1';
},
getUserIDs: () => ['<[email protected]>'],
} as PublicKeyReference;
describe('icon', () => {
describe('getSendStatusIcon', () => {
const ktActivation = KeyTransparencyActivation.DISABLED;
it('should return a blue plain lock when sending to internal users without pinned keys', () => {
const sendPreferences = {
encrypt: true,
sign: true,
pgpScheme: PACKAGE_TYPE.SEND_PM,
mimeType: MIME_TYPES.DEFAULT,
hasApiKeys: true,
hasPinnedKeys: false,
isPublicKeyPinned: false,
encryptionDisabled: false,
};
expect(getSendStatusIcon(sendPreferences, ktActivation)).toMatchObject({
colorClassName: 'color-info',
isEncrypted: true,
fill: STATUS_ICONS_FILLS.PLAIN,
text: 'End-to-end encrypted',
});
});
it('should return a blue lock with checkmark when sending to internal users with a pinned key', () => {
const sendPreferences = {
encrypt: true,
sign: true,
pgpScheme: PACKAGE_TYPE.SEND_PM,
mimeType: MIME_TYPES.DEFAULT,
hasApiKeys: true,
hasPinnedKeys: true,
isPublicKeyPinned: true,
encryptionDisabled: false,
};
expect(getSendStatusIcon(sendPreferences, ktActivation)).toMatchObject({
colorClassName: 'color-info',
isEncrypted: true,
fill: STATUS_ICONS_FILLS.CHECKMARK,
text: 'End-to-end encrypted to verified recipient',
});
});
it('should return an error sign when sending to internal users with pinned keys, but the pinned key is not used', () => {
const sendPreferences = {
encrypt: true,
sign: true,
pgpScheme: PACKAGE_TYPE.SEND_PM,
mimeType: MIME_TYPES.DEFAULT,
hasApiKeys: true,
hasPinnedKeys: true,
isPublicKeyPinned: false,
encryptionDisabled: false,
error: new EncryptionPreferencesError(
ENCRYPTION_PREFERENCES_ERROR_TYPES.PRIMARY_NOT_PINNED,
'test error'
),
};
expect(getSendStatusIcon(sendPreferences, ktActivation)).toMatchObject({
colorClassName: 'color-danger',
isEncrypted: false,
fill: STATUS_ICONS_FILLS.FAIL,
text: 'test error',
});
});
it('should return a green plain lock when sending to WKD users without pinned keys', () => {
const sendPreferences = {
encrypt: true,
sign: true,
pgpScheme: PACKAGE_TYPE.SEND_PGP_INLINE,
mimeType: MIME_TYPES.PLAINTEXT,
hasApiKeys: true,
hasPinnedKeys: false,
isPublicKeyPinned: false,
encryptionDisabled: false,
};
expect(getSendStatusIcon(sendPreferences, ktActivation)).toMatchObject({
colorClassName: 'color-success',
isEncrypted: true,
fill: STATUS_ICONS_FILLS.PLAIN,
text: 'End-to-end encrypted',
});
});
it('should return a green lock with checkmark when sending to WKD users with a pinned key', () => {
const sendPreferences = {
encrypt: true,
sign: true,
pgpScheme: PACKAGE_TYPE.SEND_PGP_MIME,
mimeType: MIME_TYPES.MIME,
hasApiKeys: true,
hasPinnedKeys: true,
isPublicKeyPinned: true,
encryptionDisabled: false,
};
expect(getSendStatusIcon(sendPreferences, ktActivation)).toMatchObject({
colorClassName: 'color-success',
isEncrypted: true,
fill: STATUS_ICONS_FILLS.CHECKMARK,
text: 'End-to-end encrypted to verified recipient',
});
});
it('should return ar error sign when sending to WKD users with pinned keys, but the pinned key is not used', () => {
const sendPreferences = {
encrypt: true,
sign: true,
pgpScheme: PACKAGE_TYPE.SEND_PGP_MIME,
mimeType: MIME_TYPES.MIME,
hasApiKeys: true,
hasPinnedKeys: true,
isPublicKeyPinned: false,
encryptionDisabled: false,
error: new EncryptionPreferencesError(
ENCRYPTION_PREFERENCES_ERROR_TYPES.PRIMARY_NOT_PINNED,
'test error'
),
};
expect(getSendStatusIcon(sendPreferences, ktActivation)).toMatchObject({
colorClassName: 'color-danger',
isEncrypted: false,
fill: STATUS_ICONS_FILLS.FAIL,
text: 'test error',
});
});
it('should return a green lock with warning sign when sending to WKD users without pinned keys with warnings', () => {
const sendPreferences = {
encrypt: true,
sign: true,
pgpScheme: PACKAGE_TYPE.SEND_PGP_MIME,
mimeType: MIME_TYPES.MIME,
hasApiKeys: true,
hasPinnedKeys: false,
isPublicKeyPinned: false,
encryptionDisabled: false,
warnings: ['warning test 1', 'warning test 2'],
};
expect(getSendStatusIcon(sendPreferences, ktActivation)).toMatchObject({
colorClassName: 'color-success',
isEncrypted: true,
fill: STATUS_ICONS_FILLS.WARNING,
text: "End-to-end encrypted. Recipient's key validation failed: warning test 1; warning test 2",
});
});
it('should return a green lock with warning sign when sending to WKD users with pinned keys with warnings', () => {
const sendPreferences = {
encrypt: true,
sign: true,
pgpScheme: PACKAGE_TYPE.SEND_PGP_MIME,
mimeType: MIME_TYPES.MIME,
hasApiKeys: true,
hasPinnedKeys: true,
isPublicKeyPinned: true,
encryptionDisabled: false,
warnings: ['warning test 1', 'warning test 2'],
};
expect(getSendStatusIcon(sendPreferences, ktActivation)).toMatchObject({
colorClassName: 'color-success',
isEncrypted: true,
fill: STATUS_ICONS_FILLS.WARNING,
text: "End-to-end encrypted. Recipient's key validation failed: warning test 1; warning test 2",
});
});
it('should return a green open lock for external PGP messages only signed', () => {
const sendPreferences = {
encrypt: false,
sign: true,
pgpScheme: PACKAGE_TYPE.SEND_PGP_MIME,
mimeType: MIME_TYPES.MIME,
hasApiKeys: false,
hasPinnedKeys: false,
encryptionDisabled: false,
};
expect(getSendStatusIcon(sendPreferences, ktActivation)).toMatchObject({
colorClassName: 'color-success',
isEncrypted: false,
fill: STATUS_ICONS_FILLS.SIGN,
text: 'PGP-signed',
});
});
it('should return a green lock with pencil sign for external PGP-encrypted (and signed) messages', () => {
const sendPreferences = {
encrypt: true,
sign: true,
pgpScheme: PACKAGE_TYPE.SEND_PGP_INLINE,
mimeType: MIME_TYPES.PLAINTEXT,
hasApiKeys: false,
hasPinnedKeys: true,
isPublicKeyPinned: false,
encryptionDisabled: false,
};
expect(getSendStatusIcon(sendPreferences, ktActivation)).toMatchObject({
colorClassName: 'color-success',
isEncrypted: true,
fill: STATUS_ICONS_FILLS.SIGN,
text: 'PGP-encrypted',
});
});
it('should return a green lock with checkmark for external PGP messages if encrypted with a pinned key', () => {
const sendPreferences = {
encrypt: true,
sign: true,
pgpScheme: PACKAGE_TYPE.SEND_PGP_MIME,
mimeType: MIME_TYPES.MIME,
hasApiKeys: false,
hasPinnedKeys: true,
isPublicKeyPinned: true,
encryptionDisabled: false,
};
expect(getSendStatusIcon(sendPreferences, ktActivation)).toMatchObject({
colorClassName: 'color-success',
isEncrypted: true,
fill: STATUS_ICONS_FILLS.CHECKMARK,
text: 'PGP-encrypted to verified recipient',
});
});
it('should return a green lock with warning sign for external PGP messages with warnings on the pinned key', () => {
const sendPreferences = {
encrypt: true,
sign: true,
pgpScheme: PACKAGE_TYPE.SEND_PGP_MIME,
mimeType: MIME_TYPES.MIME,
hasApiKeys: false,
hasPinnedKeys: true,
isPublicKeyPinned: true,
encryptionDisabled: false,
warnings: ['warning test 1', 'warning test 2'],
};
expect(getSendStatusIcon(sendPreferences, ktActivation)).toMatchObject({
colorClassName: 'color-success',
isEncrypted: true,
fill: STATUS_ICONS_FILLS.WARNING,
text: "PGP-encrypted. Recipient's key validation failed: warning test 1; warning test 2",
});
});
it('should return nothing when sending unencrypted and unsigned', () => {
const sendPreferences = {
encrypt: false,
sign: false,
pgpScheme: PACKAGE_TYPE.SEND_CLEAR,
mimeType: MIME_TYPES.MIME,
hasApiKeys: false,
hasPinnedKeys: false,
isPublicKeyPinned: false,
encryptionDisabled: false,
};
expect(getSendStatusIcon(sendPreferences, ktActivation)).toBeUndefined();
});
describe('when encryption is disabled', () => {
it('should return a black plain lock with "Zero-access" message', () => {
const sendPreferences = {
encryptionDisabled: true,
encrypt: false,
sign: false,
pgpScheme: PACKAGE_TYPE.SEND_CLEAR,
mimeType: MIME_TYPES.DEFAULT,
hasApiKeys: false,
hasPinnedKeys: false,
isPublicKeyPinned: false,
};
expect(getSendStatusIcon(sendPreferences, ktActivation)).toMatchObject({
colorClassName: 'color-norm',
isEncrypted: false,
fill: STATUS_ICONS_FILLS.PLAIN,
text: 'Zero-access encrypted. Recipient has disabled end-to-end encryption on their account.',
});
});
});
});
describe('getSentStatusIcon for imported sent message', () => {
it('should display black padlock icon', () => {
const globalIcon = getSentStatusIcon({
mapAuthentication: {},
mapEncryption: {},
contentEncryption: X_PM_HEADERS.ON_DELIVERY,
emailAddress: undefined,
isImported: true,
});
expect(globalIcon?.colorClassName).toBe('color-norm');
});
});
describe('getSentStatusIcon for individual recipients', () => {
const email = '[email protected]';
const getIconFromHeaders = (headers: { [key: string]: string }, emailAddress: string) => {
const message = {
data: {
ParsedHeaders: headers,
},
} as unknown as MessageState;
const { mapStatusIcon } = getSentStatusIconInfo(message) || {};
return mapStatusIcon[emailAddress];
};
it('should return no lock for messages sent by you neither encrypted nor authenticated', () => {
const headers = {
'X-Pm-Recipient-Authentication': 'test%40pm.me=none',
'X-Pm-Recipient-Encryption': 'test%40pm.me=none',
'X-Pm-Content-Encryption': 'end-to-end',
};
const icon = getIconFromHeaders(headers, email);
expect(icon).toEqual(undefined);
});
it('should return a green plain lock for messages sent by Proton Mail encrypted but not authenticated to PGP recipient', () => {
const headers = {
'X-Pm-Recipient-Authentication': 'test%40pm.me=none',
'X-Pm-Recipient-Encryption': 'test%40pm.me=pgp-inline',
'X-Pm-Content-Encryption': 'on-delivery',
};
const icon = getIconFromHeaders(headers, email);
expect(icon).toMatchObject({
colorClassName: 'color-success',
isEncrypted: true,
fill: STATUS_ICONS_FILLS.PLAIN,
text: 'Encrypted by Proton Mail to PGP recipient',
});
});
it('should return a green lock with pencil for messages sent by you authenticated but not encrypted to PGP recipient', () => {
const headers = {
'X-Pm-Recipient-Authentication': 'test%40pm.me=pgp-inline',
'X-Pm-Recipient-Encryption': 'test%40pm.me=none',
'X-Pm-Content-Encryption': 'on-compose',
};
const icon = getIconFromHeaders(headers, email);
expect(icon).toMatchObject({
colorClassName: 'color-success',
isEncrypted: false,
fill: STATUS_ICONS_FILLS.SIGN,
text: 'PGP-signed',
});
});
it('should return a blue lock with check-mark for messages sent by you encrypted to a Proton Mail recipient with pinned keys', () => {
const headers = {
'X-Pm-Recipient-Authentication': 'test%40pm.me=pgp-pm',
'X-Pm-Recipient-Encryption': 'test%40pm.me=pgp-pm-pinned',
'X-Pm-Content-Encryption': 'end-to-end',
};
const icon = getIconFromHeaders(headers, email);
expect(icon).toMatchObject({
colorClassName: 'color-info',
isEncrypted: true,
fill: STATUS_ICONS_FILLS.CHECKMARK,
text: 'End-to-end encrypted to verified recipient',
});
});
it('should return a green plain lock for messages sent by you encrypted and authenticated to PGP recipient with pinned keys', () => {
const headers = {
'X-Pm-Recipient-Authentication': 'test%40pm.me=pgp-mime',
'X-Pm-Recipient-Encryption': 'test%40pm.me=pgp-mime-pinned',
'X-Pm-Content-Encryption': 'end-to-end',
};
const icon = getIconFromHeaders(headers, email);
expect(icon).toMatchObject({
colorClassName: 'color-success',
isEncrypted: true,
fill: STATUS_ICONS_FILLS.CHECKMARK,
text: 'End-to-end encrypted to verified PGP recipient',
});
});
it('should return a blue plain lock for messages sent by you encrypted and authenticated to Proton Mail recipient', () => {
const headers = {
'X-Pm-Recipient-Authentication': 'test%40pm.me=pgp-pm',
'X-Pm-Recipient-Encryption': 'test%40pm.me=pgp-pm',
'X-Pm-Content-Encryption': 'end-to-end',
};
const icon = getIconFromHeaders(headers, email);
expect(icon).toMatchObject({
colorClassName: 'color-info',
isEncrypted: true,
fill: STATUS_ICONS_FILLS.PLAIN,
text: 'End-to-end encrypted',
});
});
it('should return a blue plain lock for messages sent by Proton Mail encrypted and authenticated to Proton Mail recipient', () => {
const headers = {
'X-Pm-Recipient-Authentication': 'test%40pm.me=pgp-pm',
'X-Pm-Recipient-Encryption': 'test%40pm.me=pgp-pm',
'X-Pm-Content-Encryption': 'on-delivery',
};
const icon = getIconFromHeaders(headers, email);
expect(icon).toMatchObject({
colorClassName: 'color-info',
isEncrypted: true,
fill: STATUS_ICONS_FILLS.PLAIN,
text: 'Encrypted by Proton Mail',
});
});
it('should return a blue lock with check mark for messages sent by Proton Mail encrypted and authenticated to Proton Mail recipient with pinned keys', () => {
const headers = {
'X-Pm-Recipient-Authentication': 'test%40pm.me=pgp-pm',
'X-Pm-Recipient-Encryption': 'test%40pm.me=pgp-pm-pinned',
'X-Pm-Content-Encryption': 'on-delivery',
};
const icon = getIconFromHeaders(headers, email);
expect(icon).toMatchObject({
colorClassName: 'color-info',
isEncrypted: true,
fill: STATUS_ICONS_FILLS.CHECKMARK,
text: 'Encrypted by Proton Mail to verified recipient',
});
});
it('should return a green plain lock for messages sent by Proton Mail encrypted and authenticated to PGP recipient with pinned keys', () => {
const headers = {
'X-Pm-Recipient-Authentication': 'test%40pm.me=pgp-mime',
'X-Pm-Recipient-Encryption': 'test%40pm.me=pgp-mime-pinned',
'X-Pm-Content-Encryption': 'on-delivery',
};
const icon = getIconFromHeaders(headers, email);
expect(icon).toMatchObject({
colorClassName: 'color-success',
isEncrypted: true,
fill: STATUS_ICONS_FILLS.CHECKMARK,
text: 'Encrypted by Proton Mail to verified PGP recipient',
});
});
it('should return a blue plain lock for messages sent by you encrypted-to-outside', () => {
const headers = {
'X-Pm-Recipient-Authentication': 'test%40pm.me=pgp-eo',
'X-Pm-Recipient-Encryption': 'test%40pm.me=pgp-eo',
'X-Pm-Content-Encryption': 'end-to-end',
};
const icon = getIconFromHeaders(headers, email);
expect(icon).toMatchObject({
colorClassName: 'color-info',
isEncrypted: true,
fill: STATUS_ICONS_FILLS.PLAIN,
text: 'End-to-end encrypted',
});
});
it('should return undefined when the headers are missing', () => {
const headers = {};
const icon = getIconFromHeaders(headers, email);
expect(icon).toEqual(undefined);
});
it('should return undefined when the headers do not contain the email address', () => {
const headers = {
'X-Pm-Recipient-Authentication': 'test%40pm.me=pgp-pm',
'X-Pm-Recipient-Encryption': 'testing%40pm.me=pgp-pm',
'X-Pm-Content-Encryption': 'end-to-end',
};
const icon = getIconFromHeaders(headers, email);
expect(icon).toEqual(undefined);
});
});
describe('getSentStatusIcon for aggregated icon', () => {
const getIconFromHeaders = (headers: { [key: string]: string }) => {
const message = {
data: {
ParsedHeaders: headers,
},
} as unknown as MessageState;
const { globalIcon } = getSentStatusIconInfo(message);
return globalIcon;
};
it('should return a blue lock with checkmark when sending to all pinned with some internal', () => {
const headers = {
'X-Pm-Recipient-Authentication': 'test%40pm.me=pgp-mime;test2%40pm.me=pgp-inline;test3%40pm.me=pgp-pm',
'X-Pm-Recipient-Encryption':
'test%40pm.me=pgp-mime-pinned;test2%40pm.me=pgp-inline-pinned;test3%40pm.me=pgp-pm-pinned',
'X-Pm-Content-Encryption': 'end-to-end',
};
const icon = getIconFromHeaders(headers);
expect(icon).toMatchObject({
colorClassName: 'color-info',
isEncrypted: true,
fill: STATUS_ICONS_FILLS.CHECKMARK,
text: 'Sent by you with end-to-end encryption to verified recipients',
});
});
it('should return a green lock with checkmark when sending to all pinned external', () => {
const headers = {
'X-Pm-Recipient-Authentication': 'test%40pm.me=pgp-mime;test2%40pm.me=pgp-inline',
'X-Pm-Recipient-Encryption': 'test%40pm.me=pgp-mime-pinned;test2%40pm.me=pgp-inline-pinned;',
'X-Pm-Content-Encryption': 'on-delivery',
};
const icon = getIconFromHeaders(headers);
expect(icon).toMatchObject({
colorClassName: 'color-success',
isEncrypted: true,
fill: STATUS_ICONS_FILLS.CHECKMARK,
text: 'Sent by Proton Mail with zero-access encryption to verified recipients',
});
});
it('should return a blue plain lock with checkmark when sending EO', () => {
const headers = {
'X-Pm-Recipient-Authentication': 'test%40pm.me=pgp-eo',
'X-Pm-Recipient-Encryption': 'test%40pm.me=pgp-eo;',
'X-Pm-Content-Encryption': 'end-to-end',
};
const icon = getIconFromHeaders(headers);
expect(icon).toMatchObject({
colorClassName: 'color-info',
isEncrypted: true,
fill: STATUS_ICONS_FILLS.PLAIN,
text: 'Sent by you with end-to-end encryption',
});
});
it('should return a green plain lock when sending to some not pinned external', () => {
const headers = {
'X-Pm-Recipient-Authentication': 'test%40pm.me=pgp-mime;test2%40pm.me=pgp-inline',
'X-Pm-Recipient-Encryption': 'test%40pm.me=pgp-mime-pinned;test2%40pm.me=pgp-inline;',
'X-Pm-Content-Encryption': 'on-delivery',
};
const icon = getIconFromHeaders(headers);
expect(icon).toMatchObject({
colorClassName: 'color-success',
isEncrypted: true,
fill: STATUS_ICONS_FILLS.PLAIN,
text: 'Sent by Proton Mail with zero-access encryption',
});
});
it('should return a blue plain lock when sending encrypted to mixed recipients', () => {
const headers = {
'X-Pm-Recipient-Authentication': 'test%40pm.me=pgp-pm;test2%40pm.me=pgp-inline;test3%40pm.me=pgp-eo',
'X-Pm-Recipient-Encryption': 'test%40pm.me=pgp-pm-pinned;test2%40pm.me=pgp-inline;test3%40pm.me=pgp-eo',
'X-Pm-Content-Encryption': 'end-to-end',
};
const icon = getIconFromHeaders(headers);
expect(icon).toMatchObject({
colorClassName: 'color-info',
isEncrypted: true,
fill: STATUS_ICONS_FILLS.PLAIN,
text: 'Sent by you with end-to-end encryption',
});
});
it('should fall back to a blue lock when the email was not sent encrypted to some recipient', () => {
const headers = {
'X-Pm-Recipient-Authentication':
'test%40pm.me=pgp-pm;test2%40pm.me=pgp-inline;test3%40pm.me=pgp-eo;test4%40pm.me=none',
'X-Pm-Recipient-Encryption':
'test%40pm.me=pgp-pm-pinned;test2%40pm.me=pgp-inline;test3%40pm.me=pgp-eo;test4%40pm.me=none',
'X-Pm-Content-Encryption': 'end-to-end',
};
const icon = getIconFromHeaders(headers);
expect(icon).toMatchObject({
colorClassName: 'color-info',
isEncrypted: true,
fill: STATUS_ICONS_FILLS.PLAIN,
text: 'Stored with zero-access encryption',
});
});
it('should fall back to a blue lock when some headers are missing', () => {
const headers = {
'X-Pm-Content-Encryption': 'end-to-end',
};
const icon = getIconFromHeaders(headers);
expect(icon).toMatchObject({
colorClassName: 'color-info',
isEncrypted: true,
fill: STATUS_ICONS_FILLS.PLAIN,
text: 'Stored with zero-access encryption',
});
});
it('should fall back to a blue lock when there are no headers', () => {
const headers = {};
const icon = getIconFromHeaders(headers);
expect(icon).toMatchObject({
colorClassName: 'color-info',
isEncrypted: true,
fill: STATUS_ICONS_FILLS.PLAIN,
text: 'Stored with zero-access encryption',
});
});
});
describe('getReceivedStatusIcon', () => {
it.each`
origin | encryption | pinnedKeys | pinnedKeysVerified | verificationStatus | colorClassName | iconName | text
${'internal'} | ${'on-delivery'} | ${[]} | ${false} | ${NOT_VERIFIED} | ${'color-info'} | ${'lock-filled'} | ${'Sent by Proton Mail with zero-access encryption'}
${'internal'} | ${'end-to-end'} | ${[]} | ${false} | ${NOT_SIGNED} | ${'color-info'} | ${'lock-filled'} | ${'End-to-end encrypted message'}
${'internal'} | ${'end-to-end'} | ${[fakeKey1]} | ${true} | ${NOT_SIGNED} | ${'color-info'} | ${'lock-exclamation-filled'} | ${'Sender could not be verified: Message not signed'}
${'internal'} | ${'end-to-end'} | ${[]} | ${false} | ${NOT_VERIFIED} | ${'color-info'} | ${'lock-filled'} | ${'End-to-end encrypted and signed message'}
${'internal'} | ${'end-to-end'} | ${[fakeKey1]} | ${true} | ${SIGNED_AND_VALID} | ${'color-info'} | ${'lock-check-filled'} | ${'End-to-end encrypted message from verified sender'}
${'internal'} | ${'end-to-end'} | ${[fakeKey1]} | ${false} | ${SIGNED_AND_VALID} | ${'color-info'} | ${'lock-exclamation-filled'} | ${"Sender's trusted keys verification failed"}
${'internal'} | ${'end-to-end'} | ${[fakeKey1]} | ${true} | ${SIGNED_AND_INVALID} | ${'color-info'} | ${'lock-exclamation-filled'} | ${'Sender verification failed'}
${'external'} | ${'end-to-end'} | ${[]} | ${false} | ${NOT_SIGNED} | ${'color-success'} | ${'lock-filled'} | ${'PGP-encrypted message'}
${'external'} | ${'end-to-end'} | ${[]} | ${false} | ${NOT_VERIFIED} | ${'color-success'} | ${'lock-pen-filled'} | ${'PGP-encrypted and signed message'}
${'external'} | ${'end-to-end'} | ${[fakeKey1]} | ${true} | ${SIGNED_AND_VALID} | ${'color-success'} | ${'lock-check-filled'} | ${'PGP-encrypted message from verified sender'}
${'external'} | ${'end-to-end'} | ${[fakeKey1]} | ${false} | ${SIGNED_AND_VALID} | ${'color-success'} | ${'lock-exclamation-filled'} | ${"Sender's trusted keys verification failed"}
${'external'} | ${'end-to-end'} | ${[fakeKey1]} | ${true} | ${SIGNED_AND_INVALID} | ${'color-success'} | ${'lock-exclamation-filled'} | ${'Sender verification failed'}
${'external'} | ${'on-delivery'} | ${[]} | ${false} | ${NOT_VERIFIED} | ${'color-success'} | ${'lock-open-pen-filled'} | ${'PGP-signed message'}
${'external'} | ${'on-delivery'} | ${[fakeKey1]} | ${true} | ${SIGNED_AND_VALID} | ${'color-success'} | ${'lock-open-check-filled'} | ${'PGP-signed message from verified sender'}
${'external'} | ${'on-delivery'} | ${[fakeKey1]} | ${false} | ${SIGNED_AND_VALID} | ${'color-success'} | ${'lock-open-exclamation-filled'} | ${"Sender's trusted keys verification failed"}
${'external'} | ${'on-delivery'} | ${[fakeKey1]} | ${false} | ${SIGNED_AND_INVALID} | ${'color-success'} | ${'lock-open-exclamation-filled'} | ${'PGP-signed message. Sender verification failed'}
${'external'} | ${'on-delivery'} | ${[]} | ${false} | ${NOT_SIGNED} | ${'color-norm'} | ${'lock-filled'} | ${'Stored with zero-access encryption'}
`(
'should use color $colorClassName, lock $iconName when origin $origin, encryption $encryption, verified pinned keys $pinnedKeysVerified and verification status $verificationStatus',
({
origin,
encryption,
pinnedKeys,
pinnedKeysVerified,
verificationStatus,
colorClassName,
iconName,
text,
}) => {
const headers = {
'X-Pm-Origin': origin,
'X-Pm-Content-Encryption': encryption,
} as any;
const message = {
Time: SIGNATURE_START.USER + 10 * 1000,
ParsedHeaders: headers,
} as Message;
const verification = {
senderPinnedKeys: pinnedKeys,
verificationStatus,
pinnedKeysVerified,
} as MessageVerification;
const icon = getReceivedStatusIcon(message, verification, KeyTransparencyActivation.DISABLED);
const statusIconName = getStatusIconName(icon as StatusIcon);
expect(icon?.colorClassName).toBe(colorClassName);
expect(icon?.text).toBe(text);
expect(statusIconName).toBe(iconName);
}
);
});
});
|
3,867 | 0 | petrpan-code/ProtonMail/WebClients/applications/mail/src/app/helpers | petrpan-code/ProtonMail/WebClients/applications/mail/src/app/helpers/message/messageBlockquote.test.ts | import mails from './__fixtures__/messageBlockquote.fixtures';
import { locateBlockquote } from './messageBlockquote';
/**
* Creating a whole document each time is needed because locate blockquote is using xpath request
* which will fail if the content is not actually in the document
*/
const createDocument = (content: string) => {
const newDocument = document.implementation.createHTMLDocument();
newDocument.body.innerHTML = content;
return newDocument.body;
};
describe('messageBlockquote', () => {
Object.entries(mails as { [name: string]: string }).forEach(([name, content]) => {
it(`should find the blockquote in the mail ${name}`, () => {
const [, blockquote] = locateBlockquote(createDocument(content));
expect(blockquote.length).not.toBe(0);
});
});
it(`should correctly detect proton blockquote with default font and no signature`, () => {
const content = `
<div style="font-family: verdana; font-size: 20px;">
<div style="font-family: verdana; font-size: 20px;"><br></div>
<div class="protonmail_signature_block protonmail_signature_block-empty" style="font-family: verdana; font-size: 20px;">
<div class="protonmail_signature_block-user protonmail_signature_block-empty"></div>
<div class="protonmail_signature_block-proton protonmail_signature_block-empty"></div>
</div>
<div style="font-family: verdana; font-size: 20px;"><br></div>
<div class="protonmail_quote">
On Tuesday, January 4th, 2022 at 17:13, Swiip - Test account <[email protected]> wrote:<br>
<blockquote class="protonmail_quote" type="cite">
<div style="font-family: verdana; font-size: 20px;">
<div style="font-family: verdana; font-size: 20px;">test</div>
<div class="protonmail_signature_block protonmail_signature_block-empty" style="font-family: verdana; font-size: 20px;">
<div class="protonmail_signature_block-user protonmail_signature_block-empty"></div>
<div class="protonmail_signature_block-proton protonmail_signature_block-empty"></div>
</div>
</div>
</blockquote><br>
</div>
</div>`;
const [before, after] = locateBlockquote(createDocument(content));
expect(before).not.toContain('On Tuesday');
expect(after).toContain('On Tuesday');
});
it(`should take the last element containing text in case of siblings blockquotes`, () => {
const content = `
Email content
<div class="protonmail_quote">
blockquote1
</div>
<div class="protonmail_quote">
blockquote2
</div>`;
const [before, after] = locateBlockquote(createDocument(content));
expect(before).toContain('Email content');
expect(before).toContain('blockquote1');
expect(before).not.toContain('blockquote2');
expect(after).toContain('blockquote2');
expect(after).not.toContain('blockquote1');
});
it(`should take the last element containing an image in case of siblings blockquotes`, () => {
const content = `
Email content
<div class="protonmail_quote">
blockquote1
</div>
<div class="protonmail_quote">
<span class="proton-image-anchor" />
</div>`;
const [before, after] = locateBlockquote(createDocument(content));
expect(before).toContain('Email content');
expect(before).toContain('blockquote1');
expect(before).not.toContain('proton-image-anchor');
expect(after).toContain('proton-image-anchor');
expect(after).not.toContain('blockquote1');
});
it(`should display nothing in blockquote when there is text after blockquotes`, () => {
const content = `
Email content
<div class="protonmail_quote">
blockquote1
</div>
text after blockquote`;
const [before, after] = locateBlockquote(createDocument(content));
expect(before).toContain('Email content');
expect(before).toContain('blockquote1');
expect(before).toContain('text after blockquote');
expect(after).toEqual('');
});
it(`should display nothing in blockquote when there is an image after blockquotes`, () => {
const content = `
Email content
<div class="protonmail_quote">
blockquote1
</div>
<span class="proton-image-anchor" />`;
const [before, after] = locateBlockquote(createDocument(content));
expect(before).toContain('Email content');
expect(before).toContain('blockquote1');
expect(before).toContain('proton-image-anchor');
expect(after).toEqual('');
});
});
|
3,869 | 0 | petrpan-code/ProtonMail/WebClients/applications/mail/src/app/helpers | petrpan-code/ProtonMail/WebClients/applications/mail/src/app/helpers/message/messageContent.test.ts | import { MIME_TYPES } from '@proton/shared/lib/constants';
import { Address, MailSettings, UserSettings } from '@proton/shared/lib/interfaces';
import { Attachment, Message } from '@proton/shared/lib/interfaces/mail/Message';
import { PM_SIGNATURE } from '@proton/shared/lib/mail/mailSettings';
import { data, fromFields, recipients } from '../../components/composer/quickReply/tests/QuickReply.test.data';
import { addressID, messageID, subject } from '../../components/message/tests/Message.test.helpers';
import { MESSAGE_ACTIONS } from '../../constants';
import { MessageDecryption, MessageState } from '../../logic/messages/messagesTypes';
import { generateKeys, releaseCryptoProxy, setupCryptoProxyForTesting } from '../test/crypto';
import { clearAll, removeLineBreaks } from '../test/helper';
import { createDocument } from '../test/message';
import { getContentWithBlockquotes, getContentWithoutBlockquotes } from './messageContent';
import { generateBlockquote } from './messageDraft';
const getMessage = (isPlainText: boolean, isReferenceMessage: boolean, content: string) => {
return {
localID: isReferenceMessage ? messageID : 'messageToCleanID',
data: {
ID: isReferenceMessage ? messageID : 'messageToCleanID',
AddressID: addressID,
Subject: subject,
Sender: isReferenceMessage ? recipients.fromRecipient : recipients.meRecipient,
ReplyTos: isReferenceMessage ? [recipients.fromRecipient] : [recipients.meRecipient],
ToList: isReferenceMessage ? [recipients.meRecipient] : [recipients.fromRecipient],
MIMEType: isPlainText ? MIME_TYPES.PLAINTEXT : MIME_TYPES.DEFAULT,
Attachments: [] as Attachment[],
Time: Date.now() / 1000,
} as Message,
decryption: {
decryptedBody: content,
} as MessageDecryption,
messageDocument: {
initialized: true,
plainText: isPlainText ? content : undefined,
document: isPlainText ? undefined : createDocument(content),
},
} as MessageState;
};
const getFakeNow = new Date(2021, 0, 1, 0, 0, 0);
describe('messageContent', () => {
const mailSettings = {
PMSignature: PM_SIGNATURE.ENABLED,
} as MailSettings;
const userSettings = {} as UserSettings;
let addresses: Address[] = [];
const plaintextReferenceMessageBody = 'Hello this is the reference message';
const plaintextReplyContent = 'Hello this is the reply';
const plainTextContent = `${plaintextReplyContent} ${data.protonSignature}
On Friday, January 1st, 2021 at 12:00 AM, ${fromFields.fromName} <${fromFields.fromAddress}> wrote:
> ${plaintextReferenceMessageBody}`;
const htmlReferenceMessageBody = '<div>Hello this is the reference message</div>';
const htmlReplyContent = '<div>Hello this is the reply<div>';
const htmlTextContent = `${htmlReplyContent} ${data.protonSignature}
<div class=\"protonmail_quote\">
On Friday, January 1st, 2021 at 12:00 AM, ${fromFields.fromName} <${fromFields.fromAddress}> wrote:<br><br>
<blockquote class=\"protonmail_quote\" type=\"cite\">
<div>Hello this is the reference message</div>
</blockquote><br>
</div>`;
describe('getContentWithoutBlockquotes', function () {
beforeAll(async () => {
await setupCryptoProxyForTesting();
});
afterAll(async () => {
await releaseCryptoProxy();
});
beforeEach(async () => {
jest.useFakeTimers().setSystemTime(getFakeNow.getTime());
const toKeys = await generateKeys('user', fromFields.meAddress);
addresses = [
{
Email: fromFields.meAddress,
HasKeys: 1,
ID: addressID,
Receive: 1,
Status: 1,
Send: 1,
Keys: [
{
Primary: 1,
PrivateKey: toKeys.privateKeyArmored,
PublicKey: toKeys.publicKeyArmored,
},
],
} as Address,
] as Address[];
});
afterEach(() => {
clearAll();
jest.useRealTimers();
});
it('should remove blockquotes from plaintext message', async () => {
const referenceMessage = getMessage(true, true, plaintextReferenceMessageBody);
const messageToClean = getMessage(true, false, plainTextContent);
const contentWithoutBlockquotes = getContentWithoutBlockquotes(
messageToClean,
referenceMessage,
mailSettings,
userSettings,
addresses,
MESSAGE_ACTIONS.NEW
);
const expectedContent = `${plaintextReplyContent} ${data.protonSignature}`;
// Only the content + the protonSignature should remain
expect((contentWithoutBlockquotes || '').trim()).toEqual(expectedContent);
});
it('should remove blockquotes from HTML message', async () => {
const referenceMessage = getMessage(false, true, htmlReferenceMessageBody);
const messageToCleanBlockquotes = generateBlockquote(
referenceMessage,
mailSettings,
userSettings,
addresses,
MESSAGE_ACTIONS.NEW
);
const messageToCleanBody = `${htmlReplyContent} ${data.protonSignature} ${messageToCleanBlockquotes}`;
const messageToClean = getMessage(false, false, messageToCleanBody);
const contentWithoutBlockquotes = getContentWithoutBlockquotes(
messageToClean,
referenceMessage,
mailSettings,
userSettings,
addresses,
MESSAGE_ACTIONS.NEW
);
const expectedContent = `${htmlReplyContent} ${data.protonSignature}`;
// Only the content + the protonSignature should remain
expect((contentWithoutBlockquotes || '').trim()).toEqual(expectedContent);
});
});
describe('getContentWithBlockquotes', function () {
beforeAll(async () => {
await setupCryptoProxyForTesting();
});
afterAll(async () => {
await releaseCryptoProxy();
});
beforeEach(async () => {
jest.useFakeTimers().setSystemTime(getFakeNow.getTime());
});
afterEach(() => {
clearAll();
jest.useRealTimers();
});
it('should generate content with blockquote string for a plaintext message', async () => {
const referenceMessage = getMessage(true, true, plaintextReferenceMessageBody);
const replyContent = `${plaintextReplyContent} ${data.protonSignature}`;
const contentWithBlockquotes = getContentWithBlockquotes(
replyContent,
true,
referenceMessage,
mailSettings,
userSettings,
addresses,
MESSAGE_ACTIONS.NEW
);
expect(removeLineBreaks(contentWithBlockquotes)).toEqual(removeLineBreaks(plainTextContent));
});
it('should generate content with blockquote string for an HTML message', async () => {
const referenceMessage = getMessage(false, true, htmlReferenceMessageBody);
const replyContent = `${htmlReplyContent} ${data.protonSignature}`;
const contentWithBlockquotes = getContentWithBlockquotes(
replyContent,
false,
referenceMessage,
mailSettings,
userSettings,
addresses,
MESSAGE_ACTIONS.NEW
);
expect(removeLineBreaks(contentWithBlockquotes)).toEqual(removeLineBreaks(htmlTextContent));
});
});
});
|
3,873 | 0 | petrpan-code/ProtonMail/WebClients/applications/mail/src/app/helpers | petrpan-code/ProtonMail/WebClients/applications/mail/src/app/helpers/message/messageDraft.test.ts | import { addPlusAlias } from '@proton/shared/lib/helpers/email';
import { Address, MailSettings, Recipient, UserSettings } from '@proton/shared/lib/interfaces';
import { MESSAGE_FLAGS } from '@proton/shared/lib/mail/constants';
import { FORWARDED_MESSAGE, FW_PREFIX, RE_PREFIX, formatSubject } from '@proton/shared/lib/mail/messages';
import { MESSAGE_ACTIONS } from '../../constants';
import { MessageState, MessageStateWithData } from '../../logic/messages/messagesTypes';
import { formatFullDate } from '../date';
import {
createNewDraft,
generatePreviousMessageInfos,
getBlockquoteRecipientsString,
handleActions,
} from './messageDraft';
const ID = 'ID';
const Time = 0;
const Subject = 'test';
const addressID = 'addressID';
const recipient1 = { Address: '[email protected]' };
const recipient2 = { Address: '[email protected]' };
const recipient3 = { Address: '[email protected]' };
const recipient4 = { Address: '[email protected]' };
const recipient5 = { Address: '[email protected]' };
const message = {
ID,
Time,
Subject,
ToList: [recipient1],
CCList: [recipient2],
BCCList: [recipient3],
ReplyTos: [recipient4],
};
const allActions = [MESSAGE_ACTIONS.NEW, MESSAGE_ACTIONS.REPLY, MESSAGE_ACTIONS.REPLY_ALL, MESSAGE_ACTIONS.FORWARD];
const notNewActions = [MESSAGE_ACTIONS.REPLY, MESSAGE_ACTIONS.REPLY_ALL, MESSAGE_ACTIONS.FORWARD];
const action = MESSAGE_ACTIONS.NEW;
const mailSettings = {} as MailSettings;
const userSettings = {} as UserSettings;
const address = {
ID: 'addressid',
DisplayName: 'name',
Email: 'email',
Status: 1,
Receive: 1,
Send: 1,
Signature: 'signature',
} as Address;
const addresses: Address[] = [address];
describe('messageDraft', () => {
describe('formatSubject', () => {
const listRe = ['Subject', 'Re: Subject', 'Fw: Subject', 'Fw: Re: Subject', 'Re: Fw: Subject'];
const listFw = ['Subject', 'Re: Subject', 'Fw: Subject', 'Fw: Re: Subject', 'Re: Fw: Subject'];
it('should add the RE only if id does not start with it', () => {
const [subject, reply, forward, fwreply, reforward] = listRe;
expect(formatSubject(subject, RE_PREFIX)).toBe(`${RE_PREFIX} ${subject}`);
expect(formatSubject(reply, RE_PREFIX)).toBe(reply);
expect(formatSubject(forward, RE_PREFIX)).toBe(`${RE_PREFIX} ${forward}`);
expect(formatSubject(fwreply, RE_PREFIX)).toBe(`${RE_PREFIX} ${fwreply}`);
expect(formatSubject(reforward, RE_PREFIX)).toBe(reforward);
});
it('should add the Fw only if id does not start with it', () => {
const [subject, reply, forward, fwreply, reforward] = listFw;
expect(formatSubject(subject, FW_PREFIX)).toBe(`${FW_PREFIX} ${subject}`);
expect(formatSubject(reply, FW_PREFIX)).toBe(`${FW_PREFIX} ${reply}`);
expect(formatSubject(forward, FW_PREFIX)).toBe(forward);
expect(formatSubject(fwreply, FW_PREFIX)).toBe(fwreply);
expect(formatSubject(reforward, FW_PREFIX)).toBe(`${FW_PREFIX} ${reforward}`);
});
});
describe('handleActions', () => {
it('should return empty values on copy empty input', () => {
const result = handleActions(MESSAGE_ACTIONS.NEW);
expect(result.data?.Subject).toEqual('');
expect(result.data?.ToList).toEqual([]);
expect(result.data?.CCList).toEqual([]);
expect(result.data?.BCCList).toEqual([]);
});
it('should copy values', () => {
const result = handleActions(MESSAGE_ACTIONS.NEW, {
data: {
Subject,
ToList: [recipient1],
CCList: [recipient2],
BCCList: [recipient3],
},
} as MessageStateWithData);
expect(result.data?.Subject).toEqual(Subject);
expect(result.data?.ToList).toEqual([recipient1]);
expect(result.data?.CCList).toEqual([recipient2]);
expect(result.data?.BCCList).toEqual([recipient3]);
});
it('should prepare a reply for received message', () => {
const result = handleActions(MESSAGE_ACTIONS.REPLY, {
data: {
...message,
Flags: MESSAGE_FLAGS.FLAG_RECEIVED,
},
} as MessageStateWithData);
expect(result.data?.Subject).toEqual(`${RE_PREFIX} ${Subject}`);
expect(result.data?.ToList).toEqual([recipient4]);
});
it('should prepare a reply for sent message', () => {
const result = handleActions(MESSAGE_ACTIONS.REPLY, {
data: {
...message,
Flags: MESSAGE_FLAGS.FLAG_SENT,
},
} as MessageStateWithData);
expect(result.data?.Subject).toEqual(`${RE_PREFIX} ${Subject}`);
expect(result.data?.ToList).toEqual([recipient1]);
});
it('should prepare a reply for received and sent message', () => {
const result = handleActions(MESSAGE_ACTIONS.REPLY, {
data: {
...message,
Flags: MESSAGE_FLAGS.FLAG_SENT | MESSAGE_FLAGS.FLAG_RECEIVED,
},
} as MessageStateWithData);
expect(result.data?.Subject).toEqual(`${RE_PREFIX} ${Subject}`);
expect(result.data?.ToList).toEqual([recipient1]);
});
it('should prepare a reply all for received message', () => {
const result = handleActions(MESSAGE_ACTIONS.REPLY_ALL, {
data: {
...message,
Flags: MESSAGE_FLAGS.FLAG_RECEIVED,
},
} as MessageStateWithData);
expect(result.data?.Subject).toEqual(`${RE_PREFIX} ${Subject}`);
expect(result.data?.ToList).toEqual([recipient4]);
expect(result.data?.CCList).toEqual([recipient1, recipient2]);
expect(result.data?.BCCList).toEqual(undefined);
});
it('should prepare a reply all for sent message', () => {
const result = handleActions(MESSAGE_ACTIONS.REPLY_ALL, {
data: {
...message,
Flags: MESSAGE_FLAGS.FLAG_SENT,
},
} as MessageStateWithData);
expect(result.data?.Subject).toEqual(`${RE_PREFIX} ${Subject}`);
expect(result.data?.ToList).toEqual([recipient1]);
expect(result.data?.CCList).toEqual([recipient2]);
expect(result.data?.BCCList).toEqual([recipient3]);
});
it('should prepare a reply all for received and sent message', () => {
const result = handleActions(MESSAGE_ACTIONS.REPLY_ALL, {
data: {
...message,
Flags: MESSAGE_FLAGS.FLAG_SENT | MESSAGE_FLAGS.FLAG_RECEIVED,
},
} as MessageStateWithData);
expect(result.data?.Subject).toEqual(`${RE_PREFIX} ${Subject}`);
expect(result.data?.ToList).toEqual([recipient1]);
expect(result.data?.CCList).toEqual([recipient2]);
expect(result.data?.BCCList).toEqual([recipient3]);
});
it('should keep other user addresses in the CC list on reply all', () => {
// The email is received on recipient1 (addressID) and recipient5 is another userAddress on which we received the email
// When we reply to this message, recipient1 must be removed from CCList, and recipient5 must be present
const message = {
ID,
Time,
Subject,
ToList: [recipient1, recipient5],
CCList: [recipient2],
BCCList: [recipient3],
ReplyTos: [recipient4],
AddressID: addressID,
};
const result = handleActions(
MESSAGE_ACTIONS.REPLY_ALL,
{
data: {
...message,
Flags: MESSAGE_FLAGS.FLAG_RECEIVED,
},
} as MessageStateWithData,
[
{ ID: addressID, Email: recipient1.Address } as Address,
{ ID: 'otherID', Email: recipient5.Address } as Address,
] as Address[]
);
expect(result.data?.Subject).toEqual(`${RE_PREFIX} ${Subject}`);
expect(result.data?.ToList).toEqual([recipient4]);
expect(result.data?.CCList).toEqual([recipient5, recipient2]);
expect(result.data?.BCCList).toEqual(undefined);
});
it('should prepare recipient list correctly on reply all to alias addresses', () => {
const recipient1Alias = { Address: addPlusAlias(recipient1.Address, 'alias') };
const recipient2Alias = { Address: '[email protected]' };
const recipient3Alias = { Address: addPlusAlias(recipient3.Address, 'alias') };
const recipient4Alias = { Address: '[email protected]' };
const message = {
ID,
Time,
Subject,
ToList: [recipient1Alias],
CCList: [recipient2Alias],
BCCList: [recipient3Alias],
ReplyTos: [recipient4Alias],
AddressID: addressID,
};
const result = handleActions(
MESSAGE_ACTIONS.REPLY_ALL,
{
data: {
...message,
Flags: MESSAGE_FLAGS.FLAG_RECEIVED,
},
} as MessageStateWithData,
[{ ID: addressID, Email: recipient1.Address } as Address] as Address[]
);
expect(result.data?.Subject).toEqual(`${RE_PREFIX} ${Subject}`);
expect(result.data?.ToList).toEqual([recipient4Alias]);
expect(result.data?.CCList).toEqual([recipient2Alias]);
expect(result.data?.BCCList).toEqual(undefined);
});
it('should prepare a forward', () => {
const result = handleActions(MESSAGE_ACTIONS.FORWARD, { data: message } as MessageStateWithData);
expect(result.data?.Subject).toEqual(`${FW_PREFIX} ${Subject}`);
expect(result.data?.ToList).toEqual([]);
expect(result.data?.CCList).toEqual(undefined);
expect(result.data?.BCCList).toEqual(undefined);
});
});
describe('createNewDraft', () => {
it('should use insertSignature', () => {
const result = createNewDraft(
action,
{ data: message } as MessageStateWithData,
mailSettings,
userSettings,
addresses,
jest.fn()
);
expect(result.messageDocument?.document?.innerHTML).toContain(address.Signature);
});
// TODO: Feature to implement
// it('should parse text', () => {
// expect(textToHtmlMail.parse).toHaveBeenCalledTimes(1);
// expect(textToHtmlMail.parse).toHaveBeenCalledWith(MESSAGE_BODY_PLAIN);
// });
// it('should not parse text', () => {
// expect(textToHtmlMail.parse).not.toHaveBeenCalled();
// });
it('should load the sender', () => {
const result = createNewDraft(
action,
{ data: message } as MessageStateWithData,
mailSettings,
userSettings,
addresses,
jest.fn()
);
expect(result.data?.AddressID).toBe(address.ID);
});
it('should add ParentID when not a copy', () => {
notNewActions.forEach((action) => {
const result = createNewDraft(
action,
{ data: message } as MessageStateWithData,
mailSettings,
userSettings,
addresses,
jest.fn()
);
expect(result.draftFlags?.ParentID).toBe(ID);
});
});
it('should set a value to recipient lists', () => {
allActions.forEach((action) => {
const result = createNewDraft(
action,
{ data: message } as MessageStateWithData,
mailSettings,
userSettings,
addresses,
jest.fn()
);
expect(result.data?.ToList?.length).toBeDefined();
expect(result.data?.CCList?.length).toBeDefined();
expect(result.data?.BCCList?.length).toBeDefined();
});
});
// TODO: Feature to be implemented
// it('should set a value to Attachments', () => {
// expect(item.Attachments).toEqual(DEFAULT_MESSAGE_COPY.Attachments);
// });
it('should use values from handleActions', () => {
const result = createNewDraft(
MESSAGE_ACTIONS.REPLY_ALL,
{ data: { ...message, Flags: MESSAGE_FLAGS.FLAG_RECEIVED } } as MessageStateWithData,
mailSettings,
userSettings,
addresses,
jest.fn()
);
expect(result.data?.Subject).toBe(`${RE_PREFIX} ${Subject}`);
expect(result.data?.ToList).toEqual([recipient4]);
expect(result.data?.CCList).toEqual([recipient1, recipient2]);
expect(result.data?.BCCList).toEqual([]);
});
it('should use values from findSender', () => {
const result = createNewDraft(
action,
{ data: message } as MessageStateWithData,
mailSettings,
userSettings,
addresses,
jest.fn()
);
expect(result.data?.AddressID).toBe(address.ID);
expect(result.data?.Sender?.Address).toBe(address.Email);
expect(result.data?.Sender?.Name).toBe(address.DisplayName);
});
});
describe('getBlockquoteRecipientsString', () => {
it('should return the expected recipient string for blockquotes', () => {
const recipientList = [
{ Name: 'Display Name', Address: '[email protected]' },
{ Name: '', Address: '[email protected]' },
{ Address: '[email protected]' },
] as Recipient[];
const expectedString = `Display Name <[email protected]>, [email protected] <[email protected]>, [email protected] <[email protected]>`;
expect(getBlockquoteRecipientsString(recipientList)).toEqual(expectedString);
});
});
describe('generatePreviousMessageInfos', () => {
const messageSubject = 'Subject';
const meRecipient = { Name: 'me', Address: '[email protected]' };
const toRecipient = { Name: 'toRecipient', Address: '[email protected]' };
const ccRecipient = { Address: '[email protected]' };
const sender = { Name: 'sender', Address: '[email protected]' } as Recipient;
const toList = [meRecipient, toRecipient] as Recipient[];
const ccList = [ccRecipient] as Recipient[];
const generateMessage = (hasCCList = true) => {
return {
localID: ID,
data: {
ID,
Subject: messageSubject,
Sender: sender,
ToList: toList,
CCList: hasCCList ? ccList : undefined,
},
} as MessageState;
};
it('should return the correct message blockquotes info for a reply', () => {
const referenceMessage = generateMessage();
const messageBlockquotesInfos = generatePreviousMessageInfos(referenceMessage, MESSAGE_ACTIONS.REPLY);
const expectedString = `On ${formatFullDate(new Date(0))}, ${referenceMessage.data?.Sender
.Name} <${referenceMessage.data?.Sender.Address}> wrote:<br><br>`;
expect(messageBlockquotesInfos).toEqual(expectedString);
});
it('should return the correct message blockquotes info for a forward', () => {
const referenceMessage = generateMessage();
const messageBlockquotesInfos = generatePreviousMessageInfos(referenceMessage, MESSAGE_ACTIONS.FORWARD);
const expectedString = `${FORWARDED_MESSAGE}<br>
From: ${referenceMessage.data?.Sender.Name} <${referenceMessage.data?.Sender.Address}><br>
Date: On ${formatFullDate(new Date(0))}<br>
Subject: ${messageSubject}<br>
To: ${meRecipient.Name} <${meRecipient.Address}>, ${toRecipient.Name} <${toRecipient.Address}><br>
CC: ${ccRecipient.Address} <${ccRecipient.Address}><br><br>`;
expect(messageBlockquotesInfos).toEqual(expectedString);
});
it('should return the correct message blockquotes info for a forward with no CC', () => {
const referenceMessage = generateMessage(false);
const messageBlockquotesInfos = generatePreviousMessageInfos(referenceMessage, MESSAGE_ACTIONS.FORWARD);
const expectedString = `${FORWARDED_MESSAGE}<br>
From: ${referenceMessage.data?.Sender.Name} <${referenceMessage.data?.Sender.Address}><br>
Date: On ${formatFullDate(new Date(0))}<br>
Subject: ${messageSubject}<br>
To: ${meRecipient.Name} <${meRecipient.Address}>, ${toRecipient.Name} <${toRecipient.Address}><br>
<br>`;
expect(messageBlockquotesInfos).toEqual(expectedString);
});
});
});
|
3,875 | 0 | petrpan-code/ProtonMail/WebClients/applications/mail/src/app/helpers | petrpan-code/ProtonMail/WebClients/applications/mail/src/app/helpers/message/messageEmbeddeds.test.tsx | import { stringToUint8Array } from '@proton/shared/lib/helpers/encoding';
import { Attachment } from '@proton/shared/lib/interfaces/mail/Message';
import { MessageEmbeddedImage, MessageImage, PartialMessageState } from '../../logic/messages/messagesTypes';
import { createDocument } from '../test/message';
import {
createBlob,
createEmbeddedImageFromUpload,
embeddableTypes,
findCIDsInContent,
findEmbedded,
generateCid,
insertActualEmbeddedImages,
insertBlobImages,
isEmbeddable,
markEmbeddedImagesAsLoaded,
matchSameCidOrLoc,
readContentIDandLocation,
removeEmbeddedHTML,
replaceEmbeddedAttachments,
setEmbeddedAttr,
trimQuotes,
} from './messageEmbeddeds';
const contentID = 'my-content-id';
const contentLocation = 'my-content-location';
const attachmentID = 'attachmentID';
const attachment = {
Headers: {
'content-id': contentID,
'content-location': contentLocation,
},
ID: attachmentID,
} as Attachment;
describe('messageEmbeddeds', () => {
describe('trimQuotes', () => {
it('should trim quotes', () => {
const string1 = `'string'`;
const string2 = `"string"`;
const string3 = `<string>`;
const expected = 'string';
expect(trimQuotes(string1)).toEqual(expected);
expect(trimQuotes(string2)).toEqual(expected);
expect(trimQuotes(string3)).toEqual(expected);
});
});
describe('isEmbeddable', () => {
it('should be an embeddable file', () => {
const types = embeddableTypes;
types.forEach((type) => {
expect(isEmbeddable(type)).toBeTruthy();
});
});
it('should not be an embeddable file', () => {
const types = ['something', 'application/json', 'image/webp'];
types.forEach((type) => {
expect(isEmbeddable(type)).toBeFalsy();
});
});
});
describe('readContentIDandLocation', () => {
it('should read attachment content id and content location headers', () => {
const { cid, cloc } = readContentIDandLocation(attachment);
expect(cid).toEqual(contentID);
expect(cloc).toEqual(contentLocation);
});
it('should read content id and content location headers with line breaks', () => {
const contentID = `my-content
-id`;
const contentLocation = `my
-content-location`;
const headers = {
'content-id': contentID,
'content-location': contentLocation,
};
const { cid, cloc } = readContentIDandLocation({ Headers: headers });
expect(cid).toEqual('my-content-id');
expect(cloc).toEqual('my-content-location');
});
});
describe('matchSameCidOrLoc', () => {
it('should match the image with cid', () => {
const image = {
cid: contentID,
} as MessageEmbeddedImage;
expect(matchSameCidOrLoc(image, contentID, '')).toBeTruthy();
});
it('should match the image with cloc', () => {
const image = {
cloc: contentLocation,
} as MessageEmbeddedImage;
expect(matchSameCidOrLoc(image, '', contentLocation)).toBeTruthy();
});
it('should not match the image with cloc or cid', () => {
const image = {
cid: 'something',
cloc: 'something else',
} as MessageEmbeddedImage;
expect(matchSameCidOrLoc(image, contentID, contentLocation)).toBeFalsy();
});
});
describe('generateCid', () => {
it('should generate cid', () => {
const input = 'something';
const email = '[email protected]';
expect(generateCid(input, email)).toMatch(/([0-9]|[a-z]){8}@pm\.me/);
});
});
describe('setEmbeddedAttr', () => {
it('should set element cid', () => {
const el = document.createElement('img');
setEmbeddedAttr(contentID, contentLocation, el);
const expectedAttr = `cid:${contentID}`;
expect(el.getAttribute('data-embedded-img')).toEqual(expectedAttr);
});
it('should set element cloc', () => {
const el = document.createElement('img');
setEmbeddedAttr('', contentLocation, el);
const expectedAttr = `cloc:${contentLocation}`;
expect(el.getAttribute('data-embedded-img')).toEqual(expectedAttr);
});
it('should not set element attribute', () => {
const el = document.createElement('img');
setEmbeddedAttr('', '', el);
expect(el.getAttribute('data-embedded-img')).toBeNull();
});
});
describe('createBlob', () => {
beforeEach(() => {
global.URL.createObjectURL = jest.fn(() => 'url');
});
it('should create a blob', () => {
const data = stringToUint8Array('data');
const attachment = { MIMEType: 'image/png' } as Attachment;
const blob = createBlob(attachment, data);
expect(blob).toEqual('url');
});
});
describe('createEmbeddedImageFromUpload', () => {
const expectedImage = {
type: 'embedded',
cid: contentID,
cloc: contentLocation,
tracker: undefined,
attachment,
status: 'loaded',
} as MessageEmbeddedImage;
// Ignore generated id for testing
const { id, ...embeddedImage } = createEmbeddedImageFromUpload(attachment);
expect(embeddedImage).toEqual(expectedImage);
});
describe('finEmbedded', () => {
it.each`
attribute | value
${'src'} | ${`${contentID}`}
${'src'} | ${`cid:${contentID}`}
${'data-embedded-img'} | ${`${contentID}`}
${'data-embedded-img'} | ${`cid:${contentID}`}
${'data-src'} | ${`cid:${contentID}`}
${'proton-src'} | ${`cid:${contentID}`}
`('should find cid image', ({ attribute, value }) => {
const string = `<div>
<img src="random">
<img ${attribute}="${value}"/>
<span>something</span>
</div>`;
const document = createDocument(string);
const expectedImg = window.document.createElement('img');
expectedImg.setAttribute(attribute, value);
expect(findEmbedded(contentID, contentLocation, document)).toEqual([expectedImg]);
});
it('should find cloc images', () => {
const string = `<div>
<img src="random">
<img proton-src="${contentLocation}"/>
<span>something</span>
</div>`;
const document = createDocument(string);
const expectedImg = window.document.createElement('img');
expectedImg.setAttribute('proton-src', contentLocation);
expect(findEmbedded('', contentLocation, document)).toEqual([expectedImg]);
});
it('should not find images', () => {
const string = `<div>
<img src="random">
<span>something</span>
</div>`;
const document = createDocument(string);
expect(findEmbedded(contentID, contentLocation, document)).toEqual([]);
});
});
describe('findCIDsInContent', () => {
it('should find a cid in content', () => {
const string = `<div>
<img src="random" data-embedded-img="${contentID}">
<span>something</span>
</div>`;
expect(findCIDsInContent(string)).toBeTruthy();
});
it('should not a cid in content', () => {
const string = `<div>
<img src="random">
<span>something</span>
</div>`;
expect(findCIDsInContent(string)).toBeTruthy();
});
});
describe('insertActualEmbeddedImages', () => {
it('should insert cid image', function () {
const string = `<div>
<img src="random" data-embedded-img="cid:${contentID}">
<span>something</span>
</div>`;
const document = createDocument(string);
insertActualEmbeddedImages(document);
expect(document.querySelector('img')?.getAttribute('src')).toEqual(`cid:${contentID}`);
const imageWithDataAttribute = document.querySelector('img[data-embedded-img]');
expect(imageWithDataAttribute).toBeNull();
});
it('should insert cloc image', function () {
const string = `<div>
<img src="random" data-embedded-img="cloc:${contentLocation}">
<span>something</span>
</div>`;
const document = createDocument(string);
insertActualEmbeddedImages(document);
expect(document.querySelector('img')?.getAttribute('src')).toEqual(`${contentLocation}`);
const imageWithDataAttribute = document.querySelector('img[data-embedded-img]');
expect(imageWithDataAttribute).toBeNull();
});
});
describe('replaceEmbeddedAttachments', () => {
it('should replace embedded attachments', () => {
const message = {
messageImages: {
hasEmbeddedImages: true,
images: [{ cid: contentID, type: 'embedded' } as MessageEmbeddedImage] as MessageImage[],
},
} as PartialMessageState;
const res = replaceEmbeddedAttachments(message, [attachment]);
const expected = {
attachment: {
Headers: {
'content-id': contentID,
'content-location': contentLocation,
},
ID: attachmentID,
} as Attachment,
cid: contentID,
type: 'embedded',
} as MessageEmbeddedImage;
expect(res.images).toEqual([expected]);
});
});
describe('remoteEmbeddedHTML', () => {
it('should remove embedded attachment from the document', () => {
const string = `<div>
<img src="random" data-embedded-img="${contentID}">
<span>something</span>
</div>`;
const document = createDocument(string);
removeEmbeddedHTML(document, attachment);
expect(document.querySelector('img')).toBeNull();
});
});
describe('insertBlobImages', () => {
it('should insert blob image', () => {
const url = 'https://image.com/img.png';
const string = `<div>
<img proton-src="${url}" data-embedded-img="${contentID}">
<span>something</span>
</div>`;
const document = createDocument(string);
const embeddedImages = [
{ cid: contentID, type: 'embedded', url } as MessageEmbeddedImage,
] as MessageEmbeddedImage[];
insertBlobImages(document, embeddedImages);
const image = document.querySelector('img');
expect(image?.getAttribute('proton-src')).toBeNull();
expect(image?.getAttribute('src')).toEqual(url);
});
});
describe('markEmbeddedImagesAsLoaded', () => {
it('should mark embedded images as loaded', () => {
const blobURL = 'blobURL';
const embeddedImages = [
{
cid: contentID,
type: 'embedded',
attachment: { ID: attachmentID } as Attachment,
} as MessageEmbeddedImage,
] as MessageEmbeddedImage[];
const loadResults: { attachment: Attachment; blob: string }[] = [{ attachment, blob: blobURL }];
const res = markEmbeddedImagesAsLoaded(embeddedImages, loadResults);
const expected = [
{
attachment: { ID: attachmentID },
cid: contentID,
status: 'loaded',
type: 'embedded',
url: blobURL,
},
] as MessageEmbeddedImage[];
expect(res).toEqual(expected);
});
});
});
|
3,877 | 0 | petrpan-code/ProtonMail/WebClients/applications/mail/src/app/helpers | petrpan-code/ProtonMail/WebClients/applications/mail/src/app/helpers/message/messageExpandable.test.ts | import { MAILBOX_LABEL_IDS } from '@proton/shared/lib/constants';
import { Message } from '@proton/shared/lib/interfaces/mail/Message';
import { MESSAGE_FLAGS } from '@proton/shared/lib/mail/constants';
import { findMessageToExpand } from './messageExpandable';
describe('messageExpandable', () => {
it('should return last message if not a custom label and all are reads', () => {
const labelID = MAILBOX_LABEL_IDS.INBOX;
const messages = [
{ ID: '', ConversationID: '', Flags: MESSAGE_FLAGS.FLAG_RECEIVED, Unread: 0 },
{ ID: '', ConversationID: '', Flags: MESSAGE_FLAGS.FLAG_RECEIVED, Unread: 0 },
{ ID: '', ConversationID: '', Flags: MESSAGE_FLAGS.FLAG_RECEIVED, Unread: 0 },
] as Message[];
expect(findMessageToExpand(labelID, messages)).toBe(messages[2]);
});
it('should return last unread message if not a custom label and all are not reads', () => {
const labelID = MAILBOX_LABEL_IDS.INBOX;
const messages = [
{ ID: '', ConversationID: '', Flags: MESSAGE_FLAGS.FLAG_RECEIVED, Unread: 0 },
{ ID: '', ConversationID: '', Flags: MESSAGE_FLAGS.FLAG_RECEIVED, Unread: 1 },
{ ID: '', ConversationID: '', Flags: MESSAGE_FLAGS.FLAG_RECEIVED, Unread: 1 },
] as Message[];
expect(findMessageToExpand(labelID, messages)).toBe(messages[1]);
});
it('should return last unread message if in starred label', () => {
const labelID = MAILBOX_LABEL_IDS.STARRED;
const messages = [
{ ID: '', ConversationID: '', Flags: MESSAGE_FLAGS.FLAG_RECEIVED, Unread: 0 },
{ ID: '', ConversationID: '', Flags: MESSAGE_FLAGS.FLAG_RECEIVED, LabelIDs: [labelID], Unread: 1 },
{ ID: '', ConversationID: '', Flags: MESSAGE_FLAGS.FLAG_RECEIVED, LabelIDs: [labelID], Unread: 1 },
] as Message[];
expect(findMessageToExpand(labelID, messages)).toBe(messages[1]);
});
it('should return last unread message if in starred label', () => {
const labelID = 'my custom label';
const messages = [
{ ID: '', ConversationID: '', Flags: MESSAGE_FLAGS.FLAG_RECEIVED, Unread: 0 },
{ ID: '', ConversationID: '', Flags: MESSAGE_FLAGS.FLAG_RECEIVED, LabelIDs: [labelID], Unread: 1 },
{ ID: '', ConversationID: '', Flags: MESSAGE_FLAGS.FLAG_RECEIVED, LabelIDs: [labelID], Unread: 1 },
] as Message[];
expect(findMessageToExpand(labelID, messages)).toBe(messages[1]);
});
it('should return last message if in draft label', () => {
const labelID = MAILBOX_LABEL_IDS.DRAFTS;
const messages = [
{ ID: '', ConversationID: '', Flags: MESSAGE_FLAGS.FLAG_REPLIED }, // draft
{ ID: '', ConversationID: '', Flags: MESSAGE_FLAGS.FLAG_REPLIED }, // draft
{ ID: '', ConversationID: '', Flags: MESSAGE_FLAGS.FLAG_RECEIVED }, // not draft
] as Message[];
expect(findMessageToExpand(labelID, messages)).toBe(messages[1]);
});
it('should return empty for a conversation with only a draft', () => {
const labelID = 'custom';
const messages = [{ ID: '', ConversationID: '', Flags: MESSAGE_FLAGS.FLAG_REPLIED }] as Message[];
expect(findMessageToExpand(labelID, messages)).toBeUndefined();
});
});
|
3,881 | 0 | petrpan-code/ProtonMail/WebClients/applications/mail/src/app/helpers | petrpan-code/ProtonMail/WebClients/applications/mail/src/app/helpers/message/messageHead.test.ts | import mails from './__fixtures__/messageHead.fixtures';
import { locateHead } from './messageHead';
/**
* Creating a whole document each time is needed because locate blockquote is using xpath request
* which will fail if the content is not actually in the document
*/
const createDocument = (content: string) => {
const newDocument = document.implementation.createHTMLDocument();
newDocument.documentElement.innerHTML = content;
return newDocument;
};
describe('messageHead', () => {
it(`Should find head in a basic email`, () => {
const head = locateHead(createDocument(mails.baseEmail));
expect(head).toContain(`<style type="text/css">a {padding:0;}</style>`);
});
});
|
3,883 | 0 | petrpan-code/ProtonMail/WebClients/applications/mail/src/app/helpers | petrpan-code/ProtonMail/WebClients/applications/mail/src/app/helpers/message/messageImages.test.ts | import { MessageImage, MessageImages, MessageState } from '../../logic/messages/messagesTypes';
import { createDocument } from '../test/message';
import { removeProxyURLAttributes, replaceProxyWithOriginalURLAttributes } from './messageImages';
const imageURL = 'imageURL';
const originalImageURL = 'originalImageURL';
describe('removeProxyURLAttributes', () => {
const content = `<div>
<img proton-src='${originalImageURL}-1' src='${imageURL}-1'/>
<table>
<tbody>
<tr>
<td proton-background='${originalImageURL}-2' background='${imageURL}-2'>Element1</td>
</tr>
</tbody>
</table>
<video proton-poster='${originalImageURL}-3' poster='${imageURL}-3'>
<source src="" type="video/mp4">
</video>
<svg width="90" height="90">
<image proton-xlink:href='${originalImageURL}-4' xlink:href='${imageURL}-4'/>
</svg>
</div>`;
it('should remove all proton urls from the content', () => {
const expectedContent = `<div>
<img src="${originalImageURL}-1">
<table>
<tbody>
<tr>
<td background="${originalImageURL}-2">Element1</td>
</tr>
</tbody>
</table>
<video poster="${originalImageURL}-3">
<source src="" type="video/mp4">
</video>
<svg width="90" height="90">
<image xlink:href="${originalImageURL}-4"></image>
</svg>
</div>`;
const result = removeProxyURLAttributes(content);
expect(result).toEqual(expectedContent);
});
it('should not remove urls from embedded images', () => {
const cid = 'imageCID';
const content = `<div>
<img src="cid:${cid}"/>
<img proton-src="${originalImageURL}-1" src="${imageURL}-1"/>
</div>`;
const expectedContent = `<div>
<img src="cid:${cid}">
<img src="${originalImageURL}-1">
</div>`;
const result = removeProxyURLAttributes(content);
expect(result).toEqual(expectedContent);
});
it('should not remove urls from images with no originalURL', () => {
const content = `<div>
<img src="${imageURL}-1"/>
<img proton-src="${originalImageURL}-2" src="${originalImageURL}-2"/>
<img proton-src="${originalImageURL}-3" src="${imageURL}-3"/>
</div>`;
const expectedContent = `<div>
<img src="${imageURL}-1">
<img src="${originalImageURL}-2">
<img src="${originalImageURL}-3">
</div>`;
const result = removeProxyURLAttributes(content);
expect(result).toEqual(expectedContent);
});
});
describe('replaceProxyWithOriginalURLAttributes', () => {
const content = `<div>
<img proton-src='${originalImageURL}-1' src='${imageURL}-1'/>
<img proton-src='${originalImageURL}-2' src='${originalImageURL}-2'/>
<img src='${originalImageURL}-3'/>
<img proton-src='${originalImageURL}-4'/>
<table>
<tbody>
<tr>
<td proton-background='${originalImageURL}-5' background='${imageURL}-5' >Element1</td>
</tr>
</tbody>
</table>
<video proton-poster='${originalImageURL}-6' poster='${imageURL}-6'>
<source src="" type="video/mp4">
</video>
<svg width="90" height="90">
<image proton-xlink:href='${originalImageURL}-7' xlink:href='${imageURL}-7'/>
</svg>
</div>`;
it('should remove proton attributes and use the original URL', () => {
const messageImages = {
hasRemoteImages: true,
images: [
{ type: 'remote', url: `${imageURL}-1`, originalURL: `${originalImageURL}-1` } as MessageImage,
{ type: 'remote', url: `${originalImageURL}-2`, originalURL: `${originalImageURL}-2` } as MessageImage,
{ type: 'remote', url: `${imageURL}-3` } as MessageImage,
{ type: 'remote', url: `${imageURL}-4` } as MessageImage,
{ type: 'remote', url: `${imageURL}-5`, originalURL: `${originalImageURL}-5` } as MessageImage,
{ type: 'remote', url: `${imageURL}-6`, originalURL: `${originalImageURL}-6` } as MessageImage,
{ type: 'remote', url: `${imageURL}-7`, originalURL: `${originalImageURL}-7` } as MessageImage,
],
} as MessageImages;
const message = {
messageImages,
} as MessageState;
const expected = `<div>
<img src="${originalImageURL}-1">
<img src="${originalImageURL}-2">
<img src="${originalImageURL}-3">
<img src="${originalImageURL}-4">
<table>
<tbody>
<tr>
<td background="${originalImageURL}-5">Element1</td>
</tr>
</tbody>
</table>
<video poster="${originalImageURL}-6">
<source src="" type="video/mp4">
</video>
<svg width="90" height="90">
<image xlink:href="${originalImageURL}-7"></image>
</svg>
</div>`;
const result = replaceProxyWithOriginalURLAttributes(message, createDocument(content));
expect(result).toEqual(expected);
});
});
|
Subsets and Splits