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,887
0
petrpan-code/ProtonMail/WebClients/applications/mail/src/app/helpers
petrpan-code/ProtonMail/WebClients/applications/mail/src/app/helpers/message/messageRecipients.test.ts
import { INCOMING_DEFAULTS_LOCATION } from '@proton/shared/lib/constants'; import { Address, IncomingDefault, SimpleMap } from '@proton/shared/lib/interfaces'; import { Recipient } from '@proton/shared/lib/interfaces/Address'; import { ContactEmail, ContactGroup } from '@proton/shared/lib/interfaces/contacts'; import { Message } from '@proton/shared/lib/interfaces/mail/Message'; import { MESSAGE_FLAGS } from '@proton/shared/lib/mail/constants'; import { fromFields, recipients } from '../../components/composer/quickReply/tests/QuickReply.test.data'; import { MESSAGE_ACTIONS } from '../../constants'; import { MessageState } from '../../logic/messages/messagesTypes'; import { Conversation } from '../../models/conversation'; import { Element } from '../../models/element'; import { findSender, getNumParticipants, getRecipientGroupLabel, getRecipientLabel, getRecipients, getReplyRecipientListAsString, getSendersToBlock, recipientsToRecipientOrGroup, } from './messageRecipients'; const recipient1: Recipient = { Name: '', Address: 'address1' }; const recipient2: Recipient = { Name: 'recipient2', Address: 'address2' }; const recipient3: Recipient = { Name: 'recipient3', Address: 'address3', Group: 'Group1' }; const recipient4: Recipient = { Name: 'recipient4', Address: 'address4', Group: 'Group1' }; const recipient5: Recipient = { Name: 'recipient5', Address: 'address5', Group: 'Group2' }; const group1 = { ID: 'GroupID1', Name: 'GroupName1', Path: 'Group1' } as ContactGroup; const groupMap = { [group1.Path]: group1 }; describe('messageRecipients', () => { describe('findSender', () => { it('should return empty for no message no addresses', () => { const result = findSender(); expect(result).toBe(undefined); }); it('should return empty for no addresses', () => { const result = findSender([], { AddressID: '1' } as Message); expect(result).toBe(undefined); }); it('should return empty if no match', () => { const result = findSender([{ Status: 2 }] as Address[], { AddressID: '1' } as Message); expect(result).toBe(undefined); }); it('should return first if addresses valid but no match', () => { const first = { Status: 1, Order: 1, ID: '2' }; const result = findSender( [{ Status: 2 }, first, { Status: 1, Order: 2, ID: '3' }] as Address[], { AddressID: '1', } as Message ); expect(result).toBe(first); }); it('should return first if addresses order valid but no match', () => { const first = { Status: 1, Order: 1, ID: '2' }; const result = findSender( [{ Status: 2, Order: 0, ID: '1' }, first, { Status: 1, Order: 2, ID: '3' }] as Address[], { AddressID: '1', } as Message ); expect(result).toEqual(first); }); it('should return the match over order', () => { const match = { Status: 1, Order: 2, ID: '1' }; const result = findSender( [{ Status: 2 }, match, { Status: 1, Order: 1, ID: '2' }] as Address[], { AddressID: '1', } as Message ); expect(result).toBe(match); }); }); describe('recipientsToRecipientOrGroup', () => { it('should return recipients if no group', () => { const result = recipientsToRecipientOrGroup([recipient1, recipient2], {}); expect(result).toEqual([{ recipient: recipient1 }, { recipient: recipient2 }]); }); it('should merge recipients from a group', () => { const result = recipientsToRecipientOrGroup([recipient3, recipient4], groupMap); expect(result).toEqual([{ group: { group: group1, recipients: [recipient3, recipient4] } }]); }); it('should split recipients from group and those not', () => { const result = recipientsToRecipientOrGroup([recipient2, recipient3], groupMap); expect(result).toEqual([{ recipient: recipient2 }, { group: { group: group1, recipients: [recipient3] } }]); }); it('should give up group from recipient if not in group list', () => { const result = recipientsToRecipientOrGroup([recipient5], groupMap); expect(result).toEqual([{ recipient: recipient5 }]); }); it('should return recipients if we do not want to display groups', () => { const result = recipientsToRecipientOrGroup([recipient3, recipient4, recipient5], groupMap, true); expect(result).toEqual([{ recipient: recipient3 }, { recipient: recipient4 }, { recipient: recipient5 }]); }); }); describe('getRecipientOrGroupLabel', () => { it('should return recipient address if it has no name', () => { const result = getRecipientLabel(recipient1, {}); expect(result).toEqual('address1'); }); it('should return recipient name if it exists', () => { const result = getRecipientLabel(recipient2, {}); expect(result).toEqual('recipient2'); }); it('should return group label', () => { const result = getRecipientGroupLabel({ group: group1, recipients: [] }, 0); expect(result).toEqual('GroupName1 (0/0 members)'); }); it('should compute group size with contact list', () => { const result = getRecipientGroupLabel({ group: group1, recipients: [recipient3, recipient4] }, 8); expect(result).toEqual('GroupName1 (2/8 members)'); }); }); describe('getNumParticipants', () => { it('should not count same participant', () => { const sender: Recipient = { Name: 'Panda', Address: '[email protected]' }; const recipient1: Recipient = { Name: 'Panda', Address: '[email protected]' }; const recipient2: Recipient = { Name: 'Panda', Address: '[email protected]' }; const recipient3: Recipient = { Name: 'Panda', Address: '[email protected]' }; const conversation: Element = { ID: 'conversationID', Senders: [sender], Recipients: [recipient1, recipient2, recipient3], }; const result = getNumParticipants(conversation); expect(result).toEqual(1); }); }); describe('getSendersToBlock', () => { // Message not present in SPAM or ALLOW or BLOCK list const toCreate = '[email protected]'; // Message from someone already in the SPAM list const toUpdateSpam = '[email protected]'; // Message from someone already in the ALLOW list const toUpdateInbox = '[email protected]'; // Message from someone already in the BLOCK list const alreadyBlocked = '[email protected]'; // Message sent to myself const me = '[email protected]'; // Message sent to myself from secondary address const me2 = '[email protected]'; const incomingDefaultsAddresses = [ { ID: '1', Email: toUpdateInbox, Location: INCOMING_DEFAULTS_LOCATION.INBOX } as IncomingDefault, { ID: '2', Email: toUpdateSpam, Location: INCOMING_DEFAULTS_LOCATION.SPAM } as IncomingDefault, { ID: '3', Email: alreadyBlocked, Location: INCOMING_DEFAULTS_LOCATION.BLOCKED } as IncomingDefault, ] as IncomingDefault[]; const addresses = [{ Email: me } as Address, { Email: me2 } as Address] as Address[]; const expectedSenders = [ { Address: toCreate } as Recipient, { Address: toUpdateSpam } as Recipient, { Address: toUpdateInbox } as Recipient, ]; it('should return expected senders to block from messages', () => { const elements = [ { Sender: { Address: toCreate } as Recipient, ConversationID: '1' } as Message, { Sender: { Address: toUpdateSpam } as Recipient, ConversationID: '2' } as Message, { Sender: { Address: toUpdateInbox } as Recipient, ConversationID: '3' } as Message, // Put one 2 times to check that it will not be called 2 times { Sender: { Address: toUpdateInbox } as Recipient, ConversationID: '4' } as Message, { Sender: { Address: alreadyBlocked } as Recipient, ConversationID: '5' } as Message, { Sender: { Address: me } as Recipient, ConversationID: '6' } as Message, { Sender: { Address: me2 } as Recipient, ConversationID: '7' } as Message, ] as Element[]; const senders = getSendersToBlock(elements, incomingDefaultsAddresses, addresses); expect(senders).toEqual(expectedSenders); }); it('should return expected senders to block from conversation', () => { const elements = [ { Senders: [{ Address: toCreate } as Recipient] } as Conversation, { Senders: [{ Address: toUpdateSpam } as Recipient] } as Conversation, { Senders: [{ Address: toUpdateInbox } as Recipient] } as Conversation, // Put one 2 times to check that it will not be called 2 times { Senders: [{ Address: toUpdateInbox } as Recipient] } as Conversation, { Senders: [{ Address: alreadyBlocked } as Recipient] } as Conversation, { Senders: [{ Address: me } as Recipient] } as Conversation, { Senders: [{ Address: me2 } as Recipient] } as Conversation, ] as Element[]; const senders = getSendersToBlock(elements, incomingDefaultsAddresses, addresses); expect(senders).toEqual(expectedSenders); }); }); describe('getRecipients', () => { it.each` replyType | isSentMessage ${MESSAGE_ACTIONS.REPLY} | ${true} ${MESSAGE_ACTIONS.REPLY} | ${false} ${MESSAGE_ACTIONS.REPLY_ALL} | ${true} ${MESSAGE_ACTIONS.REPLY_ALL} | ${false} `('should give the expected recipients', ({ replyType, isSentMessage }) => { const referenceMessage = { data: { ReplyTos: isSentMessage ? [recipients.meRecipient] : [recipients.fromRecipient], ToList: isSentMessage ? [recipients.toRecipient] : [recipients.meRecipient, recipients.toRecipient], CCList: [recipients.ccRecipient], BCCList: [recipients.bccRecipient], Flags: isSentMessage ? MESSAGE_FLAGS.FLAG_SENT : MESSAGE_FLAGS.FLAG_RECEIVED, } as Partial<Message>, } as MessageState; const addresses = [{ DisplayName: fromFields.meName, Email: fromFields.meAddress } as Address]; const { ToList, CCList, BCCList } = getRecipients(referenceMessage, replyType, addresses); if (replyType === MESSAGE_ACTIONS.REPLY) { if (isSentMessage) { expect(ToList).toEqual([recipients.toRecipient]); expect(CCList).toEqual([]); expect(BCCList).toEqual([]); } else { expect(ToList).toEqual([recipients.fromRecipient]); expect(CCList).toEqual([]); expect(BCCList).toEqual([]); } } else { if (isSentMessage) { expect(ToList).toEqual([recipients.toRecipient]); expect(CCList).toEqual([recipients.ccRecipient]); expect(BCCList).toEqual([recipients.bccRecipient]); } else { expect(ToList).toEqual([recipients.fromRecipient]); expect(CCList).toEqual([recipients.toRecipient, recipients.ccRecipient]); expect(BCCList).toEqual([]); } } }); }); describe('getReplyRecipientListAsString', () => { it.each` replyType | isSentMessage ${MESSAGE_ACTIONS.REPLY} | ${true} ${MESSAGE_ACTIONS.REPLY} | ${false} ${MESSAGE_ACTIONS.REPLY_ALL} | ${true} ${MESSAGE_ACTIONS.REPLY_ALL} | ${false} `('should give the expected recipient string', ({ replyType, isSentMessage }) => { const referenceMessage = { data: { ReplyTos: isSentMessage ? [recipients.meRecipient] : [recipients.fromRecipient], ToList: isSentMessage ? [recipients.toRecipient] : [recipients.meRecipient, recipients.toRecipient], CCList: [recipients.ccRecipient], BCCList: [recipients.bccRecipient], Flags: isSentMessage ? MESSAGE_FLAGS.FLAG_SENT : MESSAGE_FLAGS.FLAG_RECEIVED, } as Partial<Message>, } as MessageState; const addresses = [{ DisplayName: fromFields.meName, Email: fromFields.meAddress } as Address]; const fromCustomName = 'From contact name'; const contactsMap: SimpleMap<ContactEmail> = { '[email protected]': { Email: fromFields.fromAddress, Name: fromCustomName, } as ContactEmail, }; const recipientsString = getReplyRecipientListAsString(referenceMessage, replyType, addresses, contactsMap); if (replyType === MESSAGE_ACTIONS.REPLY) { if (isSentMessage) { expect(recipientsString).toEqual('To'); } else { expect(recipientsString).toEqual(`${fromCustomName}`); } } else { if (isSentMessage) { expect(recipientsString).toEqual('To, CC, BCC'); } else { expect(recipientsString).toEqual(`${fromCustomName}, To, CC`); } } }); }); });
3,889
0
petrpan-code/ProtonMail/WebClients/applications/mail/src/app/helpers
petrpan-code/ProtonMail/WebClients/applications/mail/src/app/helpers/message/messageRemotes.test.ts
import { MessageRemoteImage } from '../../logic/messages/messagesTypes'; import { createDocument } from '../test/message'; import { loadBackgroundImages, loadImages } from './messageRemotes'; describe('messageRemote', () => { describe('loadImages', () => { const imageURL = 'ImageURL'; const originalURL = 'originalURL'; const backgroundContent = `<div> <table> <tbody> <tr> <td proton-background='${originalURL}'>Element1</td> </tr> </tbody> </table> </div>`; const backgroundExpectedContent = `<div> <table> <tbody> <tr> <td proton-background='${originalURL}' background='${imageURL}'>Element1</td> </tr> </tbody> </table> </div>`; const posterContent = `<div> <video proton-poster='${originalURL}'> <source src="" type="video/mp4"> </video> </div>`; const posterExpectedContent = `<div> <video proton-poster='${originalURL}' poster='${imageURL}'> <source src="" type="video/mp4"> </video> </div>`; const xlinkhrefContent = `<div> <svg width="90" height="90"> <image proton-xlink:href='${originalURL}'/> </svg> </div>`; const xlinkhrefExpectedContent = `<div> <svg width="90" height="90"> <image proton-xlink:href='${originalURL}' xlink:href='${imageURL}'/> </svg> </div>`; const srcsetContent = `<div> <picture> <source media="(min-width:650px)" proton-srcset='${originalURL}' > <img src='${imageURL}' > </picture> </div>`; const srcsetExpectedContent = `<div> <picture> <source media="(min-width:650px)" proton-srcset='${originalURL}' > <img src='${imageURL}' > </picture> </div>`; it.each` content | expectedContent ${backgroundContent} | ${backgroundExpectedContent} ${posterContent} | ${posterExpectedContent} ${xlinkhrefContent} | ${xlinkhrefExpectedContent} `('should load elements other than images', async ({ content, expectedContent }) => { const messageDocument = createDocument(content); const remoteImages = [ { type: 'remote', url: imageURL, originalURL, id: 'remote-0', tracker: undefined, status: 'loaded', }, ] as MessageRemoteImage[]; loadImages(remoteImages, messageDocument); const expectedDocument = createDocument(expectedContent); expect(messageDocument.innerHTML).toEqual(expectedDocument.innerHTML); }); it('should not load srcset attribute', () => { const messageDocument = createDocument(srcsetContent); const remoteImages = [ { type: 'remote', url: imageURL, originalURL, id: 'remote-0', tracker: undefined, status: 'loaded', }, ] as MessageRemoteImage[]; loadImages(remoteImages, messageDocument); const expectedDocument = createDocument(srcsetExpectedContent); expect(messageDocument.innerHTML).toEqual(expectedDocument.innerHTML); }); }); describe('loadBackgroundImages', () => { const imageURL = 'http://test.fr/img.jpg'; const content = `<div style="background: proton-url(${imageURL})">Element1</div>`; const expectedContent = `<div style="background: url(${imageURL})">Element1</div>`; it('should load elements other than images', async () => { const messageDocument = createDocument(content); const expectedDocument = createDocument(expectedContent); const remoteImages = [ { type: 'remote', url: imageURL, originalURL: imageURL, id: 'remote-0', tracker: undefined, status: 'loaded', }, ] as MessageRemoteImage[]; loadBackgroundImages({ images: remoteImages, document: messageDocument }); expect(messageDocument.innerHTML).toEqual(expectedDocument.innerHTML); }); }); });
3,891
0
petrpan-code/ProtonMail/WebClients/applications/mail/src/app/helpers
petrpan-code/ProtonMail/WebClients/applications/mail/src/app/helpers/message/messageSignature.test.ts
import { MailSettings, UserSettings } from '@proton/shared/lib/interfaces'; import { PM_SIGNATURE as PM_SIGNATURE_ENUM } from '@proton/shared/lib/mail/mailSettings'; import { getProtonMailSignature } from '@proton/shared/lib/mail/signature'; import { message } from '@proton/shared/lib/sanitize'; import { MESSAGE_ACTIONS } from '../../constants'; import { CLASSNAME_SIGNATURE_CONTAINER, CLASSNAME_SIGNATURE_EMPTY, CLASSNAME_SIGNATURE_USER, insertSignature, } from './messageSignature'; const content = '<p>test</p>'; const signature = ` <strong>>signature</strong>`; const mailSettings = { PMSignature: PM_SIGNATURE_ENUM.DISABLED } as MailSettings; const userSettings = {} as UserSettings; const PM_SIGNATURE = getProtonMailSignature(); describe('signature', () => { afterEach(() => { jest.clearAllMocks(); }); describe('insertSignature', () => { describe('rules', () => { it('should remove line breaks', () => { const result = insertSignature( content, signature, MESSAGE_ACTIONS.NEW, mailSettings, userSettings, undefined, false ); expect(result).toContain('<br><strong>'); }); it('should try to clean the signature', () => { const result = insertSignature( content, signature, MESSAGE_ACTIONS.NEW, mailSettings, userSettings, undefined, false ); expect(result).toContain('&gt;'); }); it('should add empty line before the signature', () => { const result = insertSignature( content, '', MESSAGE_ACTIONS.NEW, mailSettings, userSettings, undefined, false ); expect(result).toMatch(new RegExp(`<div><br></div>\\s*<div class="${CLASSNAME_SIGNATURE_CONTAINER}`)); }); it('should add different number of empty lines depending on the action', () => { let result = insertSignature( content, '', MESSAGE_ACTIONS.NEW, mailSettings, userSettings, undefined, false ); expect((result.match(/<div><br><\/div>/g) || []).length).toBe(1); result = insertSignature( content, '', MESSAGE_ACTIONS.REPLY, mailSettings, userSettings, undefined, false ); expect((result.match(/<div><br><\/div>/g) || []).length).toBe(2); result = insertSignature( content, '', MESSAGE_ACTIONS.REPLY, { ...mailSettings, PMSignature: PM_SIGNATURE_ENUM.ENABLED }, userSettings, undefined, false ); expect((result.match(/<div><br><\/div>/g) || []).length).toBe(3); result = insertSignature( content, signature, MESSAGE_ACTIONS.REPLY, mailSettings, userSettings, undefined, false ); expect((result.match(/<div><br><\/div>/g) || []).length).toBe(3); result = insertSignature( content, signature, MESSAGE_ACTIONS.REPLY, { ...mailSettings, PMSignature: PM_SIGNATURE_ENUM.ENABLED }, userSettings, undefined, false ); expect((result.match(/<div><br><\/div>/g) || []).length).toBe(4); }); it('should append PM signature depending mailsettings', () => { let result = insertSignature(content, '', MESSAGE_ACTIONS.NEW, mailSettings, {}, undefined, false); expect(result).not.toContain(PM_SIGNATURE); result = insertSignature( content, '', MESSAGE_ACTIONS.NEW, { ...mailSettings, PMSignature: PM_SIGNATURE_ENUM.ENABLED }, userSettings, undefined, false ); const sanitizedPmSignature = message(PM_SIGNATURE); expect(result).toContain(sanitizedPmSignature); let messagePosition = result.indexOf(content); let signaturePosition = result.indexOf(sanitizedPmSignature); expect(messagePosition).toBeGreaterThan(signaturePosition); result = insertSignature( content, '', MESSAGE_ACTIONS.NEW, { ...mailSettings, PMSignature: PM_SIGNATURE_ENUM.ENABLED }, userSettings, undefined, true ); messagePosition = result.indexOf(content); signaturePosition = result.indexOf(sanitizedPmSignature); expect(messagePosition).toBeLessThan(signaturePosition); }); it('should append user signature if exists', () => { let result = insertSignature( content, '', MESSAGE_ACTIONS.NEW, mailSettings, userSettings, undefined, false ); expect(result).toContain(`${CLASSNAME_SIGNATURE_USER} ${CLASSNAME_SIGNATURE_EMPTY}`); result = insertSignature( content, signature, MESSAGE_ACTIONS.NEW, mailSettings, userSettings, undefined, false ); expect(result).toContain('signature'); let messagePosition = result.indexOf(content); let signaturePosition = result.indexOf(signature); expect(messagePosition).toBeGreaterThan(signaturePosition); result = insertSignature( content, signature, MESSAGE_ACTIONS.NEW, mailSettings, userSettings, undefined, true ); messagePosition = result.indexOf(content); signaturePosition = result.indexOf('signature'); expect(messagePosition).toBeLessThan(signaturePosition); }); }); describe('snapshots', () => { const protonSignatures = [false, true]; const userSignatures = [false, true]; const actions = [ MESSAGE_ACTIONS.NEW, MESSAGE_ACTIONS.REPLY, MESSAGE_ACTIONS.REPLY_ALL, MESSAGE_ACTIONS.FORWARD, ]; const isAfters = [false, true]; protonSignatures.forEach((protonSignature) => { userSignatures.forEach((userSignature) => { actions.forEach((action) => { isAfters.forEach((isAfter) => { const label = `should match with protonSignature ${protonSignature}, userSignature ${userSignature}, action ${action}, isAfter ${isAfter}`; it(label, () => { const result = insertSignature( content, userSignature ? signature : '', action, { PMSignature: protonSignature ? PM_SIGNATURE_ENUM.ENABLED : PM_SIGNATURE_ENUM.DISABLED, } as MailSettings, userSettings, undefined, isAfter ); expect(result).toMatchSnapshot(); }); }); }); }); }); }); }); });
3,893
0
petrpan-code/ProtonMail/WebClients/applications/mail/src/app/helpers
petrpan-code/ProtonMail/WebClients/applications/mail/src/app/helpers/message/messages.test.ts
import { MAILBOX_LABEL_IDS } from '@proton/shared/lib/constants'; import { Message } from '@proton/shared/lib/interfaces/mail/Message'; import { getRecipients, getSender } from '@proton/shared/lib/mail/messages'; import { MessageImage, MessageImages } from '../../logic/messages/messagesTypes'; import { getAttachmentCounts, getMessagesAuthorizedToMove } from './messages'; const { INBOX, SENT, DRAFTS, TRASH, SPAM } = MAILBOX_LABEL_IDS; describe('message', () => { describe('getSender', () => { it('should return Sender', () => { const message = { Sender: { Name: 'Name', Address: 'Address' } } as Message; expect(getSender(message)).toBe(message.Sender); }); }); describe('getRecipients', () => { it('should return Name over Address', () => { const message = { ToList: [{ Name: 'Name', Address: 'Address' }] } as Message; expect(getRecipients(message)).toEqual([message.ToList[0]]); }); it('should return recipients from all kinds', () => { const message = { ToList: [{ Name: 'Name1' }], CCList: [{ Address: 'Address2' }], BCCList: [{ Name: 'Name3' }], } as Message; expect(getRecipients(message)).toEqual([message.ToList[0], message.CCList[0], message.BCCList[0]]); }); }); describe('getMessagesAuthorizedToMove', () => { const inboxMessage = { ID: '0', LabelIDs: [INBOX], Flags: 1 } as Message; const sentMessage = { ID: '1', LabelIDs: [SENT], Flags: 2 } as Message; const draftMessage = { ID: '2', LabelIDs: [DRAFTS], Flags: 0 } as Message; it('should return messages authorized to move', () => { expect(getMessagesAuthorizedToMove([inboxMessage, sentMessage, draftMessage], INBOX)).toEqual([ inboxMessage, ]); expect(getMessagesAuthorizedToMove([inboxMessage, sentMessage, draftMessage], SENT)).toEqual([sentMessage]); expect(getMessagesAuthorizedToMove([inboxMessage, sentMessage, draftMessage], DRAFTS)).toEqual([ draftMessage, ]); }); it('should move all to trash', () => { expect(getMessagesAuthorizedToMove([inboxMessage, sentMessage, draftMessage], TRASH)).toEqual([ inboxMessage, sentMessage, draftMessage, ]); }); it('should authorize move to Inbox when message is sent to himself', () => { const message = { ID: '0', LabelIDs: [SENT], Flags: 3 } as Message; expect(getMessagesAuthorizedToMove([message], INBOX)).toEqual([message]); }); it('should not move Sent and Draft messages to Spam', () => { expect(getMessagesAuthorizedToMove([inboxMessage, sentMessage, draftMessage], SPAM)).toEqual([ inboxMessage, ]); }); }); describe('getAttachmentCounts', () => { const attachment1 = { ID: '0' }; const attachment2 = { ID: '1' }; const attachment3 = { ID: '2' }; const messageImage1 = { type: 'embedded', attachment: attachment1 }; const messageImage2 = { type: 'embedded', attachment: attachment2 }; const messageImage3 = { type: 'embedded', attachment: attachment2 }; // image 3 use attachment 2 const messageImage4 = { type: 'embedded', attachment: attachment2 }; // image 4 use attachment 2 it('should count only pure attachments', () => { const { pureAttachmentsCount, embeddedAttachmentsCount, attachmentsCount } = getAttachmentCounts( [attachment1], { images: [] as MessageImage[] } as MessageImages ); expect(pureAttachmentsCount).toBe(1); expect(embeddedAttachmentsCount).toBe(0); expect(attachmentsCount).toBe(1); }); it('should count only embedded images', () => { const { pureAttachmentsCount, embeddedAttachmentsCount, attachmentsCount } = getAttachmentCounts( [attachment1], { images: [messageImage1] } as MessageImages ); expect(pureAttachmentsCount).toBe(0); expect(embeddedAttachmentsCount).toBe(1); expect(attachmentsCount).toBe(1); }); it('should count mixed attachments', () => { const { pureAttachmentsCount, embeddedAttachmentsCount, attachmentsCount } = getAttachmentCounts( [attachment1, attachment2, attachment3], { images: [messageImage1, messageImage2] } as MessageImages ); expect(pureAttachmentsCount).toBe(1); expect(embeddedAttachmentsCount).toBe(2); expect(attachmentsCount).toBe(3); }); it('should deal with single attachment used for several embeddeds', () => { const { pureAttachmentsCount, embeddedAttachmentsCount, attachmentsCount } = getAttachmentCounts( [attachment1, attachment2, attachment3], { images: [messageImage1, messageImage2, messageImage3, messageImage4] } as MessageImages ); expect(pureAttachmentsCount).toBe(1); expect(embeddedAttachmentsCount).toBe(2); expect(attachmentsCount).toBe(3); }); }); });
3,895
0
petrpan-code/ProtonMail/WebClients/applications/mail/src/app/helpers
petrpan-code/ProtonMail/WebClients/applications/mail/src/app/helpers/message/trackers.test.tsx
import { MessageUTMTracker } from '@proton/shared/lib/models/mailUtmTrackers'; import { Tracker } from '../../hooks/message/useMessageTrackers'; import { MessageImage, MessageImages, MessageState } from '../../logic/messages/messagesTypes'; import { createDocument } from '../test/message'; import { getImageTrackersFromMessage, getUTMTrackersFromMessage } from './trackers'; const tracker1Url = 'http://tracker.com'; const tracker2Url = 'http://tracking.com'; const tracker3Url = 'http://trackerInBlockQuote.com'; const tracker4Url = 'http://Tracker.com'; const utmTracker1 = 'http://tracker.com?utm_source=tracker'; const utmTracker2 = 'http://tracking.com?utm_source=tracking&utm_content=tracking'; const document = ` <div> <div> Here is some mail content <img src="${tracker1Url}" alt="" data-proton-remote="1"/> <img src="${tracker1Url}" alt="" data-proton-remote="2"/> <img src="${tracker2Url}" alt="" data-proton-remote="3"/> <img src="${tracker4Url}" alt="" data-proton-remote="5"/> </div> <blockquote class="protonmail_quote" type="cite"> Here is some blockquote content <img src="${tracker3Url}" alt="" data-proton-remote="4"/> </blockquote> </div>`; const message = { messageImages: { images: [ { type: 'remote', id: '1', originalURL: `${tracker1Url}/tracker-1`, url: `${tracker1Url}/tracker-1`, tracker: tracker1Url, }, { type: 'remote', id: '2', originalURL: `${tracker1Url}/tracker-2`, url: `${tracker1Url}/tracker-2`, tracker: tracker1Url, }, { type: 'embedded', id: '3', cloc: `${tracker2Url}/tracker`, tracker: tracker2Url, }, ] as MessageImage[], } as MessageImages, messageDocument: { document: createDocument(document), }, messageUTMTrackers: [ { originalURL: utmTracker1, cleanedURL: tracker1Url, removed: [{ key: 'utm_source', value: 'tracker' }], }, { originalURL: utmTracker2, cleanedURL: tracker2Url, removed: [ { key: 'utm_source', value: 'tracking' }, { key: 'utm_content', value: 'tracking' }, ], }, ] as MessageUTMTracker[], } as MessageState; describe('trackers', () => { describe('getImageTrackersFromMessage', () => { it('should return the expected image trackers', () => { const { trackers, numberOfTrackers } = getImageTrackersFromMessage(message); const expectedTrackers: Tracker[] = [ { name: tracker1Url, urls: [`${tracker1Url}/tracker-1`, `${tracker1Url}/tracker-2`] }, { name: tracker2Url, urls: [`${tracker2Url}/tracker`] }, ]; expect(trackers).toEqual(expectedTrackers); expect(numberOfTrackers).toEqual(3); }); }); describe('getImageTrackersFromMessage', () => { it('should return expected utm trackers', () => { const { trackers, numberOfTrackers } = getUTMTrackersFromMessage(message); const expectedTrackers = [ { originalURL: utmTracker1, cleanedURL: tracker1Url, removed: [{ key: 'utm_source', value: 'tracker' }], }, { originalURL: utmTracker2, cleanedURL: tracker2Url, removed: [ { key: 'utm_source', value: 'tracking' }, { key: 'utm_content', value: 'tracking' }, ], }, ]; expect(trackers).toEqual(expectedTrackers); expect(numberOfTrackers).toEqual(2); }); }); });
3,899
0
petrpan-code/ProtonMail/WebClients/applications/mail/src/app/helpers/message
petrpan-code/ProtonMail/WebClients/applications/mail/src/app/helpers/message/__snapshots__/messageSignature.test.ts.snap
// Jest Snapshot v1, https://goo.gl/fbAQLP exports[`signature insertSignature snapshots should match with protonSignature false, userSignature false, action -1, isAfter false 1`] = ` "<div><br></div> <div class="protonmail_signature_block protonmail_signature_block-empty"> <div class="protonmail_signature_block-user protonmail_signature_block-empty"> </div> <div class="protonmail_signature_block-proton protonmail_signature_block-empty"> </div> </div> <p>test</p>" `; exports[`signature insertSignature snapshots should match with protonSignature false, userSignature false, action -1, isAfter true 1`] = ` "<p>test</p><div><br></div> <div class="protonmail_signature_block protonmail_signature_block-empty"> <div class="protonmail_signature_block-user protonmail_signature_block-empty"> </div> <div class="protonmail_signature_block-proton protonmail_signature_block-empty"> </div> </div> " `; exports[`signature insertSignature snapshots should match with protonSignature false, userSignature false, action 0, isAfter false 1`] = ` "<div><br></div> <div class="protonmail_signature_block protonmail_signature_block-empty"> <div class="protonmail_signature_block-user protonmail_signature_block-empty"> </div> <div class="protonmail_signature_block-proton protonmail_signature_block-empty"> </div> </div> <div><br></div><p>test</p>" `; exports[`signature insertSignature snapshots should match with protonSignature false, userSignature false, action 0, isAfter true 1`] = ` "<p>test</p><div><br></div> <div class="protonmail_signature_block protonmail_signature_block-empty"> <div class="protonmail_signature_block-user protonmail_signature_block-empty"> </div> <div class="protonmail_signature_block-proton protonmail_signature_block-empty"> </div> </div> <div><br></div>" `; exports[`signature insertSignature snapshots should match with protonSignature false, userSignature false, action 1, isAfter false 1`] = ` "<div><br></div> <div class="protonmail_signature_block protonmail_signature_block-empty"> <div class="protonmail_signature_block-user protonmail_signature_block-empty"> </div> <div class="protonmail_signature_block-proton protonmail_signature_block-empty"> </div> </div> <div><br></div><p>test</p>" `; exports[`signature insertSignature snapshots should match with protonSignature false, userSignature false, action 1, isAfter true 1`] = ` "<p>test</p><div><br></div> <div class="protonmail_signature_block protonmail_signature_block-empty"> <div class="protonmail_signature_block-user protonmail_signature_block-empty"> </div> <div class="protonmail_signature_block-proton protonmail_signature_block-empty"> </div> </div> <div><br></div>" `; exports[`signature insertSignature snapshots should match with protonSignature false, userSignature false, action 2, isAfter false 1`] = ` "<div><br></div> <div class="protonmail_signature_block protonmail_signature_block-empty"> <div class="protonmail_signature_block-user protonmail_signature_block-empty"> </div> <div class="protonmail_signature_block-proton protonmail_signature_block-empty"> </div> </div> <div><br></div><p>test</p>" `; exports[`signature insertSignature snapshots should match with protonSignature false, userSignature false, action 2, isAfter true 1`] = ` "<p>test</p><div><br></div> <div class="protonmail_signature_block protonmail_signature_block-empty"> <div class="protonmail_signature_block-user protonmail_signature_block-empty"> </div> <div class="protonmail_signature_block-proton protonmail_signature_block-empty"> </div> </div> <div><br></div>" `; exports[`signature insertSignature snapshots should match with protonSignature false, userSignature true, action -1, isAfter false 1`] = ` "<div><br></div><div><br></div> <div class="protonmail_signature_block"> <div class="protonmail_signature_block-user"> <br><strong>&gt;signature</strong> </div> <div class="protonmail_signature_block-proton protonmail_signature_block-empty"> </div> </div> <p>test</p>" `; exports[`signature insertSignature snapshots should match with protonSignature false, userSignature true, action -1, isAfter true 1`] = ` "<p>test</p><div><br></div><div><br></div> <div class="protonmail_signature_block"> <div class="protonmail_signature_block-user"> <br><strong>&gt;signature</strong> </div> <div class="protonmail_signature_block-proton protonmail_signature_block-empty"> </div> </div> " `; exports[`signature insertSignature snapshots should match with protonSignature false, userSignature true, action 0, isAfter false 1`] = ` "<div><br></div><div><br></div> <div class="protonmail_signature_block"> <div class="protonmail_signature_block-user"> <br><strong>&gt;signature</strong> </div> <div class="protonmail_signature_block-proton protonmail_signature_block-empty"> </div> </div> <div><br></div><p>test</p>" `; exports[`signature insertSignature snapshots should match with protonSignature false, userSignature true, action 0, isAfter true 1`] = ` "<p>test</p><div><br></div><div><br></div> <div class="protonmail_signature_block"> <div class="protonmail_signature_block-user"> <br><strong>&gt;signature</strong> </div> <div class="protonmail_signature_block-proton protonmail_signature_block-empty"> </div> </div> <div><br></div>" `; exports[`signature insertSignature snapshots should match with protonSignature false, userSignature true, action 1, isAfter false 1`] = ` "<div><br></div><div><br></div> <div class="protonmail_signature_block"> <div class="protonmail_signature_block-user"> <br><strong>&gt;signature</strong> </div> <div class="protonmail_signature_block-proton protonmail_signature_block-empty"> </div> </div> <div><br></div><p>test</p>" `; exports[`signature insertSignature snapshots should match with protonSignature false, userSignature true, action 1, isAfter true 1`] = ` "<p>test</p><div><br></div><div><br></div> <div class="protonmail_signature_block"> <div class="protonmail_signature_block-user"> <br><strong>&gt;signature</strong> </div> <div class="protonmail_signature_block-proton protonmail_signature_block-empty"> </div> </div> <div><br></div>" `; exports[`signature insertSignature snapshots should match with protonSignature false, userSignature true, action 2, isAfter false 1`] = ` "<div><br></div><div><br></div> <div class="protonmail_signature_block"> <div class="protonmail_signature_block-user"> <br><strong>&gt;signature</strong> </div> <div class="protonmail_signature_block-proton protonmail_signature_block-empty"> </div> </div> <div><br></div><p>test</p>" `; exports[`signature insertSignature snapshots should match with protonSignature false, userSignature true, action 2, isAfter true 1`] = ` "<p>test</p><div><br></div><div><br></div> <div class="protonmail_signature_block"> <div class="protonmail_signature_block-user"> <br><strong>&gt;signature</strong> </div> <div class="protonmail_signature_block-proton protonmail_signature_block-empty"> </div> </div> <div><br></div>" `; exports[`signature insertSignature snapshots should match with protonSignature true, userSignature false, action -1, isAfter false 1`] = ` "<div><br></div><div><br></div> <div class="protonmail_signature_block"> <div class="protonmail_signature_block-user protonmail_signature_block-empty"> </div> <div class="protonmail_signature_block-proton"> Sent with <a target="_blank" href="https://proton.me/">Proton Mail</a> secure email. </div> </div> <p>test</p>" `; exports[`signature insertSignature snapshots should match with protonSignature true, userSignature false, action -1, isAfter true 1`] = ` "<p>test</p><div><br></div><div><br></div> <div class="protonmail_signature_block"> <div class="protonmail_signature_block-user protonmail_signature_block-empty"> </div> <div class="protonmail_signature_block-proton"> Sent with <a target="_blank" href="https://proton.me/">Proton Mail</a> secure email. </div> </div> " `; exports[`signature insertSignature snapshots should match with protonSignature true, userSignature false, action 0, isAfter false 1`] = ` "<div><br></div><div><br></div> <div class="protonmail_signature_block"> <div class="protonmail_signature_block-user protonmail_signature_block-empty"> </div> <div class="protonmail_signature_block-proton"> Sent with <a target="_blank" href="https://proton.me/">Proton Mail</a> secure email. </div> </div> <div><br></div><p>test</p>" `; exports[`signature insertSignature snapshots should match with protonSignature true, userSignature false, action 0, isAfter true 1`] = ` "<p>test</p><div><br></div><div><br></div> <div class="protonmail_signature_block"> <div class="protonmail_signature_block-user protonmail_signature_block-empty"> </div> <div class="protonmail_signature_block-proton"> Sent with <a target="_blank" href="https://proton.me/">Proton Mail</a> secure email. </div> </div> <div><br></div>" `; exports[`signature insertSignature snapshots should match with protonSignature true, userSignature false, action 1, isAfter false 1`] = ` "<div><br></div><div><br></div> <div class="protonmail_signature_block"> <div class="protonmail_signature_block-user protonmail_signature_block-empty"> </div> <div class="protonmail_signature_block-proton"> Sent with <a target="_blank" href="https://proton.me/">Proton Mail</a> secure email. </div> </div> <div><br></div><p>test</p>" `; exports[`signature insertSignature snapshots should match with protonSignature true, userSignature false, action 1, isAfter true 1`] = ` "<p>test</p><div><br></div><div><br></div> <div class="protonmail_signature_block"> <div class="protonmail_signature_block-user protonmail_signature_block-empty"> </div> <div class="protonmail_signature_block-proton"> Sent with <a target="_blank" href="https://proton.me/">Proton Mail</a> secure email. </div> </div> <div><br></div>" `; exports[`signature insertSignature snapshots should match with protonSignature true, userSignature false, action 2, isAfter false 1`] = ` "<div><br></div><div><br></div> <div class="protonmail_signature_block"> <div class="protonmail_signature_block-user protonmail_signature_block-empty"> </div> <div class="protonmail_signature_block-proton"> Sent with <a target="_blank" href="https://proton.me/">Proton Mail</a> secure email. </div> </div> <div><br></div><p>test</p>" `; exports[`signature insertSignature snapshots should match with protonSignature true, userSignature false, action 2, isAfter true 1`] = ` "<p>test</p><div><br></div><div><br></div> <div class="protonmail_signature_block"> <div class="protonmail_signature_block-user protonmail_signature_block-empty"> </div> <div class="protonmail_signature_block-proton"> Sent with <a target="_blank" href="https://proton.me/">Proton Mail</a> secure email. </div> </div> <div><br></div>" `; exports[`signature insertSignature snapshots should match with protonSignature true, userSignature true, action -1, isAfter false 1`] = ` "<div><br></div><div><br></div> <div class="protonmail_signature_block"> <div class="protonmail_signature_block-user"> <br><strong>&gt;signature</strong> </div> <div><br></div> <div class="protonmail_signature_block-proton"> Sent with <a target="_blank" href="https://proton.me/">Proton Mail</a> secure email. </div> </div> <p>test</p>" `; exports[`signature insertSignature snapshots should match with protonSignature true, userSignature true, action -1, isAfter true 1`] = ` "<p>test</p><div><br></div><div><br></div> <div class="protonmail_signature_block"> <div class="protonmail_signature_block-user"> <br><strong>&gt;signature</strong> </div> <div><br></div> <div class="protonmail_signature_block-proton"> Sent with <a target="_blank" href="https://proton.me/">Proton Mail</a> secure email. </div> </div> " `; exports[`signature insertSignature snapshots should match with protonSignature true, userSignature true, action 0, isAfter false 1`] = ` "<div><br></div><div><br></div> <div class="protonmail_signature_block"> <div class="protonmail_signature_block-user"> <br><strong>&gt;signature</strong> </div> <div><br></div> <div class="protonmail_signature_block-proton"> Sent with <a target="_blank" href="https://proton.me/">Proton Mail</a> secure email. </div> </div> <div><br></div><p>test</p>" `; exports[`signature insertSignature snapshots should match with protonSignature true, userSignature true, action 0, isAfter true 1`] = ` "<p>test</p><div><br></div><div><br></div> <div class="protonmail_signature_block"> <div class="protonmail_signature_block-user"> <br><strong>&gt;signature</strong> </div> <div><br></div> <div class="protonmail_signature_block-proton"> Sent with <a target="_blank" href="https://proton.me/">Proton Mail</a> secure email. </div> </div> <div><br></div>" `; exports[`signature insertSignature snapshots should match with protonSignature true, userSignature true, action 1, isAfter false 1`] = ` "<div><br></div><div><br></div> <div class="protonmail_signature_block"> <div class="protonmail_signature_block-user"> <br><strong>&gt;signature</strong> </div> <div><br></div> <div class="protonmail_signature_block-proton"> Sent with <a target="_blank" href="https://proton.me/">Proton Mail</a> secure email. </div> </div> <div><br></div><p>test</p>" `; exports[`signature insertSignature snapshots should match with protonSignature true, userSignature true, action 1, isAfter true 1`] = ` "<p>test</p><div><br></div><div><br></div> <div class="protonmail_signature_block"> <div class="protonmail_signature_block-user"> <br><strong>&gt;signature</strong> </div> <div><br></div> <div class="protonmail_signature_block-proton"> Sent with <a target="_blank" href="https://proton.me/">Proton Mail</a> secure email. </div> </div> <div><br></div>" `; exports[`signature insertSignature snapshots should match with protonSignature true, userSignature true, action 2, isAfter false 1`] = ` "<div><br></div><div><br></div> <div class="protonmail_signature_block"> <div class="protonmail_signature_block-user"> <br><strong>&gt;signature</strong> </div> <div><br></div> <div class="protonmail_signature_block-proton"> Sent with <a target="_blank" href="https://proton.me/">Proton Mail</a> secure email. </div> </div> <div><br></div><p>test</p>" `; exports[`signature insertSignature snapshots should match with protonSignature true, userSignature true, action 2, isAfter true 1`] = ` "<p>test</p><div><br></div><div><br></div> <div class="protonmail_signature_block"> <div class="protonmail_signature_block-user"> <br><strong>&gt;signature</strong> </div> <div><br></div> <div class="protonmail_signature_block-proton"> Sent with <a target="_blank" href="https://proton.me/">Proton Mail</a> secure email. </div> </div> <div><br></div>" `;
3,933
0
petrpan-code/ProtonMail/WebClients/applications/mail/src/app/helpers/transforms
petrpan-code/ProtonMail/WebClients/applications/mail/src/app/helpers/transforms/tests/transformBase.test.ts
import range from '@proton/utils/range'; import { transformBase } from '../transformBase'; describe('transformBase service', () => { const URL_PROTON = 'https://proton.me'; const URL_PROTON_SLASH = 'https://proton.me/'; const LINKS = { linkRelative: '/monique', linkRelative2: '/robert', linkRelative3: 'roberts', imgRelative: '/monique.jpg', imgRelative2: '/robert.jpg', imgRelative3: 'robert3.jpg', linkAbsolutehttp: 'http://cpp.li/monique', linkAbsolutehttps: 'https://cpp.li/monique2', imgAbsolute: 'http://cpp.li/robert3.jpg', imgAbsolute2: 'https://cpp.li/robert3.jpg', imgCID: 'cid:xxxxx', imghttp: 'https://cpp.li/robert3.jpg', ahttp: 'https://cpp.li/', mailto: 'mailto:[email protected]', }; const DOM = ` <section> <a href="${LINKS.linkRelative}" id="linkRelative" class="link-relative">Monique</a> <a href="${LINKS.linkRelative2}" id="linkRelative2" class="link-relative">Robert</a> <a href="${LINKS.linkRelative3}" id="linkRelative3" class="link-relative">Roberts</a> <a href="${LINKS.linkAbsolutehttp}" id="linkAbsolutehttp" class="link-absolute">Monique</a> <a href="${LINKS.linkAbsolutehttps}" id="linkAbsolutehttps" class="link-absolute">Monique</a> <a class="link-empty" id="linkNope">Nope</a> <img src="${LINKS.imgRelative}" id="imgRelative" class="img-relative"> <img src="${LINKS.imgRelative2}" id="imgRelative2" class="img-relative"> <img src="${LINKS.imgRelative3}" id="imgRelative3" class="img-relative"> <img src="${LINKS.imgAbsolute}" id="imgAbsolute" class="img-absolute"> <img src="${LINKS.imgAbsolute2}" id="imgAbsolute2" class="img-absolute"> <img class="img-empty" id="imgNope"> <img proton-src="${LINKS.imgCID}" alt="" id="imgcid" /> <img src="${LINKS.imghttp}" alt="" id="imghttp" /> <a href="${LINKS.ahttp}" id="ahttp">dew</a> <a href="${LINKS.mailto}" id="mailto">Mailto</a> </section `; const DEFAULT_DOMAIN = 'http://lol.com'; const setup = (path = DEFAULT_DOMAIN) => { const doc = document.implementation.createHTMLDocument('test transformBase'); const base = document.createElement('BASE') as HTMLBaseElement; base.href = path; doc.head.appendChild(base); doc.body.innerHTML = DOM; transformBase(doc.documentElement); const querySelector = (selectors: string) => doc.querySelector(selectors); const querySelectorAll = (selectors: string) => [...doc.querySelectorAll(selectors)]; return { document: doc, querySelector, querySelectorAll }; }; describe('Remove base tag', () => { it('should remove base tag from the head', () => { const { querySelectorAll } = setup(); expect(querySelectorAll('base').length).toBe(0); }); it('should remove multiple base tag from the head', () => { const doc = document.implementation.createHTMLDocument('test transformBase'); range(0, 5).forEach((index) => { const base = document.createElement('BASE') as HTMLBaseElement; base.href = `https://something.com/${index}/`; doc.head.appendChild(base); }); doc.body.innerHTML = DOM; transformBase(doc.documentElement); expect(doc.querySelectorAll('base').length).toBe(0); }); }); describe('Escape base relative no slash', () => { describe('For a link', () => { const getLinks = (type = 'relative') => { const { querySelectorAll } = setup(URL_PROTON); return querySelectorAll(`.link-${type}`).map((element) => (element as HTMLLinkElement).href); }; it('should prepend the base into href', () => { const [link1, link2, link3] = getLinks(); expect(link1).toContain(URL_PROTON); expect(link2).toContain(URL_PROTON); expect(link3).toContain(URL_PROTON); }); it('should prepend the base into href without breaking the path', () => { const [link1, link2] = getLinks(); expect(link1).toBe(URL_PROTON + LINKS.linkRelative); expect(link2).toBe(URL_PROTON + LINKS.linkRelative2); }); it('should prepend the base into href with a slash', () => { const [, , link3] = getLinks(); expect(link3).toBe(`${URL_PROTON}/${LINKS.linkRelative3}`); }); it('should bind a href if there is not', () => { const { querySelector } = setup(URL_PROTON); const nope = querySelector('#linkNope') as HTMLLinkElement; expect(nope.href).toBe(`${URL_PROTON}/`); }); it('should not change the HREF for a link with already http', () => { const { querySelector } = setup(URL_PROTON); const nope = querySelector('#ahttp') as HTMLLinkElement; expect(nope.href).toBe(LINKS.ahttp); }); }); describe('For an image', () => { const getImages = (type = 'relative') => { const { querySelectorAll } = setup(URL_PROTON); return querySelectorAll(`.img-${type}`).map((element) => (element as HTMLImageElement).src); }; it('should prepend the base into href', () => { const [img1, img2, img3] = getImages(); expect(img1).toContain(URL_PROTON); expect(img2).toContain(URL_PROTON); expect(img3).toContain(URL_PROTON); }); it('should prepend the base into src without breaking the path', () => { const [img1, img2] = getImages(); expect(img1).toBe(URL_PROTON + LINKS.imgRelative); expect(img2).toBe(URL_PROTON + LINKS.imgRelative2); }); it('should prepend the base into src with a slash', () => { const [, , img3] = getImages(); expect(img3).toBe(`${URL_PROTON}/${LINKS.imgRelative3}`); }); it('should bind proton-src if there is not', () => { const { querySelector } = setup(URL_PROTON); const nope = querySelector('#imgNope') as HTMLImageElement; expect(nope.getAttribute('proton-src')).toBe(`${URL_PROTON}/`); expect(nope.src).toBe(''); }); it('should not change the SRC for a link with already http', () => { const { querySelector } = setup(URL_PROTON); const nope = querySelector('#imghttp') as HTMLImageElement; expect(nope.src).toBe(LINKS.imghttp); }); it('should not change the SRC for a link with cid', () => { const { querySelector } = setup(URL_PROTON); const nope = querySelector('#imgcid') as HTMLImageElement; expect(nope.getAttribute('proton-src')).toBe(LINKS.imgCID); expect(nope.getAttribute('src')).toBe(null); }); }); }); describe('Escape base relative slash', () => { describe('For a link', () => { const getLinks = (type = 'relative') => { const { querySelectorAll } = setup(URL_PROTON_SLASH); return querySelectorAll(`.link-${type}`).map((element) => (element as HTMLLinkElement).href); }; it('should prepend the base into href', () => { const [link1, link2, link3] = getLinks(); expect(link1).toContain(URL_PROTON_SLASH); expect(link2).toContain(URL_PROTON_SLASH); expect(link3).toContain(URL_PROTON_SLASH); }); it('should prepend the base into href without breaking the path', () => { const [link1, link2] = getLinks(); expect(link1).toBe(URL_PROTON + LINKS.linkRelative); expect(link2).toBe(URL_PROTON + LINKS.linkRelative2); }); it('should prepend the base into href with a slash', () => { const [, , link3] = getLinks(); expect(link3).toBe(URL_PROTON_SLASH + LINKS.linkRelative3); }); it('should bind a href if there is not', () => { const { querySelector } = setup(URL_PROTON_SLASH); const nope = querySelector('#linkNope') as HTMLLinkElement; expect(nope.href).toBe(URL_PROTON_SLASH); }); it('should not change the HREF for a link with already http', () => { const { querySelector } = setup(URL_PROTON_SLASH); const nope = querySelector('#ahttp') as HTMLLinkElement; expect(nope.href).toBe(LINKS.ahttp); }); }); describe('For an image', () => { const getImages = (type = 'relative') => { const { querySelectorAll } = setup(URL_PROTON_SLASH); return querySelectorAll(`.img-${type}`).map((element) => (element as HTMLImageElement).src); }; it('should prepend the base into href', () => { const [img1, img2, img3] = getImages(); expect(img1).toContain(URL_PROTON_SLASH); expect(img2).toContain(URL_PROTON_SLASH); expect(img3).toContain(URL_PROTON_SLASH); }); it('should prepend the base into src without breaking the path', () => { const [img1, img2] = getImages(); expect(img1).toBe(URL_PROTON + LINKS.imgRelative); expect(img2).toBe(URL_PROTON + LINKS.imgRelative2); }); it('should prepend the base into src with a slash', () => { const [, , img3] = getImages(); expect(img3).toBe(URL_PROTON_SLASH + LINKS.imgRelative3); }); it('should bind proton-src if there is not', () => { const { querySelector } = setup(URL_PROTON_SLASH); const nope = querySelector('#imgNope') as HTMLImageElement; expect(nope.getAttribute('proton-src')).toBe(URL_PROTON_SLASH); expect(nope.src).toBe(''); }); it('should not change the SRC for a link with already http', () => { const { querySelector } = setup(URL_PROTON_SLASH); const nope = querySelector('#imghttp') as HTMLImageElement; expect(nope.src).toBe(LINKS.imghttp); }); it('should not change the SRC for a link with cid', () => { const { querySelector } = setup(URL_PROTON_SLASH); const nope = querySelector('#imgcid') as HTMLImageElement; expect(nope.getAttribute('proton-src')).toBe(LINKS.imgCID); expect(nope.getAttribute('src')).toBe(null); }); }); }); describe('Escape with a base', () => { const matchLink = (url: string, domain = DEFAULT_DOMAIN) => `${domain}${url.startsWith('/') ? url : `/${url}`}`; describe('For a link', () => { const getLinks = (type = 'relative') => { const { querySelectorAll } = setup(); return querySelectorAll(`.link-${type}`).map((element) => (element as HTMLLinkElement).href); }; it('should prepend the base into href', () => { const [link1, link2, link3] = getLinks(); expect(link1).not.toContain(URL_PROTON); expect(link2).not.toContain(URL_PROTON); expect(link3).not.toContain(URL_PROTON); }); it('should prepend the base into href without breaking the path', () => { const [link1, link2] = getLinks(); expect(link1).toBe(matchLink(LINKS.linkRelative)); expect(link2).toBe(matchLink(LINKS.linkRelative2)); }); it('should prepend the base into href with a slash', () => { const [, , link3] = getLinks(); expect(link3).toBe(matchLink(LINKS.linkRelative3)); }); it('should bind a href if there is not', () => { const { querySelector } = setup(); const nope = querySelector('#linkNope') as HTMLLinkElement; expect(nope.href).toBe(matchLink('')); }); it('should not change the HREF for a link with already http', () => { const { querySelector } = setup(); const nope = querySelector('#ahttp') as HTMLLinkElement; expect(nope.href).toBe(LINKS.ahttp); }); it('should not change the HREF for a mailto link', () => { const { querySelector } = setup(); const nope = querySelector('#mailto') as HTMLLinkElement; expect(nope.href).toBe(LINKS.mailto); }); }); describe('For an image', () => { const getImages = (type = 'relative') => { const { querySelectorAll } = setup(); return querySelectorAll(`.img-${type}`).map((element) => (element as HTMLImageElement).src); }; it('should prepend the base into href', () => { const [img1, img2, img3] = getImages(); expect(img1).not.toContain(URL_PROTON_SLASH); expect(img2).not.toContain(URL_PROTON_SLASH); expect(img3).not.toContain(URL_PROTON_SLASH); }); it('should prepend the base into src without breaking the path', () => { const [img1, img2] = getImages(); expect(img1).toBe(matchLink(LINKS.imgRelative)); expect(img2).toBe(matchLink(LINKS.imgRelative2)); }); it('should prepend the base into src with a slash', () => { const [, , img3] = getImages(); expect(img3).toBe(matchLink(LINKS.imgRelative3)); }); it('should bind proton-src if there is not', () => { const { querySelector } = setup(); const nope = querySelector('#imgNope') as HTMLImageElement; expect(nope.getAttribute('proton-src')).toBe(matchLink('')); expect(nope.src).toBe(''); }); it('should not change the SRC for a link with already http', () => { const { querySelector } = setup(); const nope = querySelector('#imghttp') as HTMLImageElement; expect(nope.src).toBe(LINKS.imghttp); }); it('should not change the SRC for a link with cid', () => { const { querySelector } = setup(); const nope = querySelector('#imgcid') as HTMLImageElement; expect(nope.getAttribute('proton-src')).toBe(LINKS.imgCID); expect(nope.getAttribute('src')).toBe(null); }); }); }); });
3,934
0
petrpan-code/ProtonMail/WebClients/applications/mail/src/app/helpers/transforms
petrpan-code/ProtonMail/WebClients/applications/mail/src/app/helpers/transforms/tests/transformEmbedded.test.ts
import { MailSettings } from '@proton/shared/lib/interfaces'; import { Attachment, Message } from '@proton/shared/lib/interfaces/mail/Message'; import { SHOW_IMAGES } from '@proton/shared/lib/mail/mailSettings'; import { MessageImage, MessageState } from '../../../logic/messages/messagesTypes'; import { createDocument } from '../../test/message'; import { transformEmbedded } from '../transformEmbedded'; const defaultMailSettings = { HideEmbeddedImages: SHOW_IMAGES.SHOW, } as MailSettings; describe('transformEmbedded', () => { const setup = (message: MessageState, mailSettings = defaultMailSettings) => { return transformEmbedded( message, mailSettings, jest.fn(() => Promise.resolve([])) ); }; it('should detect cid embedded images', async () => { const cids = ['imageCID1', 'imageCID2', 'imageCID3', 'imageCID4', 'imageCID5', 'imageCID6']; const content = `<div> <img src='cid:${cids[0]}'/> <img src='${cids[1]}'/> <img src='${cids[2]}' data-embedded-img='${cids[2]}'/> <img src='${cids[3]}' data-embedded-img='cid:${cids[3]}'/> <img src='${cids[4]}' data-src='${cids[4]}'/> <img src='${cids[5]}' proton-src='${cids[5]}'/> </div>`; const message: MessageState = { localID: 'messageWithEmbedded', data: { ID: 'messageID', Attachments: [ { Headers: { 'content-id': cids[0] } } as Attachment, { Headers: { 'content-id': cids[1] } } as Attachment, { Headers: { 'content-id': cids[2] } } as Attachment, { Headers: { 'content-id': cids[3] } } as Attachment, { Headers: { 'content-id': cids[4] } } as Attachment, { Headers: { 'content-id': cids[5] } } as Attachment, ], } as Message, messageDocument: { document: createDocument(content) }, }; const { showEmbeddedImages, embeddedImages, hasEmbeddedImages } = await setup(message); expect(showEmbeddedImages).toBeTruthy(); expect(hasEmbeddedImages).toBeTruthy(); expect(embeddedImages.length).toEqual(6); embeddedImages.forEach((img, index) => { expect(embeddedImages[index].attachment.Headers?.['content-id']).toEqual(cids[index]); expect(embeddedImages[index].cid).toEqual(cids[index]); expect(embeddedImages[index].cloc).toEqual(''); expect(embeddedImages[index].type).toEqual('embedded'); }); }); it('should detect cloc embedded images', async () => { const cloc = 'imageCLOC'; const content = `<div><img src='${cloc}' proton-src='${cloc}'/></div>`; const message: MessageState = { localID: 'messageWithEmbedded', data: { ID: 'messageID', Attachments: [{ Headers: { 'content-location': cloc } } as Attachment], } as Message, messageDocument: { document: createDocument(content) }, }; const { showEmbeddedImages, embeddedImages, hasEmbeddedImages } = await setup(message); expect(showEmbeddedImages).toBeTruthy(); expect(hasEmbeddedImages).toBeTruthy(); expect(embeddedImages[0].attachment.Headers?.['content-location']).toEqual(cloc); expect(embeddedImages[0].cloc).toEqual(cloc); expect(embeddedImages[0].cid).toEqual(''); expect(embeddedImages[0].type).toEqual('embedded'); }); it('should detect embedded images when already loaded', async () => { const cid = 'imageCID'; const content = `<div><img src='cid:${cid}'/></div>`; const message: MessageState = { localID: 'messageWithEmbedded', data: { ID: 'messageID', Attachments: [{ Headers: { 'content-id': cid } } as Attachment], } as Message, messageDocument: { document: createDocument(content) }, messageImages: { hasRemoteImages: false, hasEmbeddedImages: true, showRemoteImages: false, showEmbeddedImages: true, trackersStatus: 'not-loaded', images: [ { type: 'embedded', cid, cloc: '', attachment: { Headers: { 'content-id': cid } } as Attachment, } as MessageImage, ], }, }; const { showEmbeddedImages, embeddedImages, hasEmbeddedImages } = await setup(message); expect(showEmbeddedImages).toBeTruthy(); expect(hasEmbeddedImages).toBeTruthy(); expect(embeddedImages[0].attachment.Headers?.['content-id']).toEqual(cid); expect(embeddedImages[0].cid).toEqual(cid); expect(embeddedImages[0].cloc).toEqual(''); expect(embeddedImages[0].type).toEqual('embedded'); }); it('should detect embedded images in drafts', async () => { const cid = 'imageCID'; const content = `<div><img src='cid:${cid}'/></div>`; const message: MessageState = { localID: 'messageWithEmbedded', data: { ID: 'messageID', Flags: 12, // Flag as draft Attachments: [{ Headers: { 'content-id': cid } } as Attachment], } as Message, messageDocument: { document: createDocument(content) }, }; const { showEmbeddedImages, embeddedImages, hasEmbeddedImages } = await setup(message); expect(showEmbeddedImages).toBeTruthy(); expect(hasEmbeddedImages).toBeTruthy(); expect(embeddedImages[0].attachment.Headers?.['content-id']).toEqual(cid); expect(embeddedImages[0].cid).toEqual(cid); expect(embeddedImages[0].cloc).toEqual(''); expect(embeddedImages[0].type).toEqual('embedded'); expect(embeddedImages[0].status).toEqual('not-loaded'); }); it('should load embedded images by default whatever the loading setting value when Sender is Proton verified', async () => { const cid = 'imageCID'; const content = `<div><img src='cid:${cid}'/></div>`; const message: MessageState = { localID: 'messageWithEmbedded', data: { ID: 'messageID', Attachments: [{ Headers: { 'content-id': cid } } as Attachment], Sender: { Name: 'Verified address', Address: '[email protected]', IsProton: 1, }, } as Message, messageDocument: { document: createDocument(content) }, }; const mailSettings = { HideEmbeddedImages: SHOW_IMAGES.HIDE, } as MailSettings; const { showEmbeddedImages, embeddedImages, hasEmbeddedImages } = await setup(message, mailSettings); expect(showEmbeddedImages).toBeTruthy(); expect(hasEmbeddedImages).toBeTruthy(); expect(embeddedImages[0].attachment.Headers?.['content-id']).toEqual(cid); expect(embeddedImages[0].cid).toEqual(cid); expect(embeddedImages[0].cloc).toEqual(''); expect(embeddedImages[0].type).toEqual('embedded'); }); it('should not load embedded images by default when Sender is not Proton verified', async () => { const cid = 'imageCID'; const content = `<div><img src='cid:${cid}'/></div>`; const message: MessageState = { localID: 'messageWithEmbedded', data: { ID: 'messageID', Attachments: [{ Headers: { 'content-id': cid } } as Attachment], Sender: { Name: 'Normal address', Address: '[email protected]', IsProton: 0, }, } as Message, messageDocument: { document: createDocument(content) }, }; const mailSettings = { HideEmbeddedImages: SHOW_IMAGES.HIDE, } as MailSettings; const { showEmbeddedImages, embeddedImages, hasEmbeddedImages } = await setup(message, mailSettings); expect(showEmbeddedImages).toBeFalsy(); expect(hasEmbeddedImages).toBeTruthy(); expect(embeddedImages[0].attachment.Headers?.['content-id']).toEqual(cid); expect(embeddedImages[0].cid).toEqual(cid); expect(embeddedImages[0].cloc).toEqual(''); expect(embeddedImages[0].type).toEqual('embedded'); }); });
3,935
0
petrpan-code/ProtonMail/WebClients/applications/mail/src/app/helpers/transforms
petrpan-code/ProtonMail/WebClients/applications/mail/src/app/helpers/transforms/tests/transformEscape.test.ts
import { base64Cache, clearAll } from '../../test/helper'; import { attachBase64, transformEscape } from '../transformEscape'; describe('transformEscape', () => { const babase64 = `src="data:image/jpg;base64,iVBORw0KGgoAAAANSUhEUgAABoIAAAVSCAYAAAAisOk2AAAMS2lDQ1BJQ0MgUHJv ZmlsZQAASImVVwdYU8kWnltSSWiBUKSE3kQp0qWE0CIISBVshCSQUGJMCCJ2FlkF 1y4ioK7oqoiLrgWQtaKudVHs/aGIysq6WLCh8iYF1tXvvfe9831z758z5/ynZO69 MwDo1PKk0jxUF4B8SYEsITKUNTEtnUXqAgSgD1AwGozk8eVSdnx8DIAydP+nvLkO"`; const DOM = ` <section> <svg id="svigi" width="5cm" height="4cm" version="1.1" xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink"> <image xlink:href="firefox.jpg" x="0" y="0" height="50px" width="50px" /> <image xlink:href="chrome.jpg" x="0" y="0" height="50px" width="50px" /> <image href="svg-href.jpg" x="0" y="0" height="50px" width="50px" /> </svg> <video src="fichiervideo.webm" autoplay poster="vignette.jpg"> </video> <div> <img border="0" usemap="#fp" src="cats.jpg "> <map name="fp"> <area coords="0,0,800,800" href="proton_exploit.html" shape="rect" target="_blank" > </map> </div> <video src="fichiervideo.webm" autoplay poster="vignette2.jpg"> </video> <img src="mon-image.jpg" srcset="mon-imageHD.jpg 2x" width="" height="" alt=""> <img src="lol-image.jpg" srcset="lol-imageHD.jpg 2x" width="" height="" alt=""> <img data-src="lol-image.jpg" width="" height="" alt=""> <a href="lol-image.jpg">Alll</a> <a href="jeanne-image.jpg">Alll</a> <div background="jeanne-image.jpg">Alll</div> <div background="jeanne-image2.jpg">Alll</div> <p style="font-size:10.0pt;font-family:\\2018Calibri\\2019;color:black"> Example style that caused regexps to crash </p> <img id="babase64" ${babase64}/> </section> `; const CODE_HTML_HIGHLIGHT = ` <div style="white-space: normal;" class="pre"><div style="color: #fff;max-inline-size: 100%;font-size: 16px;line-height: 1.3;" class="code"><span style="color: #DDDDDF;" class="nt">&lt;script</span> <span style="color: #84868B;" class="na">src="</span><span style="color: #68BEA2;" class="s"><span class="s">https<span>://</span>use.fontawesome<span>.</span>com/f0d8991ea9.js</span><span style="color: #84868B;" class="na">"</span><span style="color: #DDDDDF;" class="nt">&gt;</span><span style="color: #DDDDDF;" class="nt">&lt;/script&gt;</span></span></div></div><div class="pre"></div> `; const HTML_LINKS = ` <div> <a href="http://www.dewdwesrcset-dewdw.com/?srcset=de&srcset=Dewdwe"></a> <a href="http://www.dewdwesrc-dewdw.com/?src=de&src=Dewdwe"></a> <a href="http://www.dewdwebackground-dewdw.com/?background=de&background=Dewdwe"></a> <a href="http://www.dewdweposter-dewdw.com/?poster=de&poster=Dewdwe"></a> <a href="http://www.google.nl/?url=a"></a> <a href="http://www.google.nl/?src=a&srcset=dew"></a> </div> `; const CODE_HTML = '<pre><code><img src="polo.fr"></code></pre>'; const CODE_HTML_ESCAPED = '<pre><code><img proton-src="polo.fr"></code></pre>'; const CODE_TEXT = "<pre><code>{ background: url('monique.jpg') }</code></pre>"; const TEXT = '<p>salut monique est ceque tu as un src="lol" dans la poche ?</p><span>src=</span>'; const EDGE_CASE = '<div id="ymail_android_signature"><a href="https://overview.mail.yahoo.com/mobile/?.src=Android">Sent from Yahoo Mail on Android</a></div>'; const EDGE_CASE_2 = ` webEngineView->setUrl(" <span>webEngineView->setUrl("</span> <div>webEngineView->setUrl("</div> <pre>webEngineView->setUrl("</pre> <code>webEngineView->setUrl(".</code> `; const EX_URL = '<div style="background: url(\'https://i.imgur.com/WScAnHr.jpg\')">ddewdwed</div>'; const EX_URL_CLEAN = '<div style="background: proton-url(\'https://i.imgur.com/WScAnHr.jpg\')">ddewdwed</div>'; const BACKGROUND_URL = ` <div style="background: url('https://i.imgur.com/WScAnHr.jpg')">ddewdwed</div> <div style="color: red; background: #ffffff url('https://i.imgur.com/WScAnHr.jpg')">ddewdwed</div> <div style="color: red; background: url('https://i.imgur.com/WScAnHr.jpg')">ddewdwed</div> <div style="color: red; background:url('https://i.imgur.com/WScAnHr.jpg')">ddewdwed</div> <span style="color: red; background:url('https://i.imgur.com/WScAnHr.jpg')">ddewdwed</span>`; const BACKGROUND_URL_ESCAPED_WTF = '<div style="inline-size: 500px; block-size: 500px; background:u\\rl(&quot;https://i.imgur.com/WScAnHr.jpg&quot;)">ddewdwed</div>'; // DON'T REMOVE THEM const BACKGROUND_URL_ESCAPED_WTF2 = ` <div style="inline-size: 500px; block-size: 500px; background:url(&quot;https://i.imgur.com/WScAnHr.jpg&quot;)">ddewdwed</div> <div style="inline-size: 500px; block-size: 500px; background:u&#114;l(&quot;https://i.imgur.com/WScAnHr.jpg&quot;)">ddewdwed</div> <div style="inline-size: 500px; block-size: 500px; background:ur&#108;(&quot;https://i.imgur.com/WScAnHr.jpg&quot;)">ddewdwed</div> `; const BACKGROUND_URL_ESCAPED = ` <div style="inline-size: 500px; block-size: 500px; background:&#117;rl(&quot;https://i.imgur.com/WScAnHr.jpg&quot;)">ddewdwed</div> <div style="inline-size: 500px; block-size: 500px; background:&#117;rl(&quot;https://i.imgur.com/WScAnHr.jpg&quot;)">ddewdwed</div> <div style="inline-size: 500px; block-size: 500px; background:&#117;rl(&apos;https://i.imgur.com/WScAnHr.jpg&apos;)">ddewdwed</div> <div style="inline-size: 500px; block-size: 500px; content: &quot; ass &quot;; background:url(https://i.imgur.com/WScAnHr.jpg);">ddewdwed</div> <div style="inline-size: 500px; block-size: 500px; content: &quot; ass &quot;; background:url(https://i.imgur.com/WScAnHr.jpg);">ddewdwed</div> <div style="inline-size: 500px; block-size: 120px; content: &quot; ass &quot;; background:&#117;&#114;&#108;(https://i.imgur.com/WScAnHr.jpg);">ddewdwed</div> <div style="inline-size: 500px; block-size: 120px; content: &quot; ass &quot;; background:&#117;r&#108;(https://i.imgur.com/WScAnHr.jpg);">ddewdwed</div> <div style="inline-size: 500px; block-size: 120px; content: &quot; ass &quot;; background: u&#114l(https://i.imgur.com/WScAnHr.jpg);">ddewdwed</div> <div style="inline-size: 500px; block-size: 500px; content: &quot; ass &quot;; background:url&#x00028;https://i.imgur.com/WScAnHr.jpg);">ddewdwed</div> <div style="inline-size: 500px; block-size: 500px; content: &quot; ass &quot;; background:url&lpar;https://i.imgur.com/WScAnHr.jpg);">ddewdwed</div> <div style="inline-size: 500px; block-size: 456px; content: &quot; ass &quot;; background:url&#40;https://i.imgur.com/WScAnHr.jpg);">ddewdwed</div> `; const BACKGROUND_URL_OCTAL_HEX_ENCODING = ` <div style="background: \\75&#114\\6C('https://TRACKING1/')">test1</div> <div style="background: \\75&#114;\\6C('https://TRACKING2/')">test2</div> <div style="background: \\75r&#108('https://TRACKING3/')">test3</div> <div style="background: &#117r\\6c('https://TRACKING4/')">test4</div> <div style="background: \\75 \\72 \\6C ('https://TRACKING5/')">test5</div> <div style="background: \\75\\72\\6c ('https://TRACKING6/')">test6</div> <div style="background: \\75\\72\\6C('https://TRACKING7/')">test7</div> <div style="background: \\75\\72\\6c('https://TRACKING8/')">test8</div> <div style="background: \x75\x72\x6C('https://TRACKING9/')">test9</div> <div style="background: \u0075\u0072\u006c('https://TRACKING10/')">test10</div> <div style="background: &#x75r\\6c('https://TRACKING11/')">test11</div> <div style="background: \\75&#x72;\\6C('https://TRACKING12/')">test12</div> <div style="background: \\75r&#x6c;('https://TRACKING13/')">test13</div> <div style="background: \\75r&#x6c;('https://TRACKING14/')">test14</div> `; const BACKGROUND_URL_SAFE = ` <span>url('dewd')</span> <span>style="dewdw" url('dewd')</span> <span>dew style="dewdw" url('dewd')</span> <span>dew style="dewdw": url(</span> <span>dew style="content: \\"a\\"": url(</span> <span>dew style="content: 'a": url(</span> <span>dew style="content: \\"a": url(</span> `; // TODO: Fix those 2 // <div style="inline-size: 500px; block-size: 500px; content: &quot; background:url(test)&quot;">ddewdwed</div> // <div style="inline-size: 500px; block-size: 500px; content: &apos; background:url(test)&apos;">ddewdwed</div> // Firefox support image-set :/ // https://jira.protontech.ch/browse/MAILWEB-2993 const BACKGROUND_IMAGE_SET = ` <div style='background: image-set("https://TRACKING/");'> `; // That's a nasty one! const BACKGROUND_DOUBLE_ESCAPING = ` <div style="background: ur\\\\5C\\\\6C(https://TRACKING/); /* url( */"></div> `; const setup = (content = DOM) => { const doc = transformEscape(content, base64Cache); const querySelector = (selectors: string) => doc.querySelector(selectors); const querySelectorAll = (selectors: string) => [...doc.querySelectorAll(selectors)]; return { document: doc, querySelector, querySelectorAll }; }; afterEach(clearAll); describe('Replace base64', () => { describe('No syntax hightlighting', () => { const getBase64Image = () => { const { querySelector } = setup(); return querySelector('img[data-proton-replace-base]') as HTMLImageElement; }; it('should remove the base64 from src', () => { const image = getBase64Image(); expect(image.src).toBe(''); expect(image.hasAttribute('src')).toBe(false); }); it('should add a custom marker attribute', () => { const image = getBase64Image(); expect(image.hasAttribute('data-proton-replace-base')).toBe(true); expect(image.getAttribute('data-proton-replace-base')).not.toBe(''); }); it('should add a custom marker attribute with a hash available inside the cache', () => { const image = getBase64Image(); const [hash] = base64Cache.keys(); expect(image.getAttribute('data-proton-replace-base')).toBe(hash); expect(base64Cache.get(hash)).toBe(babase64); }); it('should attach the base64', () => { const { document, querySelector } = setup(); attachBase64(document, base64Cache); const image = querySelector('img[src*=base64]') as HTMLImageElement; expect(image.hasAttribute('data-proton-replace-base')).toBe(false); expect(image.hasAttribute('src')).toBe(true); const value = babase64.replace(/^src="/, '').slice(0, 20); expect(image.src.startsWith(value)).toBe(true); }); }); describe('Syntax hightlighting', () => { it('should not escape inside a <code> tag', () => { const { document } = setup(CODE_HTML_HIGHLIGHT); expect(document.innerHTML).not.toMatch(/proton-/); }); }); }); describe('Escape <pre>', () => { describe('No syntax hightlighting', () => { it('should escape inside a <code> tag', () => { const { querySelector } = setup(CODE_HTML); expect(querySelector('body')?.innerHTML).toBe(CODE_HTML_ESCAPED); }); it('should not escape text inside a <code> tag', () => { const { querySelector } = setup(CODE_TEXT); expect(querySelector('body')?.innerHTML).toBe(CODE_TEXT); }); }); describe('Syntax hightlighting', () => { it('should not escape inside a <code> tag', () => { const { document } = setup(CODE_HTML_HIGHLIGHT); expect(document.innerHTML).not.toMatch(/proton-/); }); }); }); describe('Escape everything with proton-', () => { const getAttribute = (attribute: string) => { const { querySelectorAll } = setup(); return querySelectorAll(`[${attribute}]`); }; describe('Add a prefix', () => { it('should not add the prefix before href on a link', () => { const list = getAttribute('proton-href'); expect(list.filter((element) => element.tagName === 'A').length).toBe(0); }); it('should add the prefix before src', () => { const list = getAttribute('proton-src'); expect(list.length).toBe(5); }); it('should add the prefix before data-src', () => { const list = getAttribute('proton-data-src'); expect(list.length).toBe(1); }); it('should add the prefix before srcset', () => { const list = getAttribute('proton-srcset'); expect(list.length).toBe(2); }); it('should add the prefix before background', () => { const list = getAttribute('proton-background'); expect(list.length).toBe(2); }); it('should add the prefix before poster', () => { const list = getAttribute('proton-poster'); expect(list.length).toBe(2); }); }); describe('SVG have been totally discontinuated, should be removed, not prefixed!', () => { it('should not add the prefix for SVG', () => { const { querySelectorAll } = setup(); const list = querySelectorAll('proton-svg'); expect(list.length).toBe(0); }); it('should not add the prefix for xlink:href', () => { const { document } = setup(); const list = document.innerHTML.match(/proton-xlink:href/g); expect(list?.length).toBeUndefined(); }); it('should not add the prefix for svg href', () => { const { querySelector } = setup(); const svgHref = querySelector('[proton-href="svg-href.jpg"]'); expect(svgHref).toBe(null); }); }); describe('Excape all the things !', () => { it('should have escaped every src', () => { const list = getAttribute('src'); expect(list.length).toBe(0); }); it('should have escaped every srcset', () => { const list = getAttribute('srcset'); expect(list.length).toBe(0); }); it('should have escaped every background', () => { const list = getAttribute('background'); expect(list.length).toBe(0); }); it('should have escaped every poster', () => { const list = getAttribute('poster'); expect(list.length).toBe(0); }); it('should have escaped every SVG', () => { const { querySelectorAll } = setup(); const list = querySelectorAll('svg'); expect(list.length).toBe(0); }); }); }); describe('No escape inside URL', () => { it('should not escape the content of an anchor tag', () => { const { document } = setup(HTML_LINKS); expect(document.innerHTML).not.toMatch(/proton-/); }); }); describe('No escape TXT', () => { it('should not escape txt', () => { const { document } = setup(TEXT); expect(document.innerHTML).not.toMatch(/proton-/); }); }); describe('No escape EDGE_CASE', () => { it('should not escape EDGE_CASE', () => { const { document } = setup(EDGE_CASE); expect(document.innerHTML).not.toMatch(/proton-/); }); }); describe('No escape EDGE_CASE2', () => { it('should not escape EDGE_CASE', () => { const { document } = setup(EDGE_CASE_2); expect(document.innerHTML).not.toMatch(/proton-/); }); }); describe('No double escape', () => { it('should not double escape attributes', () => { const { document } = setup(DOM); expect(document.innerHTML).not.toMatch(/proton-proton-/); }); }); describe('Escape BACKGROUND_URL', () => { const getList = (content: string) => { const { querySelector } = setup(content); return ( querySelector('body') ?.innerHTML.split('\n') .map((s) => s.trim()) .filter(Boolean) || [] ); }; it('should escape all', () => { const list = getList(BACKGROUND_URL); list.forEach((key) => expect(key).toMatch(/proton-/)); }); it('should escape all encoded url', () => { const list = getList(BACKGROUND_URL_ESCAPED); list.forEach((key) => expect(key).toMatch(/proton-/)); }); it('should escape encoded url with escape \\r', () => { const { document } = setup(BACKGROUND_URL_ESCAPED_WTF); expect(document.innerHTML).toMatch(/proton-/); }); it('should escape encoded url with escape standard wtf', () => { const list = getList(BACKGROUND_URL_ESCAPED_WTF2); list.forEach((key) => expect(key).toMatch(/proton-/)); }); it('should escape octal and hex encoded urls with escape', () => { const list = getList(BACKGROUND_URL_OCTAL_HEX_ENCODING); list.forEach((key) => expect(key).toMatch(/proton-/)); }); it('should not break the HTML', () => { const { querySelector } = setup(EX_URL); expect(querySelector('body')?.innerHTML).toEqual(EX_URL_CLEAN); }); }); describe('base handling', () => { it('Should preserve <base href> in <head>', () => { const BASE = `<head><base href="https://bugzilla.mozilla.org/"></head>`; const { document, querySelector } = setup(BASE); expect(document.innerHTML).toMatch(/<base/); const base = querySelector('base'); expect(base).toBeTruthy(); expect(base?.getAttribute('href')).toEqual('https://bugzilla.mozilla.org/'); }); }); describe('Not escape BACKGROUND_URL', () => { it('should not escape anything', () => { const { document } = setup(BACKGROUND_URL_SAFE); expect(document.innerHTML).not.toMatch(/proton-/); }); }); describe('Escape BACKGROUND_IMAGE_SET', () => { it('should escape image-set', () => { const { document } = setup(BACKGROUND_IMAGE_SET); expect(document.innerHTML).toMatch(/proton-/); }); }); describe('Escape BACKGROUND_DOUBLE_ESCAPING', () => { it('should escape double escaping', () => { const { document } = setup(BACKGROUND_DOUBLE_ESCAPING); expect(document.innerHTML).toMatch(/proton-url\(https/); }); }); });
3,936
0
petrpan-code/ProtonMail/WebClients/applications/mail/src/app/helpers/transforms
petrpan-code/ProtonMail/WebClients/applications/mail/src/app/helpers/transforms/tests/transformLinks.test.ts
import { transformLinks } from '../transformLinks'; describe('transformLinks service', () => { const ADD_REF = ` <a href="#lol" id="anchorLink">anchor</a> <a href="" id="emptyLink">nada</a> <a href="/monique">relative</a> <a href="https://lol.jpg">https</a> <a href="http://lol.jpg">http</a> <a href="ftp://lol.jpg">ftp</a> <a href="xmpp://lol.jpg">xmpp</a> <a href="tel://lol.jpg">tel</a> <a href="callto://lol.jpg">callto</a> <a href="mailto://lol.jpg">mailto</a> <a href="https://ads.com?utm_content=toto">utm</a> <div href id="hrefLink">xxxx</div> `; const EMPTY_LINK = '<a>anchor</a>'; const setup = (content = ADD_REF) => { const doc = document.createElement('DIV'); doc.innerHTML = content; transformLinks(doc, jest.fn(), true); const querySelector = (selectors: string) => doc.querySelector(selectors); const querySelectorAll = (selectors: string) => [...doc.querySelectorAll(selectors)]; return { document: doc, querySelector, querySelectorAll }; }; describe('Improve privacy', () => { const TOTAL = ADD_REF.split('\n') .map((s) => s.trim()) .filter(Boolean).length; it('should add referrer', () => { const { querySelectorAll } = setup(); expect(querySelectorAll('[rel="noreferrer nofollow noopener"]').length).toEqual(TOTAL); }); it('should add target for real link', () => { const { querySelectorAll } = setup(); expect(querySelectorAll('[target="_blank"]').length).toEqual(4); expect(querySelectorAll('[href^="http"][target="_blank"]').length).toEqual(4); }); it('should strip tracking parameters (utm)', () => { const { querySelector } = setup(ADD_REF); expect(querySelector('[href="https://ads.com/"]')).toBeTruthy(); expect(querySelector('[href*="utm_content=toto"]')).toBeFalsy(); }); }); describe('Fix links', () => { it('should add domain in from of the link relative', () => { const { querySelector } = setup(ADD_REF + EMPTY_LINK); expect(querySelector('[href="http:///monique"]')).toBeTruthy(); }); it('should not do anything for an empty anchor tag', () => { const { querySelector } = setup(ADD_REF + EMPTY_LINK); expect(querySelector('a:not([href])')?.outerHTML).toEqual(EMPTY_LINK); }); it('should add pointerEvents to an empty anchor or invalid', () => { const { querySelector, querySelectorAll } = setup(ADD_REF + EMPTY_LINK); expect(querySelectorAll('[style]').length).toBe(2); expect((querySelector('#emptyLink') as HTMLElement).style.pointerEvents).toBe('none'); expect((querySelector('#hrefLink') as HTMLElement).style.pointerEvents).toBe('none'); }); it('should not escape the anchor link', () => { const { querySelector } = setup(ADD_REF + EMPTY_LINK); expect(querySelector('#anchorLink')?.hasAttribute('style')).toBe(false); }); }); });
3,937
0
petrpan-code/ProtonMail/WebClients/applications/mail/src/app/helpers/transforms
petrpan-code/ProtonMail/WebClients/applications/mail/src/app/helpers/transforms/tests/transformRemote.test.ts
import { wait } from '@proton/shared/lib/helpers/promise'; import { MailSettings } from '@proton/shared/lib/interfaces'; import { Message } from '@proton/shared/lib/interfaces/mail/Message'; import { IMAGE_PROXY_FLAGS, SHOW_IMAGES } from '@proton/shared/lib/mail/mailSettings'; import { MessageState } from '../../../logic/messages/messagesTypes'; import { createDocument } from '../../test/message'; import { transformRemote } from '../transformRemote'; describe('transformRemote', () => { let onLoadRemoteImagesProxy: jest.Mock; let onLoadFakeImagesProxy: jest.Mock; let onLoadRemoteImagesDirect: jest.Mock; const setup = (message: MessageState, mailSettings: MailSettings) => { onLoadRemoteImagesProxy = jest.fn(); onLoadFakeImagesProxy = jest.fn(); onLoadRemoteImagesDirect = jest.fn(); return transformRemote( message, mailSettings, onLoadRemoteImagesDirect, onLoadRemoteImagesProxy, onLoadFakeImagesProxy ); }; it('should detect remote images', async () => { const imageURL = 'imageURL'; const imageBackgroundURL = 'http://domain.com/image.jpg'; const content = `<div> <img proton-src='${imageURL}'/> </div> <div style="background: proton-url(${imageBackgroundURL})" /> `; const message: MessageState = { localID: 'messageWithRemote', data: { ID: 'messageID', } as Message, messageDocument: { document: createDocument(content) }, }; const mailSettings = { HideRemoteImages: SHOW_IMAGES.SHOW, } as MailSettings; const { showRemoteImages, remoteImages, hasRemoteImages } = setup(message, mailSettings); expect(showRemoteImages).toBeTruthy(); expect(hasRemoteImages).toBeTruthy(); expect(remoteImages[0].type).toEqual('remote'); expect(remoteImages[0].url).toEqual(imageURL); expect(remoteImages[1].type).toEqual('remote'); expect(remoteImages[1].url).toEqual(imageBackgroundURL); }); it('should load remote images through proxy', async () => { const imageURL = 'imageURL'; const imageBackgroundURL = 'http://domain.com/image.jpg'; const content = `<div> <img proton-src='${imageURL}'/> </div> <div style="background: proton-url(${imageBackgroundURL})" /> `; const message: MessageState = { localID: 'messageWithRemote', data: { ID: 'messageID', } as Message, messageDocument: { document: createDocument(content) }, }; const mailSettings = { HideRemoteImages: SHOW_IMAGES.SHOW, ImageProxy: IMAGE_PROXY_FLAGS.PROXY, } as MailSettings; const { showRemoteImages, remoteImages, hasRemoteImages } = setup(message, mailSettings); expect(showRemoteImages).toBeTruthy(); expect(hasRemoteImages).toBeTruthy(); expect(remoteImages[0].type).toEqual('remote'); expect(remoteImages[0].url).toEqual(imageURL); expect(remoteImages[1].type).toEqual('remote'); expect(remoteImages[1].url).toEqual(imageBackgroundURL); // There is a wait 0 inside the loadRemoteImages helper await wait(0); expect(onLoadRemoteImagesProxy).toHaveBeenCalled(); }); it('should load remote images by default whatever the loading setting value when Sender is Proton verified', async () => { const imageURL = 'imageURL'; const content = `<div> <img proton-src='${imageURL}'/> </div>`; const message: MessageState = { localID: 'messageWithRemote', data: { ID: 'messageID', Sender: { Name: 'Verified address', Address: '[email protected]', IsProton: 1, }, } as Message, messageDocument: { document: createDocument(content) }, }; const mailSettings = { HideRemoteImages: SHOW_IMAGES.HIDE, ImageProxy: IMAGE_PROXY_FLAGS.PROXY, } as MailSettings; const { showRemoteImages, remoteImages, hasRemoteImages } = setup(message, mailSettings); expect(showRemoteImages).toBeTruthy(); expect(hasRemoteImages).toBeTruthy(); expect(remoteImages[0].type).toEqual('remote'); expect(remoteImages[0].url).toEqual(imageURL); // There is a wait 0 inside the loadRemoteImages helper await wait(0); expect(onLoadRemoteImagesProxy).toHaveBeenCalled(); }); it('should not load remote images by default when setting is off and address is not Proton verified', async () => { const imageURL = 'imageURL'; const content = `<div> <img proton-src='${imageURL}'/> </div>`; const message: MessageState = { localID: 'messageWithRemote', data: { ID: 'messageID', Sender: { Name: 'normal address', Address: '[email protected]', IsProton: 0, }, } as Message, messageDocument: { document: createDocument(content) }, }; const mailSettings = { HideRemoteImages: SHOW_IMAGES.HIDE, ImageProxy: IMAGE_PROXY_FLAGS.PROXY, } as MailSettings; const { showRemoteImages, remoteImages, hasRemoteImages } = setup(message, mailSettings); expect(showRemoteImages).toBeFalsy(); expect(hasRemoteImages).toBeTruthy(); expect(remoteImages[0].type).toEqual('remote'); expect(remoteImages[0].url).toEqual(imageURL); // There is a wait 0 inside the loadRemoteImages helper await wait(0); expect(onLoadRemoteImagesProxy).not.toHaveBeenCalled(); }); });
3,938
0
petrpan-code/ProtonMail/WebClients/applications/mail/src/app/helpers/transforms
petrpan-code/ProtonMail/WebClients/applications/mail/src/app/helpers/transforms/tests/transformStyleAttributes.test.ts
import { transformStyleAttributes } from '../transformStyleAttributes'; describe('transformStyleAttributes', () => { const setup = () => { const doc = document.implementation.createHTMLDocument('test transform style attribute'); return doc; }; describe('Transform `vh` height property', () => { it('Should remove VH from style attributes with height containing vh unit', () => { const document = setup(); document.write(` <div id="a" style="margin: 0; width: 100vh; height: 100vh;"> <div id="b" style="margin: 0; width: 100px; height: 100px;"> <span id="c" style="margin: 0; width: 100px; height: 100vh;"></span> </div> </div> `); let a = document.getElementById('a'); let b = document.getElementById('b'); let c = document.getElementById('c'); expect(a?.style.height).toBe('100vh'); expect(a?.style.width).toBe('100vh'); expect(a?.style.margin).toBe('0px'); expect(b?.style.height).toBe('100px'); expect(b?.style.width).toBe('100px'); expect(b?.style.margin).toBe('0px'); expect(c?.style.height).toBe('100vh'); expect(c?.style.width).toBe('100px'); expect(c?.style.margin).toBe('0px'); transformStyleAttributes(document as unknown as Element); expect(a?.style.height).toBe('auto'); expect(a?.style.width).toBe('100vh'); expect(a?.style.margin).toBe('0px'); expect(b?.style.height).toBe('100px'); expect(b?.style.width).toBe('100px'); expect(b?.style.margin).toBe('0px'); expect(c?.style.height).toBe('auto'); expect(c?.style.width).toBe('100px'); expect(c?.style.margin).toBe('0px'); }); }); });
3,949
0
petrpan-code/ProtonMail/WebClients/applications/mail/src/app
petrpan-code/ProtonMail/WebClients/applications/mail/src/app/hooks/useExpiringElement.test.ts
import { fromUnixTime, getUnixTime } from 'date-fns'; import { Message } from '@proton/shared/lib/interfaces/mail/Message'; import { renderHook } from 'proton-mail/helpers/test/render'; import { globalReset } from 'proton-mail/logic/actions'; import { MessageState } from 'proton-mail/logic/messages/messagesTypes'; import { initialize } from 'proton-mail/logic/messages/read/messagesReadActions'; import { store } from 'proton-mail/logic/store'; import { Conversation } from 'proton-mail/models/conversation'; import { useExpiringElement } from './useExpiringElement'; // TODO: Remove when global mock is merged (later) class ResizeObserver { observe() {} unobserve() {} disconnect() {} } beforeAll(() => { window.ResizeObserver = ResizeObserver; }); const MESSAGE_ID = 'messageID'; type GetStoreMessageProps = { types: ('withDraftFlagExpiresIn' | 'withDataExpirationTime')[]; /** Unix timestamp */ expirationTime: number; conversationID: string; }; const getStoreMessage = ({ types, expirationTime, conversationID }: Partial<GetStoreMessageProps>) => { return { localID: MESSAGE_ID, data: { ...(conversationID ? { ConversationID: conversationID } : {}), ...(types?.includes('withDataExpirationTime') ? { ExpirationTime: expirationTime } : {}), }, draftFlags: { ...(types?.includes('withDraftFlagExpiresIn') ? { expiresIn: fromUnixTime(expirationTime as number) } : {}), }, } as MessageState; }; describe('useExpiringElement', () => { let dateTimestamp: number; beforeEach(() => { dateTimestamp = getUnixTime(new Date(2023, 7, 27, 0, 0, 0, 0)); }); afterEach(() => { store.dispatch(globalReset()); }); describe('Conversation mode ON', () => { const conversationID = 'conversationID'; const element = { ID: conversationID, } as Conversation; const labelID = '0'; it('Should not have expiration when no `contextExpirationTime` on the Element and no `expiresIn` draftFlag in messages from store', async () => { store.dispatch(initialize(getStoreMessage({ conversationID }))); const result = await renderHook(() => useExpiringElement(element, labelID, true)); expect(result.result.current.hasExpiration).toBe(false); expect(result.result.current.expirationTime).toBe(0); }); it('Should not have expiration with `expirationTime` data in messages from store', async () => { store.dispatch( initialize( getStoreMessage({ conversationID, types: ['withDataExpirationTime'], expirationTime: dateTimestamp, }) ) ); const result = await renderHook(() => useExpiringElement(element, labelID, true)); expect(result.result.current.hasExpiration).toBe(false); expect(result.result.current.expirationTime).toBe(0); }); it('Should have expiration with `contextExpirationTime` on the element', async () => { const result = await renderHook(() => useExpiringElement( { ...element, ContextExpirationTime: dateTimestamp, }, labelID, true ) ); expect(result.result.current.hasExpiration).toBe(true); expect(result.result.current.expirationTime).toBe(dateTimestamp); }); it('Should have expiration with `expiresIn` draftFlag in messages from store', async () => { store.dispatch( initialize( getStoreMessage({ conversationID, types: ['withDraftFlagExpiresIn'], expirationTime: dateTimestamp, }) ) ); const result = await renderHook(() => useExpiringElement(element, labelID, true)); expect(result.result.current.hasExpiration).toBe(true); expect(result.result.current.expirationTime).toBe(dateTimestamp); }); it('should look for ContextExpirationTime in Labels', async () => { const result = await renderHook(() => useExpiringElement( { ...element, Labels: [ { ID: labelID, ContextExpirationTime: dateTimestamp, }, ], }, labelID, true ) ); expect(result.result.current.hasExpiration).toBe(true); expect(result.result.current.expirationTime).toBe(dateTimestamp); }); }); describe('Conversation mode OFF', () => { const element = { ID: MESSAGE_ID, } as Message; const labelID = '0'; it('Should not have expiration when no `ExpirationTime` on the Element and no `ExpirationTime` data or `expiresIn` draftFlag in message store', async () => { store.dispatch(initialize(getStoreMessage({ types: [], expirationTime: dateTimestamp }))); const result = await renderHook(() => useExpiringElement(element, labelID, false)); expect(result.result.current.hasExpiration).toBe(false); expect(result.result.current.expirationTime).toBe(0); }); it('Should have expiration when `ExpirationTime` on the Element', async () => { store.dispatch(initialize(getStoreMessage({ types: [], expirationTime: dateTimestamp }))); const result = await renderHook(() => useExpiringElement( { ...element, ExpirationTime: dateTimestamp, }, labelID, false ) ); expect(result.result.current.hasExpiration).toBe(true); expect(result.result.current.expirationTime).toBe(dateTimestamp); }); it('Should have expiration when `expiresIn` is set on the message store draftFlags', async () => { store.dispatch( initialize(getStoreMessage({ types: ['withDraftFlagExpiresIn'], expirationTime: dateTimestamp })) ); const result = await renderHook(() => useExpiringElement(element, labelID, false)); expect(result.result.current.hasExpiration).toBe(true); expect(result.result.current.expirationTime).toBe(dateTimestamp); }); it('Should have expiration when `ExpirationTime` is set on the message store data', async () => { store.dispatch( initialize(getStoreMessage({ types: ['withDataExpirationTime'], expirationTime: dateTimestamp })) ); const result = await renderHook(() => useExpiringElement(element, labelID, false)); expect(result.result.current.hasExpiration).toBe(true); expect(result.result.current.expirationTime).toBe(dateTimestamp); }); }); });
3,953
0
petrpan-code/ProtonMail/WebClients/applications/mail/src/app
petrpan-code/ProtonMail/WebClients/applications/mail/src/app/hooks/useLabelActions.test.ts
import { renderHook } from '@testing-library/react-hooks'; import { useFolders, useLabels } from '@proton/components/hooks'; import { MAILBOX_LABEL_IDS } from '@proton/shared/lib/constants'; import { useLabelActions } from './useLabelActions'; jest.mock('@proton/components/hooks/useCategories'); const { TRASH, SPAM, DRAFTS, ARCHIVE, SENT, INBOX, ALL_DRAFTS, ALL_SENT, STARRED, ALL_MAIL, ALMOST_ALL_MAIL, SCHEDULED, SNOOZED, } = MAILBOX_LABEL_IDS; describe('useLabelActions', () => { const useFoldersMock = useFolders as jest.Mock; const useLabelsMock = useLabels as jest.Mock; beforeEach(() => { useFoldersMock.mockReturnValue([[], jest.fn()]); useLabelsMock.mockReturnValue([[], jest.fn()]); }); afterEach(() => { useFoldersMock.mockClear(); useLabelsMock.mockClear(); }); it('should render correct action for inbox label', () => { const { result } = renderHook(() => useLabelActions(INBOX)); expect(result.current[0]).toEqual(['trash', 'archive', 'spam']); }); it('should render correct action for drafts and all drafts label', () => { const resDrafts = renderHook(() => useLabelActions(DRAFTS)); expect(resDrafts.result.current[0]).toEqual(['trash', 'archive', 'delete']); const resAllDrafts = renderHook(() => useLabelActions(ALL_DRAFTS)); expect(resAllDrafts.result.current[0]).toEqual(['trash', 'archive', 'delete']); }); it('should render correct action for sent and all sent label', () => { const resSent = renderHook(() => useLabelActions(SENT)); expect(resSent.result.current[0]).toEqual(['trash', 'archive', 'delete']); const resAllSent = renderHook(() => useLabelActions(ALL_SENT)); expect(resAllSent.result.current[0]).toEqual(['trash', 'archive', 'delete']); }); it('should render correct action for scheduled and snooze label', () => { const resScheduled = renderHook(() => useLabelActions(SCHEDULED)); expect(resScheduled.result.current[0]).toEqual(['trash', 'archive']); const resSnoozed = renderHook(() => useLabelActions(SNOOZED)); expect(resSnoozed.result.current[0]).toEqual(['trash', 'archive']); }); it('should render correct action for starred label', () => { const { result } = renderHook(() => useLabelActions(STARRED)); expect(result.current[0]).toEqual(['trash', 'archive', 'spam']); }); it('should render correct action for archive label', () => { const { result } = renderHook(() => useLabelActions(ARCHIVE)); expect(result.current[0]).toEqual(['trash', 'inbox', 'spam']); }); it('should render correct action for spam label', () => { const { result } = renderHook(() => useLabelActions(SPAM)); expect(result.current[0]).toEqual(['trash', 'nospam', 'delete']); }); it('should render correct action for trash label', () => { const { result } = renderHook(() => useLabelActions(TRASH)); expect(result.current[0]).toEqual(['inbox', 'archive', 'delete']); }); it('should render correct action for all mail and almost all mail label', () => { const resAllMail = renderHook(() => useLabelActions(ALL_MAIL)); expect(resAllMail.result.current[0]).toEqual(['trash', 'archive', 'spam']); const resAlmostAllMail = renderHook(() => useLabelActions(ALMOST_ALL_MAIL)); expect(resAlmostAllMail.result.current[0]).toEqual(['trash', 'archive', 'spam']); }); it('should render correct action for custom folder label', () => { const customFolder = 'customFolder'; const customLabel = 'customLabel'; useFoldersMock.mockReturnValue([[{ ID: customFolder }], jest.fn()]); useLabelsMock.mockReturnValue([[{ ID: customLabel }], jest.fn()]); const resFolders = renderHook(() => useLabelActions(customFolder)); expect(resFolders.result.current[0]).toEqual(['trash', 'archive', 'spam']); const resLabels = renderHook(() => useLabelActions(customLabel)); expect(resLabels.result.current[0]).toEqual(['trash', 'archive', 'spam']); }); });
3,957
0
petrpan-code/ProtonMail/WebClients/applications/mail/src/app
petrpan-code/ProtonMail/WebClients/applications/mail/src/app/hooks/useMoveSystemFolders.helpers.test.ts
import { MAILBOX_LABEL_IDS } from '@proton/shared/lib/constants'; import { SYSTEM_FOLDER_SECTION, SystemFolder } from './useMoveSystemFolders'; import { moveSystemFolders } from './useMoveSystemFolders.helpers'; const INBOX: SystemFolder = { labelID: MAILBOX_LABEL_IDS.INBOX, display: SYSTEM_FOLDER_SECTION.MAIN, order: 1, payloadExtras: { Color: 'white', Name: 'undefined', }, icon: 'alias', ID: 'payloadID', text: 'text', visible: true, }; const DRAFTS: SystemFolder = { labelID: MAILBOX_LABEL_IDS.DRAFTS, display: SYSTEM_FOLDER_SECTION.MAIN, order: 2, payloadExtras: { Color: 'white', Name: 'undefined', }, icon: 'alias', ID: 'payloadID', text: 'text', visible: true, }; const SENT: SystemFolder = { labelID: MAILBOX_LABEL_IDS.SENT, display: SYSTEM_FOLDER_SECTION.MAIN, order: 3, payloadExtras: { Color: 'white', Name: 'undefined', }, icon: 'alias', ID: 'payloadID', text: 'text', visible: true, }; const ALL_SENT: SystemFolder = { labelID: MAILBOX_LABEL_IDS.ALL_SENT, display: SYSTEM_FOLDER_SECTION.MAIN, order: 4, payloadExtras: { Color: 'white', Name: 'undefined', }, icon: 'alias', ID: 'payloadID', text: 'text', visible: false, }; const SCHEDULED: SystemFolder = { labelID: MAILBOX_LABEL_IDS.SCHEDULED, display: SYSTEM_FOLDER_SECTION.MAIN, order: 4, payloadExtras: { Color: 'white', Name: 'undefined', }, icon: 'alias', ID: 'payloadID', text: 'text', visible: true, }; const ARCHIVE_MORE: SystemFolder = { labelID: MAILBOX_LABEL_IDS.ARCHIVE, display: SYSTEM_FOLDER_SECTION.MORE, order: 5, payloadExtras: { Color: 'white', Name: 'undefined', }, icon: 'alias', ID: 'payloadID', text: 'text', visible: true, }; const ALL_MAIL_MORE: SystemFolder = { labelID: MAILBOX_LABEL_IDS.ALL_MAIL, display: SYSTEM_FOLDER_SECTION.MORE, order: 6, payloadExtras: { Color: 'white', Name: 'undefined', }, icon: 'alias', ID: 'payloadID', text: 'text', visible: true, }; const SPAM_MORE: SystemFolder = { labelID: MAILBOX_LABEL_IDS.SPAM, display: SYSTEM_FOLDER_SECTION.MORE, order: 7, payloadExtras: { Color: 'white', Name: 'undefined', }, icon: 'alias', ID: 'payloadID', text: 'text', visible: true, }; describe('moveSystemFolders', () => { describe('inbox', () => { it('Should not move when dragged', () => { const navItems: SystemFolder[] = [INBOX, DRAFTS, SENT, SCHEDULED]; expect(moveSystemFolders(MAILBOX_LABEL_IDS.INBOX, MAILBOX_LABEL_IDS.DRAFTS, navItems)).toEqual(navItems); }); it('Should not move when dropped', () => { const navItems: SystemFolder[] = [INBOX, DRAFTS, SENT, SCHEDULED]; expect(moveSystemFolders(MAILBOX_LABEL_IDS.DRAFTS, MAILBOX_LABEL_IDS.INBOX, navItems)).toEqual(navItems); expect(moveSystemFolders(MAILBOX_LABEL_IDS.SENT, MAILBOX_LABEL_IDS.INBOX, navItems)).toEqual([ INBOX, { ...SENT, order: 2 }, { ...DRAFTS, order: 3 }, SCHEDULED, ]); }); it('Should allow drop', () => { const navItems: SystemFolder[] = [INBOX, DRAFTS, SCHEDULED, ARCHIVE_MORE, ALL_MAIL_MORE]; const movedFolders = moveSystemFolders(MAILBOX_LABEL_IDS.ARCHIVE, MAILBOX_LABEL_IDS.INBOX, navItems); expect(movedFolders).toEqual([ INBOX, { ...ARCHIVE_MORE, order: 2, display: SYSTEM_FOLDER_SECTION.MAIN }, { ...DRAFTS, order: 3 }, { ...SCHEDULED, order: 4 }, { ...ALL_MAIL_MORE, order: 5 }, ]); }); }); describe('item', () => { it('Should move withing main section', () => { const navItems: SystemFolder[] = [INBOX, DRAFTS, SENT, SCHEDULED]; // From top to bottom expect(moveSystemFolders(MAILBOX_LABEL_IDS.DRAFTS, MAILBOX_LABEL_IDS.SCHEDULED, navItems)).toEqual([ INBOX, { ...SENT, order: 2 }, { ...SCHEDULED, order: 3 }, { ...DRAFTS, order: 4 }, ]); // From bottom to top expect(moveSystemFolders(MAILBOX_LABEL_IDS.SCHEDULED, MAILBOX_LABEL_IDS.DRAFTS, navItems)).toEqual([ INBOX, { ...SCHEDULED, order: 2 }, { ...DRAFTS, order: 3 }, { ...SENT, order: 4 }, ]); }); it('Should change section (main to more) when dropped over "more" folder', () => { const navItems: SystemFolder[] = [INBOX, DRAFTS, SENT, SCHEDULED, ARCHIVE_MORE, ALL_MAIL_MORE, SPAM_MORE]; expect(moveSystemFolders(MAILBOX_LABEL_IDS.SCHEDULED, 'MORE_FOLDER_ITEM', navItems)).toEqual([ INBOX, DRAFTS, SENT, { ...ARCHIVE_MORE, order: 4 }, { ...ALL_MAIL_MORE, order: 5 }, { ...SPAM_MORE, order: 6 }, { ...SCHEDULED, order: 7, display: SYSTEM_FOLDER_SECTION.MORE }, ]); expect(moveSystemFolders(MAILBOX_LABEL_IDS.SENT, 'MORE_FOLDER_ITEM', navItems)).toEqual([ INBOX, DRAFTS, { ...SCHEDULED, order: 3 }, { ...ARCHIVE_MORE, order: 4 }, { ...ALL_MAIL_MORE, order: 5 }, { ...SPAM_MORE, order: 6 }, { ...SENT, order: 7, display: SYSTEM_FOLDER_SECTION.MORE }, ]); // Should take the last main element if more section is empty const navItemsWithMoreEmpty: SystemFolder[] = [INBOX, DRAFTS, SENT, SCHEDULED]; expect(moveSystemFolders(MAILBOX_LABEL_IDS.SENT, 'MORE_FOLDER_ITEM', navItemsWithMoreEmpty)).toEqual([ INBOX, DRAFTS, { ...SCHEDULED, order: 3 }, { ...SENT, order: 4, display: SYSTEM_FOLDER_SECTION.MORE }, ]); }); it('Should stay in "more" section when dropped on first MORE element', () => { const navItems: SystemFolder[] = [INBOX, DRAFTS, SENT, SCHEDULED, ARCHIVE_MORE, ALL_MAIL_MORE, SPAM_MORE]; expect(moveSystemFolders(MAILBOX_LABEL_IDS.ALL_MAIL, MAILBOX_LABEL_IDS.ARCHIVE, navItems)).toEqual([ INBOX, DRAFTS, SENT, SCHEDULED, { ...ALL_MAIL_MORE, order: 5 }, { ...ARCHIVE_MORE, order: 6 }, SPAM_MORE, ]); }); it('should move linked label such as sent, all sent', () => { const navItems: SystemFolder[] = [INBOX, DRAFTS, SENT, ALL_SENT, SCHEDULED]; expect(moveSystemFolders(MAILBOX_LABEL_IDS.SENT, MAILBOX_LABEL_IDS.INBOX, navItems)).toEqual([ INBOX, { ...ALL_SENT, order: 2 }, { ...SENT, order: 3 }, { ...DRAFTS, order: 4 }, { ...SCHEDULED, order: 5 }, ]); }); }); });
3,965
0
petrpan-code/ProtonMail/WebClients/applications/mail/src/app
petrpan-code/ProtonMail/WebClients/applications/mail/src/app/hooks/useShouldMoveOut.test.ts
import useShouldMoveOut from './useShouldMoveOut'; describe('useShouldMoveOut', () => { it('should move out if elementID is not in elementIDs', () => { const onBack = jest.fn(); useShouldMoveOut({ elementID: '1', elementIDs: ['2', '3'], onBack, loadingElements: false, }); expect(onBack).toHaveBeenCalled(); }); it('should do nothing if elements are loading', () => { const onBack = jest.fn(); useShouldMoveOut({ elementID: '1', elementIDs: ['2', '3'], onBack, loadingElements: true, }); expect(onBack).not.toHaveBeenCalled(); }); it('should move out if elementID is not defined', () => { const onBack = jest.fn(); useShouldMoveOut({ elementIDs: ['2', '3'], onBack, loadingElements: false, }); expect(onBack).toHaveBeenCalled(); }); it('should move out if there is not elements', () => { const onBack = jest.fn(); useShouldMoveOut({ elementID: '1', elementIDs: [], onBack, loadingElements: false, }); expect(onBack).toHaveBeenCalled(); }); });
3,976
0
petrpan-code/ProtonMail/WebClients/applications/mail/src/app/hooks
petrpan-code/ProtonMail/WebClients/applications/mail/src/app/hooks/actions/useSnooze.test.ts
import * as reactRedux from 'react-redux'; import { act, renderHook } from '@testing-library/react-hooks'; import { useFlag } from '@proton/components/containers'; import useSnooze from './useSnooze'; jest.mock('@proton/components/containers/unleash'); jest.mock('react-redux', () => ({ ...jest.requireActual('react-redux'), useSelector: jest.fn(), })); jest.mock('@proton/components/hooks', () => ({ useUser: () => [{ hasPaidMail: false }, jest.fn], })); jest.mock('@proton/components/hooks', () => ({ useEventManager: () => ({ call: jest.fn(), stop: jest.fn(), start: jest.fn() }), useNotifications: () => ({ createNotification: jest.fn() }), useApi: () => jest.fn(), })); jest.mock('../optimistic/useOptimisticApplyLabels', () => ({ useOptimisticApplyLabels: () => jest.fn(), })); jest.mock('../../logic/store', () => ({ useAppDispatch: () => jest.fn(), })); describe('useSnooze', () => { const useSelectorMock = reactRedux.useSelector as jest.Mock; const mockedUseFlag = useFlag as jest.Mock; beforeEach(() => { useSelectorMock.mockReturnValue({ labelID: '0', conversationMode: true }); mockedUseFlag.mockReturnValue(true); }); afterEach(() => { useSelectorMock.mockClear(); }); it('canSnooze should be true when in inbox and conversation mode', () => { useSelectorMock.mockReturnValue({ labelID: '0', conversationMode: true }); const { result } = renderHook(() => useSnooze()); expect(result.current.canSnooze).toEqual(true); expect(result.current.isSnoozeEnabled).toEqual(true); }); it('canSnooze should be false when in inbox and not conversation mode', () => { useSelectorMock.mockReturnValue({ labelID: '0', conversationMode: false }); const { result } = renderHook(() => useSnooze()); expect(result.current.canSnooze).toEqual(false); expect(result.current.isSnoozeEnabled).toEqual(true); }); it('canUnsnooze should be true when in snooze and conversation mode', () => { useSelectorMock.mockReturnValue({ labelID: '16', conversationMode: true }); const { result } = renderHook(() => useSnooze()); expect(result.current.canUnsnooze).toEqual(true); expect(result.current.isSnoozeEnabled).toEqual(true); }); it('canUnsnooze should be false when in snooze and not conversation mode', () => { useSelectorMock.mockReturnValue({ labelID: '16', conversationMode: false }); const { result } = renderHook(() => useSnooze()); expect(result.current.canUnsnooze).toEqual(false); expect(result.current.isSnoozeEnabled).toEqual(true); }); it('isSnoozeEnabled should be false when flag is off', () => { mockedUseFlag.mockReturnValue(false); const { result } = renderHook(() => useSnooze()); expect(result.current.isSnoozeEnabled).toEqual(false); }); it('should update snooze state after custom click and close', () => { const { result } = renderHook(() => useSnooze()); expect(result.current.snoozeState).toEqual('snooze-selection'); act(() => { result.current.handleCustomClick(); }); expect(result.current.snoozeState).toEqual('custom-snooze'); act(() => { result.current.handleClose(); }); expect(result.current.snoozeState).toEqual('snooze-selection'); }); });
3,999
0
petrpan-code/ProtonMail/WebClients/applications/mail/src/app/hooks
petrpan-code/ProtonMail/WebClients/applications/mail/src/app/hooks/composer/useSendVerifications.test.ts
import loudRejection from 'loud-rejection'; import { MIME_TYPES, MIME_TYPES_MORE, PGP_SCHEMES } from '@proton/shared/lib/constants'; import { EncryptionPreferences } from '@proton/shared/lib/mail/encryptionPreferences'; import { PACKAGE_TYPE } from '@proton/shared/lib/mail/mailSettings'; import getSendPreferences from '@proton/shared/lib/mail/send/getSendPreferences'; import { clearAll, renderHook } from '../../helpers/test/helper'; import { SendInfo } from '../../models/crypto'; import { useSendVerifications } from './useSendVerifications'; loudRejection(); const createMessage: (emailAddress: string) => {} = (emailAddress) => ({ data: { ToList: [{ Address: emailAddress, Name: 'test' }], CCList: [], BCCList: [], }, }); const mockEncryptionPreferences: { [email: string]: EncryptionPreferences } = { '[email protected]': { sign: true, encrypt: true, isSendKeyPinned: true, isContactSignatureVerified: true, contactSignatureTimestamp: new Date(), // irrelevant fields scheme: PGP_SCHEMES.PGP_MIME, mimeType: MIME_TYPES_MORE.AUTOMATIC, apiKeys: [], pinnedKeys: [], verifyingPinnedKeys: [], isInternal: true, hasApiKeys: true, hasPinnedKeys: true, isContact: true, isInternalWithDisabledE2EEForMail: false, }, '[email protected]': { sign: true, encrypt: true, isSendKeyPinned: false, isContactSignatureVerified: undefined, contactSignatureTimestamp: undefined, // irrelevant fields scheme: PGP_SCHEMES.PGP_MIME, mimeType: MIME_TYPES_MORE.AUTOMATIC, apiKeys: [], pinnedKeys: [], verifyingPinnedKeys: [], isInternal: true, hasApiKeys: true, hasPinnedKeys: false, isContact: true, isInternalWithDisabledE2EEForMail: false, }, '[email protected]': { sign: true, encrypt: true, isSendKeyPinned: false, isContactSignatureVerified: true, contactSignatureTimestamp: new Date(), // irrelevant fields scheme: PGP_SCHEMES.PGP_MIME, mimeType: MIME_TYPES_MORE.AUTOMATIC, apiKeys: [], pinnedKeys: [], verifyingPinnedKeys: [], isInternal: true, hasApiKeys: true, hasPinnedKeys: false, isContact: true, isInternalWithDisabledE2EEForMail: false, }, '[email protected]': { sign: true, encrypt: true, isSendKeyPinned: true, isContactSignatureVerified: true, contactSignatureTimestamp: new Date(), // irrelevant fields scheme: PGP_SCHEMES.PGP_MIME, mimeType: MIME_TYPES_MORE.AUTOMATIC, apiKeys: [], pinnedKeys: [], verifyingPinnedKeys: [], isInternal: true, hasApiKeys: true, hasPinnedKeys: true, isContact: true, isInternalWithDisabledE2EEForMail: true, }, '[email protected]': { sign: true, encrypt: true, isSendKeyPinned: true, isContactSignatureVerified: true, contactSignatureTimestamp: new Date(), // irrelevant fields scheme: PGP_SCHEMES.PGP_MIME, mimeType: MIME_TYPES_MORE.AUTOMATIC, apiKeys: [], pinnedKeys: [], verifyingPinnedKeys: [], isInternal: false, hasApiKeys: false, hasPinnedKeys: true, isContact: true, isInternalWithDisabledE2EEForMail: false, }, '[email protected]': { sign: true, encrypt: false, isSendKeyPinned: false, isContactSignatureVerified: undefined, contactSignatureTimestamp: undefined, // irrelevant fields scheme: PGP_SCHEMES.PGP_MIME, mimeType: MIME_TYPES_MORE.AUTOMATIC, apiKeys: [], pinnedKeys: [], verifyingPinnedKeys: [], isInternal: false, hasApiKeys: false, hasPinnedKeys: false, isContact: true, isInternalWithDisabledE2EEForMail: false, }, '[email protected]': { sign: true, encrypt: false, isSendKeyPinned: true, isContactSignatureVerified: true, contactSignatureTimestamp: new Date(), // irrelevant fields scheme: PGP_SCHEMES.PGP_MIME, mimeType: MIME_TYPES_MORE.AUTOMATIC, apiKeys: [], pinnedKeys: [], verifyingPinnedKeys: [], isInternal: false, hasApiKeys: false, hasPinnedKeys: true, isContact: true, isInternalWithDisabledE2EEForMail: false, }, }; const mockCreateModalSpy = jest.fn(({ ...props }) => { props.props.onSubmit(); }); jest.mock('@proton/components', () => { const componentsMock = jest.requireActual('@proton/components'); const useGetEncryptionPreferences = () => { const getEncryptionPreferences: ({ email }: { email: string }) => EncryptionPreferences = ({ email }) => mockEncryptionPreferences[email]; return getEncryptionPreferences; }; return { __esModule: true, ...componentsMock, useModals: function () { return { createModal: mockCreateModalSpy, }; }, useGetEncryptionPreferences, }; }); const originalResizeObserver = window.ResizeObserver; const ResizeObserverMock = jest.fn(() => ({ disconnect: jest.fn(), observe: jest.fn(), unobserve: jest.fn(), })); beforeAll(() => { window.ResizeObserver = ResizeObserverMock; }); afterAll(() => { window.ResizeObserver = originalResizeObserver; }); describe('useSendVerifications', () => { const setup = async () => { const result = await renderHook(() => useSendVerifications()); return result.result.current.extendedVerifications as any; }; afterEach(clearAll); describe('extended verifications of last-minute preferences', () => { // eslint-disable-next-line no-only-tests/no-only-tests it('should warn user on deletion of contact with pinned keys (internal)', async () => { const recipient = '[email protected]'; const cachedPreferences: SendInfo = { sendPreferences: { encrypt: true, sign: true, isPublicKeyPinned: true, hasApiKeys: true, hasPinnedKeys: true, pgpScheme: PACKAGE_TYPE.SEND_PM, mimeType: MIME_TYPES.DEFAULT, encryptionDisabled: false, }, contactSignatureInfo: { isVerified: true, creationTime: new Date(), }, loading: false, emailValidation: true, }; const extendedVerifications = await setup(); const message = createMessage(recipient); const mapSendInfo = { [recipient]: cachedPreferences }; const { mapSendPrefs } = await extendedVerifications(message, mapSendInfo); expect(mockCreateModalSpy).toHaveBeenCalled(); // user was warned const lastMinutePreferences = mockEncryptionPreferences[recipient]; expect(mapSendPrefs[recipient]).toStrictEqual(getSendPreferences(lastMinutePreferences, message)); // sanity checks expect(mapSendPrefs[recipient].encrypt).toBe(true); expect(mapSendPrefs[recipient].isPublicKeyPinned).toBe(false); }); it('should warn user on deletion of contact with pinned keys (external)', async () => { const recipient = '[email protected]'; const cachedPreferences: SendInfo = { sendPreferences: { encrypt: true, sign: true, isPublicKeyPinned: true, hasApiKeys: true, hasPinnedKeys: true, pgpScheme: PACKAGE_TYPE.SEND_PM, mimeType: MIME_TYPES.DEFAULT, encryptionDisabled: false, }, contactSignatureInfo: { isVerified: true, creationTime: new Date(), }, loading: false, emailValidation: true, }; const extendedVerifications = await setup(); const message = createMessage(recipient); const mapSendInfo = { [recipient]: cachedPreferences }; const { mapSendPrefs } = await extendedVerifications(message, mapSendInfo); expect(mockCreateModalSpy).toHaveBeenCalled(); // user was warned const lastMinutePreferences = mockEncryptionPreferences[recipient]; expect(mapSendPrefs[recipient]).toStrictEqual(getSendPreferences(lastMinutePreferences, message)); // sanity checks expect(mapSendPrefs[recipient].encrypt).toBe(false); expect(mapSendPrefs[recipient].isPublicKeyPinned).toBe(false); }); it('should warn user on encryption disabled with contact with pinned keys (internal case only)', async () => { const recipient = '[email protected]'; const lastMinutePreferences = mockEncryptionPreferences[recipient]; const cachedPreferences: SendInfo = { sendPreferences: { encrypt: true, sign: true, isPublicKeyPinned: true, hasApiKeys: true, hasPinnedKeys: true, pgpScheme: PACKAGE_TYPE.SEND_PM, mimeType: MIME_TYPES.DEFAULT, encryptionDisabled: false, }, contactSignatureInfo: { isVerified: true, creationTime: new Date(+lastMinutePreferences.contactSignatureTimestamp!), }, loading: false, emailValidation: true, }; const extendedVerifications = await setup(); const message = createMessage(recipient); const mapSendInfo = { [recipient]: cachedPreferences }; const { mapSendPrefs } = await extendedVerifications(message, mapSendInfo); expect(mockCreateModalSpy).toHaveBeenCalled(); // user was warned expect(mapSendPrefs[recipient]).toStrictEqual(getSendPreferences(lastMinutePreferences, message)); // sanity checks expect(mapSendPrefs[recipient].encrypt).toBe(false); expect(mapSendPrefs[recipient].isPublicKeyPinned).toBe(true); }); it('should silently send with last-minute prefs on contact deletion with encryption disabled (external)', async () => { const recipient = '[email protected]'; const cachedPreferences: SendInfo = { sendPreferences: { sign: true, encrypt: false, isPublicKeyPinned: true, hasApiKeys: false, hasPinnedKeys: true, pgpScheme: PACKAGE_TYPE.SEND_PGP_MIME, mimeType: MIME_TYPES.MIME, encryptionDisabled: false, }, contactSignatureInfo: { isVerified: true, creationTime: new Date(), }, loading: false, emailValidation: true, }; const extendedVerifications = await setup(); const message = createMessage(recipient); const mapSendInfo = { [recipient]: cachedPreferences }; const { mapSendPrefs } = await extendedVerifications(message, mapSendInfo); expect(mockCreateModalSpy).not.toHaveBeenCalled(); // user was not warned const lastMinutePreferences = mockEncryptionPreferences[recipient]; expect(mapSendPrefs[recipient]).toStrictEqual(getSendPreferences(lastMinutePreferences, message)); // sanity checks expect(mapSendPrefs[recipient].encrypt).toBe(false); expect(mapSendPrefs[recipient].isPublicKeyPinned).toBe(false); }); it('should silently send with last-minute prefs on last-minute unpinning via new signature (internal)', async () => { const recipient = '[email protected]'; const lastMinutePreferences = mockEncryptionPreferences[recipient]; const cachedPreferences: SendInfo = { sendPreferences: { sign: true, encrypt: true, isPublicKeyPinned: true, hasApiKeys: true, hasPinnedKeys: true, pgpScheme: PACKAGE_TYPE.SEND_PM, mimeType: MIME_TYPES.DEFAULT, encryptionDisabled: false, }, contactSignatureInfo: { isVerified: true, creationTime: new Date(+lastMinutePreferences.contactSignatureTimestamp! - 1), }, loading: false, emailValidation: true, }; const extendedVerifications = await setup(); const message = createMessage(recipient); const mapSendInfo = { [recipient]: cachedPreferences }; const { mapSendPrefs } = await extendedVerifications(message, mapSendInfo); expect(mockCreateModalSpy).not.toHaveBeenCalled(); // user was not warned expect(mapSendPrefs[recipient]).toStrictEqual(getSendPreferences(lastMinutePreferences, message)); // sanity checks expect(mapSendPrefs[recipient].encrypt).toBe(true); expect(mapSendPrefs[recipient].isPublicKeyPinned).toBe(false); }); it('should silently send with last-minute prefs on last-minute encryption disabling via new signature (external)', async () => { const recipient = '[email protected]'; const lastMinutePreferences = mockEncryptionPreferences[recipient]; const cachedPreferences: SendInfo = { sendPreferences: { sign: true, encrypt: true, isPublicKeyPinned: true, hasApiKeys: false, hasPinnedKeys: true, pgpScheme: PACKAGE_TYPE.SEND_PGP_MIME, mimeType: MIME_TYPES.MIME, encryptionDisabled: false, }, contactSignatureInfo: { isVerified: true, creationTime: new Date(+lastMinutePreferences.contactSignatureTimestamp! - 1), }, loading: false, emailValidation: true, }; const extendedVerifications = await setup(); const message = createMessage(recipient); const mapSendInfo = { [recipient]: cachedPreferences }; const { mapSendPrefs } = await extendedVerifications(message, mapSendInfo); expect(mockCreateModalSpy).not.toHaveBeenCalled(); // user was not warned expect(mapSendPrefs[recipient]).toStrictEqual(getSendPreferences(lastMinutePreferences, message)); // sanity checks expect(mapSendPrefs[recipient].encrypt).toBe(false); expect(mapSendPrefs[recipient].isPublicKeyPinned).toBe(true); }); it('should silently send with cached prefs on last-minute unpinning via old signature (internal)', async () => { const recipient = '[email protected]'; const lastMinutePreferences = mockEncryptionPreferences[recipient]; const cachedPreferences: SendInfo = { sendPreferences: { sign: true, encrypt: true, isPublicKeyPinned: true, hasApiKeys: true, hasPinnedKeys: true, pgpScheme: PACKAGE_TYPE.SEND_PM, mimeType: MIME_TYPES.DEFAULT, encryptionDisabled: false, }, contactSignatureInfo: { isVerified: true, creationTime: new Date(+lastMinutePreferences.contactSignatureTimestamp! + 1), }, loading: false, emailValidation: true, }; const extendedVerifications = await setup(); const message = createMessage(recipient); const mapSendInfo = { [recipient]: cachedPreferences }; const { mapSendPrefs } = await extendedVerifications(message, mapSendInfo); expect(mockCreateModalSpy).not.toHaveBeenCalled(); // user was not warned expect(mapSendPrefs[recipient]).toStrictEqual(cachedPreferences.sendPreferences); // sanity checks expect(mapSendPrefs[recipient].encrypt).toBe(true); expect(mapSendPrefs[recipient].isPublicKeyPinned).toBe(true); }); it('should silently send with cached prefs on last-minute encryption disabling via old signature (external)', async () => { const recipient = '[email protected]'; const lastMinutePreferences = mockEncryptionPreferences[recipient]; const cachedPreferences: SendInfo = { sendPreferences: { sign: true, encrypt: true, isPublicKeyPinned: true, hasApiKeys: false, hasPinnedKeys: true, pgpScheme: PACKAGE_TYPE.SEND_PGP_MIME, mimeType: MIME_TYPES.DEFAULT, encryptionDisabled: false, }, contactSignatureInfo: { isVerified: true, creationTime: new Date(+lastMinutePreferences.contactSignatureTimestamp! + 1), }, loading: false, emailValidation: true, }; const extendedVerifications = await setup(); const message = createMessage(recipient); const mapSendInfo = { [recipient]: cachedPreferences }; const { mapSendPrefs } = await extendedVerifications(message, mapSendInfo); expect(mockCreateModalSpy).not.toHaveBeenCalled(); // user was not warned expect(mapSendPrefs[recipient]).toStrictEqual(cachedPreferences.sendPreferences); // sanity checks expect(mapSendPrefs[recipient].encrypt).toBe(true); expect(mapSendPrefs[recipient].isPublicKeyPinned).toBe(true); }); it('should silently send with last-minute prefs on last-minute key pinning (internal)', async () => { const recipient = '[email protected]'; const lastMinutePreferences = mockEncryptionPreferences[recipient]; const cachedPreferences: SendInfo = { sendPreferences: { sign: true, encrypt: true, isPublicKeyPinned: false, hasApiKeys: true, hasPinnedKeys: false, pgpScheme: PACKAGE_TYPE.SEND_PM, mimeType: MIME_TYPES.DEFAULT, encryptionDisabled: false, }, contactSignatureInfo: { isVerified: undefined, creationTime: undefined, }, loading: false, emailValidation: true, }; const extendedVerifications = await setup(); const message = createMessage(recipient); const mapSendInfo = { [recipient]: cachedPreferences }; const { mapSendPrefs } = await extendedVerifications(message, mapSendInfo); expect(mockCreateModalSpy).not.toHaveBeenCalled(); // user was not warned expect(mapSendPrefs[recipient]).toStrictEqual(getSendPreferences(lastMinutePreferences, message)); // sanity checks expect(mapSendPrefs[recipient].encrypt).toBe(true); expect(mapSendPrefs[recipient].isPublicKeyPinned).toBe(true); }); it('should silently send with last-minute prefs on encryption enabled last-minute (external)', async () => { const recipient = '[email protected]'; const lastMinutePreferences = mockEncryptionPreferences[recipient]; const cachedPreferences: SendInfo = { sendPreferences: { sign: true, encrypt: false, isPublicKeyPinned: true, hasApiKeys: false, hasPinnedKeys: true, pgpScheme: PACKAGE_TYPE.SEND_PGP_MIME, mimeType: MIME_TYPES.MIME, encryptionDisabled: false, }, contactSignatureInfo: { isVerified: true, creationTime: new Date(+lastMinutePreferences.contactSignatureTimestamp! - 1), }, loading: false, emailValidation: true, }; const extendedVerifications = await setup(); const message = createMessage(recipient); const mapSendInfo = { [recipient]: cachedPreferences }; const { mapSendPrefs } = await extendedVerifications(message, mapSendInfo); expect(mockCreateModalSpy).not.toHaveBeenCalled(); // user was not warned expect(mapSendPrefs[recipient]).toStrictEqual(getSendPreferences(lastMinutePreferences, message)); // sanity checks expect(mapSendPrefs[recipient].encrypt).toBe(true); expect(mapSendPrefs[recipient].isPublicKeyPinned).toBe(true); }); it('should silently send with last-minute prefs for non-contacts (internal)', async () => { const recipient = '[email protected]'; const lastMinutePreferences = mockEncryptionPreferences[recipient]; const cachedPreferences: SendInfo = { sendPreferences: { sign: true, encrypt: true, isPublicKeyPinned: false, hasApiKeys: true, hasPinnedKeys: false, pgpScheme: PACKAGE_TYPE.SEND_PGP_MIME, mimeType: MIME_TYPES.MIME, encryptionDisabled: false, }, contactSignatureInfo: { isVerified: undefined, creationTime: undefined, }, loading: false, emailValidation: true, }; const extendedVerifications = await setup(); const message = createMessage(recipient); const mapSendInfo = { [recipient]: cachedPreferences }; const { mapSendPrefs } = await extendedVerifications(message, mapSendInfo); expect(mockCreateModalSpy).not.toHaveBeenCalled(); // user was not warned expect(mapSendPrefs[recipient]).toStrictEqual(getSendPreferences(lastMinutePreferences, message)); // sanity checks expect(mapSendPrefs[recipient].encrypt).toBe(true); expect(mapSendPrefs[recipient].isPublicKeyPinned).toBe(false); }); it('should silently send with last-minute prefs for non-contacts (external)', async () => { const recipient = '[email protected]'; const lastMinutePreferences = mockEncryptionPreferences[recipient]; const cachedPreferences: SendInfo = { sendPreferences: { sign: true, encrypt: false, isPublicKeyPinned: false, hasApiKeys: false, hasPinnedKeys: false, pgpScheme: PACKAGE_TYPE.SEND_PGP_MIME, mimeType: MIME_TYPES.MIME, encryptionDisabled: false, }, contactSignatureInfo: { isVerified: undefined, creationTime: undefined, }, loading: false, emailValidation: true, }; const extendedVerifications = await setup(); const message = createMessage(recipient); const mapSendInfo = { [recipient]: cachedPreferences }; const { mapSendPrefs } = await extendedVerifications(message, mapSendInfo); expect(mockCreateModalSpy).not.toHaveBeenCalled(); // user was not warned expect(mapSendPrefs[recipient]).toStrictEqual(getSendPreferences(lastMinutePreferences, message)); // sanity checks expect(mapSendPrefs[recipient].encrypt).toBe(false); expect(mapSendPrefs[recipient].isPublicKeyPinned).toBe(false); }); it('should silently send with last-minute prefs if no trusted send prefs are given', async () => { const recipient = '[email protected]'; const lastMinutePreferences = mockEncryptionPreferences[recipient]; const extendedVerifications = await setup(); const message = createMessage(recipient); const { mapSendPrefs } = await extendedVerifications(message, {}); expect(mockCreateModalSpy).not.toHaveBeenCalled(); // user was not warned expect(mapSendPrefs[recipient]).toStrictEqual(getSendPreferences(lastMinutePreferences, message)); // sanity checks expect(mapSendPrefs[recipient].encrypt).toBe(true); expect(mapSendPrefs[recipient].isPublicKeyPinned).toBe(true); }); }); });
4,023
0
petrpan-code/ProtonMail/WebClients/applications/mail/src/app/hooks
petrpan-code/ProtonMail/WebClients/applications/mail/src/app/hooks/mailbox/useFolderNavigationHotkeys.test.tsx
import { KeyboardKey } from '@proton/shared/lib/interfaces'; import { ALMOST_ALL_MAIL, SHORTCUTS, SHOW_MOVED } from '@proton/shared/lib/mail/mailSettings'; import { mockUseHistory, mockUseMailSettings } from '@proton/testing/index'; import { useFolderNavigationHotkeys } from './useFolderNavigationHotkeys'; jest.mock('@proton/shared/lib/shortcuts/helpers', () => ({ __esModule: true, isBusy: jest.fn(() => false) })); const event = { stopPropagation: jest.fn(), preventDefault: jest.fn(), } as unknown as KeyboardEvent; describe('useFolderNavigationHotkeys', () => { const mockedPush = jest.fn(); beforeEach(() => { mockUseHistory({ push: mockedPush }); mockUseMailSettings([{ Shortcuts: 1 }]); }); afterEach(() => { mockedPush.mockClear(); }); it('should return correct helper', () => { const shortcuts = useFolderNavigationHotkeys(); expect(shortcuts).toHaveLength(8); const firstShortCut = shortcuts[0]; expect(firstShortCut).toStrictEqual(['G', 'I', expect.anything()]); (firstShortCut[2] as (e: KeyboardEvent) => void)(event); expect(mockedPush).toHaveBeenCalledTimes(1); expect(mockedPush).toHaveBeenCalledWith('/inbox'); mockedPush.mockClear(); const secondShortCut = shortcuts[1]; expect(secondShortCut).toStrictEqual(['G', 'D', expect.anything()]); (secondShortCut[2] as (e: KeyboardEvent) => void)(event); expect(mockedPush).toHaveBeenCalledTimes(1); expect(mockedPush).toHaveBeenCalledWith('/drafts'); mockedPush.mockClear(); const thirdShortCut = shortcuts[2]; expect(thirdShortCut).toStrictEqual(['G', 'E', expect.anything()]); (thirdShortCut[2] as (e: KeyboardEvent) => void)(event); expect(mockedPush).toHaveBeenCalledTimes(1); expect(mockedPush).toHaveBeenCalledWith('/sent'); mockedPush.mockClear(); const fourthShortCut = shortcuts[3]; expect(fourthShortCut).toStrictEqual(['G', KeyboardKey.Star, expect.anything()]); (fourthShortCut[2] as (e: KeyboardEvent) => void)(event); expect(mockedPush).toHaveBeenCalledTimes(1); expect(mockedPush).toHaveBeenCalledWith('/starred'); mockedPush.mockClear(); const fifthShortCut = shortcuts[4]; expect(fifthShortCut).toStrictEqual(['G', 'A', expect.anything()]); (fifthShortCut[2] as (e: KeyboardEvent) => void)(event); expect(mockedPush).toHaveBeenCalledTimes(1); expect(mockedPush).toHaveBeenCalledWith('/archive'); mockedPush.mockClear(); const sixthShortCut = shortcuts[5]; expect(sixthShortCut).toStrictEqual(['G', 'S', expect.anything()]); (sixthShortCut[2] as (e: KeyboardEvent) => void)(event); expect(mockedPush).toHaveBeenCalledTimes(1); expect(mockedPush).toHaveBeenCalledWith('/spam'); mockedPush.mockClear(); const seventhShortCut = shortcuts[6]; expect(seventhShortCut).toStrictEqual(['G', 'T', expect.anything()]); (seventhShortCut[2] as (e: KeyboardEvent) => void)(event); expect(mockedPush).toHaveBeenCalledTimes(1); expect(mockedPush).toHaveBeenCalledWith('/trash'); mockedPush.mockClear(); const eigthShortCut = shortcuts[7]; expect(eigthShortCut).toStrictEqual(['G', 'M', expect.anything()]); (eigthShortCut[2] as (e: KeyboardEvent) => void)(event); expect(mockedPush).toHaveBeenCalledTimes(1); expect(mockedPush).toHaveBeenCalledWith('/all-mail'); mockedPush.mockClear(); }); describe('when shortcut is set to false', () => { it('should return no shortcut', () => { mockUseMailSettings([{ Shortcuts: SHORTCUTS.DISABLED }]); const shortcuts = useFolderNavigationHotkeys(); expect(shortcuts).toHaveLength(0); }); }); describe('when ShowMoved is true', () => { it('should navigate to correct url', () => { mockUseMailSettings([{ Shortcuts: SHORTCUTS.ENABLED, ShowMoved: SHOW_MOVED.DRAFTS }]); const shortcuts = useFolderNavigationHotkeys(); expect(shortcuts).toHaveLength(8); const secondShortCut = shortcuts[1]; expect(secondShortCut).toStrictEqual(['G', 'D', expect.anything()]); (secondShortCut[2] as (e: KeyboardEvent) => void)(event); expect(mockedPush).toHaveBeenCalledTimes(1); expect(mockedPush).toHaveBeenCalledWith('/all-drafts'); mockedPush.mockClear(); }); }); describe('when AlmostAllMail is true', () => { it('should navigate to correct url', () => { mockUseMailSettings([{ Shortcuts: SHORTCUTS.ENABLED, AlmostAllMail: ALMOST_ALL_MAIL.ENABLED }]); const shortcuts = useFolderNavigationHotkeys(); expect(shortcuts).toHaveLength(8); const eigthShortCut = shortcuts[7]; expect(eigthShortCut).toStrictEqual(['G', 'M', expect.anything()]); (eigthShortCut[2] as (e: KeyboardEvent) => void)(event); expect(mockedPush).toHaveBeenCalledTimes(1); expect(mockedPush).toHaveBeenCalledWith('/almost-all-mail'); mockedPush.mockClear(); }); }); });
4,033
0
petrpan-code/ProtonMail/WebClients/applications/mail/src/app/hooks
petrpan-code/ProtonMail/WebClients/applications/mail/src/app/hooks/message/useFutureTimeDate.test.tsx
import { act, renderHook } from '@testing-library/react-hooks'; import { addDays, addHours, format, isSameDay, isSameHour, set, startOfTomorrow, startOfYesterday } from 'date-fns'; import { dateLocale } from '@proton/shared/lib/i18n'; import { getMinScheduleTime } from '../../helpers/schedule'; import useFutureTimeDate from './useFutureTimeDate'; describe('useFutureTimeDate', () => { it('should return no errors and the new date if date is changed to tomorrow', () => { const tomorrow = startOfTomorrow(); const { result } = renderHook(() => useFutureTimeDate({ defaultDate: new Date() })); act(() => { result.current.handleChangeDate(tomorrow); }); expect(result.current.errorDate).toBeUndefined(); expect(result.current.date).toEqual(tomorrow); }); it('should not change anything if no date is passed to handleChangeDate', () => { const date = new Date(); const { result } = renderHook(() => useFutureTimeDate({ defaultDate: date })); act(() => { result.current.handleChangeDate(); }); expect(result.current.errorDate).toBeUndefined(); expect(result.current.date).toEqual(date); }); it('should return an error if date is changed to yesterday', () => { const yesterday = startOfYesterday(); const { result } = renderHook(() => useFutureTimeDate({ defaultDate: new Date() })); act(() => { result.current.handleChangeDate(yesterday); }); expect(result.current.errorDate).toBe('Choose a date in the future.'); }); it('should return custom error if date is larger than max day', () => { const future = addDays(new Date(), 20); const { result } = renderHook(() => useFutureTimeDate({ defaultDate: new Date(), maxDaysAllowed: 10, maxDateErrorMessage: 'Custom error' }) ); act(() => { result.current.handleChangeDate(future); }); expect(isSameDay(addDays(new Date(), 10), result.current.maxDate ?? startOfTomorrow())).toBe(true); expect(result.current.errorDate).toBe('Custom error'); }); it('should return next available slot when changing date to today with time before now', () => { const today = new Date(); const before = set(today, { hours: today.getHours() - 2 }); // Set the time to the start of the hour to avoid issue if we're more than 30 minutes into the hour const defaultDate = set(today, { minutes: 0, seconds: 0, milliseconds: 0 }); const { result } = renderHook(() => useFutureTimeDate({ defaultDate })); act(() => { result.current.handleChangeDate(before); }); const nextAvailableTime = getMinScheduleTime(before); // make sure the test fails if nextAvailableTime is undefined by comparing it to yesterday expect(isSameDay(result.current.date, nextAvailableTime ?? startOfYesterday())).toBe(true); expect(isSameHour(result.current.date, nextAvailableTime ?? startOfYesterday())).toBe(true); }); it('should return no errors and the new time if time is changed to the future', () => { const inTwoHours = addHours(new Date(), 2); const { result } = renderHook(() => useFutureTimeDate({ defaultDate: new Date() })); act(() => { result.current.handleChangeTime(inTwoHours); }); expect(result.current.errorTime).toBeUndefined(); expect(result.current.time).toEqual(inTwoHours); }); it('should return today if date is set to today', () => { const { result } = renderHook(() => useFutureTimeDate({ defaultDate: new Date() })); const today = new Date(); let res = result.current.formatDateInput(today, { code: 'en-US' }); expect(res).toEqual('Today'); const tomorrow = startOfTomorrow(); res = result.current.formatDateInput(tomorrow, { code: 'en-US' }); expect(res).toEqual('Tomorrow'); const inTwoDays = addDays(new Date(), 2); const formatted = format(inTwoDays, 'PP', { locale: dateLocale }); res = result.current.formatDateInput(inTwoDays, dateLocale); expect(res).toEqual(formatted); }); it('should update date and time', () => { const randomDateInFuture = set(new Date(), { year: 2100, month: 10, date: 10, hours: 10, minutes: 10, seconds: 10, }); const { result } = renderHook(() => useFutureTimeDate({ defaultDate: new Date() })); act(() => { result.current.updateDateAndTime(randomDateInFuture); }); expect(result.current.date).toEqual(randomDateInFuture); expect(result.current.time).toEqual(randomDateInFuture); }); });
4,053
0
petrpan-code/ProtonMail/WebClients/applications/mail/src/app
petrpan-code/ProtonMail/WebClients/applications/mail/src/app/logic/snoozehelpers.test.ts
import { format, getUnixTime, nextMonday, nextSaturday, set } from 'date-fns'; import { MAILBOX_LABEL_IDS } from '@proton/shared/lib/constants'; import { Element } from '../models/element'; import { getSnoozeDate, getSnoozeNotificationText, getSnoozeTimeFromElement, getSnoozeUnixTime } from './snoozehelpers'; describe('snooze helpers - getSnoozeUnixTime', () => { it('Should return tomorrow 9 when snooze duration is tomorrow', () => { const tomorrow = new Date(); tomorrow.setDate(tomorrow.getDate() + 1); tomorrow.setHours(9, 0, 0, 0); expect(getSnoozeUnixTime('tomorrow')).toEqual(tomorrow.getTime() / 1000); }); it('Should return two days from now 9 when snooze duration is later', () => { const twoDaysFromNow = new Date(); twoDaysFromNow.setDate(twoDaysFromNow.getDate() + 2); twoDaysFromNow.setHours(9, 0, 0, 0); expect(getSnoozeUnixTime('later')).toEqual(twoDaysFromNow.getTime() / 1000); }); it('Should return next Saturday 9 when snooze duration is weekend', () => { const nextSat = nextSaturday(new Date()); nextSat.setHours(9, 0, 0, 0); expect(getSnoozeUnixTime('weekend')).toEqual(nextSat.getTime() / 1000); }); it('Should return next Monday 9 when snooze duration is nextweek', () => { const nextMon = nextMonday(new Date()); nextMon.setHours(9, 0, 0, 0); expect(getSnoozeUnixTime('nextweek')).toEqual(nextMon.getTime() / 1000); }); it('Should throw an error when no snooze time for custom duration', () => { expect(() => getSnoozeUnixTime('custom')).toThrowError('Snooze time is required for custom snooze'); }); it('Should return unix time of custom time', () => { const futureDate = set(new Date(), { year: 2030, month: 10, date: 10, minutes: 0, seconds: 0, milliseconds: 0, hours: 9, }); expect(getSnoozeUnixTime('custom', futureDate)).toEqual(futureDate.getTime() / 1000); }); }); describe('snooze helpers - getSnoozeNotificationText', () => { it('Should return snooze notification text when snooze is true', () => { expect(getSnoozeNotificationText(true, 1)).toEqual('1 conversation snoozed'); expect(getSnoozeNotificationText(true, 2)).toEqual('2 conversations snoozed'); }); it('Should return unsnooze notification text when snooze is false', () => { expect(getSnoozeNotificationText(false, 1)).toEqual('1 conversation unsnoozed'); expect(getSnoozeNotificationText(false, 2)).toEqual('2 conversations unsnoozed'); }); }); describe('snooze helpers - getSnoozeTimeFromElement', () => { it('Should return undefined when no element', () => { expect(getSnoozeTimeFromElement()).toEqual(undefined); }); it('Should return undefined when element is not a conversation', () => { expect(getSnoozeTimeFromElement({} as Element)).toEqual(undefined); }); it('Should return snooze time when element is a conversation and has a snooze label', () => { const snoozeTime = new Date().getTime(); expect( getSnoozeTimeFromElement({ Labels: [{ ID: MAILBOX_LABEL_IDS.SNOOZED, ContextSnoozeTime: snoozeTime }], } as Element) ).toEqual(snoozeTime); }); it('Should return snooze time when element is a conversation and has a inbox label', () => { const snoozeTime = new Date().getTime(); expect( getSnoozeTimeFromElement({ Labels: [{ ID: MAILBOX_LABEL_IDS.INBOX, ContextSnoozeTime: snoozeTime }], } as Element) ).toEqual(snoozeTime); }); it('Should return undefined when element is a conversation and has no snooze label', () => { expect( getSnoozeTimeFromElement({ Labels: [{ ID: MAILBOX_LABEL_IDS.DRAFTS }], } as Element) ).toEqual(undefined); }); it('Should return snooze time when element is a message', () => { const snoozeTime = new Date().getTime(); expect( getSnoozeTimeFromElement({ ConversationID: 'conversationID', SnoozeTime: snoozeTime, } as Element) ).toEqual(snoozeTime); }); it('Should return undefined when element is a message and has no snooze time', () => { expect( getSnoozeTimeFromElement({ ConversationID: 'conversationID', } as Element) ).toEqual(undefined); }); }); describe('snooze helpers - getSnoozeDate', () => { const isSameTime = (date1: Date, date2: Date) => { const formatter = 'yyyy-MM-dd HH:mm:ss'; return format(date1, formatter) === format(date2, formatter); }; it('Should return current date when no element', () => { expect(isSameTime(getSnoozeDate(undefined, '1'), new Date())); }); it('Should return current date when element is not a conversation', () => { expect(isSameTime(getSnoozeDate({} as Element, '1'), new Date())); }); it('Should return snooze date when element is a conversation and has a snooze label', () => { const now = new Date(); const date = getSnoozeDate( { Labels: [{ ID: MAILBOX_LABEL_IDS.SNOOZED, ContextSnoozeTime: getUnixTime(now) }], } as Element, '1' ); expect(isSameTime(date, now)); }); });
4,079
0
petrpan-code/ProtonMail/WebClients/applications/mail/src/app/logic/elements
petrpan-code/ProtonMail/WebClients/applications/mail/src/app/logic/elements/helpers/elementBypassFilters.test.ts
import { MARK_AS_STATUS } from '../../../hooks/actions/useMarkAs'; import { Element } from '../../../models/element'; import { getElementsToBypassFilter } from './elementBypassFilters'; describe('getElementsToBypassFilter', () => { const elements = [{ ID: 'message1' } as Element, { ID: 'message2' } as Element] as Element[]; it.each` unreadFilter | markAsAction | elementsToBypass | elementsToRemove ${0} | ${MARK_AS_STATUS.READ} | ${[]} | ${elements} ${1} | ${MARK_AS_STATUS.UNREAD} | ${[]} | ${elements} ${0} | ${MARK_AS_STATUS.UNREAD} | ${elements} | ${[]} ${1} | ${MARK_AS_STATUS.READ} | ${elements} | ${[]} ${undefined} | ${MARK_AS_STATUS.READ} | ${[]} | ${[]} ${undefined} | ${MARK_AS_STATUS.UNREAD} | ${[]} | ${[]} `( 'it should return the expected elementsToBypass when unreadFilter is [$unreadFilter] and marking elements as [$markAsAction]', ({ unreadFilter, markAsAction, elementsToBypass, elementsToRemove }) => { const expected = { elementsToBypass, elementsToRemove }; expect(getElementsToBypassFilter(elements, markAsAction, unreadFilter)).toEqual(expected); } ); });
4,082
0
petrpan-code/ProtonMail/WebClients/applications/mail/src/app/logic/elements
petrpan-code/ProtonMail/WebClients/applications/mail/src/app/logic/elements/helpers/elementTotal.test.ts
import { LabelCount } from '@proton/shared/lib/interfaces'; import { getTotal } from './elementTotal'; describe('getTotal', () => { it('should return the correct count with no filter', () => { const labelID = '1'; const labelCounts = [ { LabelID: labelID, Total: 45, Unread: 45, }, ] as LabelCount[]; expect(getTotal(labelCounts, labelID, {}, 0)).toEqual(45); }); it('should return the correct count with unread filter', () => { const labelID = '1'; const labelCounts = [ { LabelID: labelID, Total: 45, Unread: 40, }, ] as LabelCount[]; expect(getTotal(labelCounts, labelID, { Unread: 1 }, 0)).toEqual(40); }); it('should return the correct count with read filter', () => { const labelID = '1'; const labelCounts = [ { LabelID: labelID, Total: 45, Unread: 40, }, ] as LabelCount[]; expect(getTotal(labelCounts, labelID, { Unread: 0 }, 0)).toEqual(5); }); it('should return the correct count with unread filter and bypassFilter', () => { const labelID = '1'; const labelCounts = [ { LabelID: labelID, Total: 55, Unread: 50, }, ] as LabelCount[]; expect(getTotal(labelCounts, labelID, { Unread: 1 }, 5)).toEqual(55); }); it('should return the correct count with unread filter and bypassFilter', () => { const labelID = '1'; const labelCounts = [ { LabelID: labelID, Total: 55, Unread: 5, }, ] as LabelCount[]; expect(getTotal(labelCounts, labelID, { Unread: 0 }, 5)).toEqual(55); }); });
4,710
0
petrpan-code/ProtonMail/WebClients/applications/verify/src
petrpan-code/ProtonMail/WebClients/applications/verify/src/app/App.test.tsx
describe('App', () => { it('should run a test', () => { expect(true).toBe(true); }); });
4,809
0
petrpan-code/ProtonMail/WebClients/packages/activation/src/components/Modals
petrpan-code/ProtonMail/WebClients/packages/activation/src/components/Modals/ConfirmLeaveModal/ConfirmLeaveModal.test.tsx
import { fireEvent, screen } from '@testing-library/dom'; import { easySwitchRender } from '@proton/activation/src/tests/render'; import ConfirmLeaveModal from './ConfirmLeaveModal'; describe('Test confirm leave modal', () => { it('Should trigger close events', () => { const handleClose = jest.fn(); const handleContinue = jest.fn(); easySwitchRender(<ConfirmLeaveModal handleClose={handleClose} handleContinue={handleContinue} />); const cancel = screen.getByTestId('ConfirmLeaveModal:discard'); fireEvent.click(cancel); expect(handleClose).toBeCalledTimes(1); }); it('Should trigger continue events', () => { const handleClose = jest.fn(); const handleContinue = jest.fn(); easySwitchRender(<ConfirmLeaveModal handleClose={handleClose} handleContinue={handleContinue} />); const submit = screen.getByTestId('ConfirmLeaveModal:continue'); fireEvent.click(submit); expect(handleContinue).toBeCalledTimes(1); }); });
4,812
0
petrpan-code/ProtonMail/WebClients/packages/activation/src/components/Modals
petrpan-code/ProtonMail/WebClients/packages/activation/src/components/Modals/CustomizeMailImportModal/CustomizeMailImportModal.test.tsx
import { fireEvent, screen, waitFor } from '@testing-library/dom'; import { ApiMailImporterFolder } from '@proton/activation/src/api/api.interface'; import MailImportFoldersParser from '@proton/activation/src/helpers/MailImportFoldersParser/MailImportFoldersParser'; import { MailImportDestinationFolder, TIME_PERIOD } from '@proton/activation/src/interface'; import { easySwitchRender } from '@proton/activation/src/tests/render'; import { ModalStateProps } from '@proton/components'; import { ADDRESS_STATUS, ADDRESS_TYPE } from '@proton/shared/lib/constants'; import { Address } from '@proton/shared/lib/interfaces'; import CustomizeMailImportModal from './CustomizeMailImportModal'; import { MailImportFields } from './CustomizeMailImportModal.interface'; const address: Address = { DisplayName: 'Testing', DomainID: 'proton.ch', Email: '[email protected]', HasKeys: 1, ID: 'ID', Keys: [], SignedKeyList: null, Order: 1, Priority: 1, Receive: 1, Send: 1, Signature: 'Testing signature', Status: ADDRESS_STATUS.STATUS_ENABLED, Type: ADDRESS_TYPE.TYPE_ORIGINAL, ProtonMX: false, ConfirmationState: 1, CatchAll: false, }; const isLabelMapping = false; const simpleProviderFolders: ApiMailImporterFolder[] = [ { Source: 'New Name', Separator: '/', Size: 10, Flags: [], }, ]; const simpleFields: MailImportFields = { mapping: new MailImportFoldersParser(simpleProviderFolders, isLabelMapping).folders, importLabel: { Color: '#fff', Name: 'label', Type: 1 }, importPeriod: TIME_PERIOD.LAST_MONTH, importAddress: address, importCategoriesDestination: MailImportDestinationFolder.INBOX, }; const providerFolderWithError: ApiMailImporterFolder[] = [ { Source: 'Scheduled', Separator: '/', Size: 10, Flags: [], }, ]; const getModalProps = (): ModalStateProps => { const key = new Date(); return { key: key.getTime().toString(), open: true, onClose: () => {}, onExit: () => {}, }; }; describe('Customize modal tests', () => { it('Should display the customize folder modal and close it with save button', () => { easySwitchRender( <CustomizeMailImportModal foldersOpened={false} fields={simpleFields} importedEmail="[email protected]" isLabelMapping={false} onSubmit={() => {}} displayCategories={false} modalProps={getModalProps()} /> ); const saveButton = screen.getByTestId('CustomizeModal:modalSave'); fireEvent.click(saveButton); }); it('Should display the customize folder modal and close it with cancel button', () => { easySwitchRender( <CustomizeMailImportModal foldersOpened={false} fields={simpleFields} importedEmail="[email protected]" isLabelMapping={false} onSubmit={() => {}} displayCategories={false} modalProps={getModalProps()} /> ); const cancelButton = screen.getByTestId('CustomizeModal:modalCancel'); fireEvent.click(cancelButton); }); it('Should display the customize folder modal', () => { easySwitchRender( <CustomizeMailImportModal foldersOpened={false} fields={simpleFields} importedEmail="[email protected]" isLabelMapping={false} onSubmit={() => {}} displayCategories={false} modalProps={getModalProps()} /> ); screen.getByTestId('CustomizeModal:folderHeader'); // Display folders const showFolderButton = screen.getByTestId('CustomizeModal:toggleFolders'); fireEvent.click(showFolderButton); screen.getByTestId('CustomizeModal:destinationItem'); // Toggle folder checkbox const checkboxes = screen.getAllByTestId('CustomizeModal:checkbox'); fireEvent.click(checkboxes[0]); fireEvent.click(checkboxes[0]); // Close folders fireEvent.click(showFolderButton); expect(screen.queryByTestId('CustomizeModal:destinationItem')).toBeNull(); // Open and close the edit label modal const editLabelButton = screen.getByTestId('CustomizeModal:editLabel'); fireEvent.click(editLabelButton); screen.getByTestId('label-modal'); const editLabelCloseButton = screen.getByTestId('label-modal:cancel'); fireEvent.click(editLabelCloseButton); // Change default time period const select = screen.getByText('Last month only'); fireEvent.click(select); fireEvent.click(screen.getByText('Last 3 months only')); // Close modal and expect confirmation modal and close it const cancelButton = screen.getByTestId('CustomizeModal:modalCancel'); fireEvent.click(cancelButton); screen.getByTestId('CancelModal:container'); const closeModal = screen.getByTestId('CancelModal:cancel'); fireEvent.click(closeModal); // Click again the cancel button but cancel the changes this time fireEvent.click(cancelButton); const quitModal = screen.getByTestId('CancelModal:quit'); fireEvent.click(quitModal); }); it('Should display the customize label modal', async () => { const onSubmit = jest.fn(); easySwitchRender( <CustomizeMailImportModal foldersOpened={false} fields={simpleFields} importedEmail="[email protected]" isLabelMapping={true} displayCategories={true} onSubmit={onSubmit} modalProps={getModalProps()} /> ); screen.getByTestId('CustomizeModal:labelHeader'); const showFolderButton = screen.getByTestId('CustomizeModal:toggleFolders'); fireEvent.click(showFolderButton); screen.getByTestId('CustomizeModal:destinationItem'); fireEvent.click(showFolderButton); expect(screen.queryByTestId('CustomizeModal:destinationItem')).toBeNull(); // Expect to see gmail categories screen.getByTestId('CustomizeModal:gmailCategories'); // Change the Gmail category const select = screen.getByText('Move to Inbox'); fireEvent.click(select); fireEvent.click(screen.getByText('Move to Archive')); // Submit the change and verify the new payload const modalSave = screen.getByTestId('CustomizeModal:modalSave'); fireEvent.click(modalSave); expect(onSubmit).toHaveBeenCalledTimes(1); expect(onSubmit).toHaveBeenCalledWith({ ...simpleFields, importCategoriesDestination: MailImportDestinationFolder.ARCHIVE, }); }); it('Should display an error if folder is reserved and save buttons should be disabled', () => { const fields: MailImportFields = { mapping: new MailImportFoldersParser(providerFolderWithError, isLabelMapping).folders, importLabel: { Color: '#fff', Name: 'label', Type: 1 }, importPeriod: TIME_PERIOD.LAST_MONTH, importAddress: address, importCategoriesDestination: MailImportDestinationFolder.ALL_DRAFTS, }; const onSubmit = jest.fn(); easySwitchRender( <CustomizeMailImportModal foldersOpened={true} fields={fields} importedEmail="[email protected]" isLabelMapping={false} displayCategories={false} onSubmit={onSubmit} modalProps={getModalProps()} /> ); const input = screen.getByDisplayValue('Scheduled'); const rowSave = screen.getAllByTestId('CustomizeModal:rowSave'); const modalSave = screen.getByTestId('CustomizeModal:modalSave'); expect(input).toBeInvalid(); expect(modalSave).toBeDisabled(); rowSave.every((item) => expect(item).toBeDisabled()); fireEvent.click(modalSave); rowSave.forEach((item) => fireEvent.click(item)); expect(onSubmit).toHaveBeenCalledTimes(0); }); it('Should remove error if error is fixed and save buttons should be enabled', async () => { const fields: MailImportFields = { mapping: new MailImportFoldersParser(providerFolderWithError, isLabelMapping).folders, importLabel: { Color: '#fff', Name: 'label', Type: 1 }, importPeriod: TIME_PERIOD.LAST_MONTH, importAddress: address, importCategoriesDestination: MailImportDestinationFolder.ALL_DRAFTS, }; const onSubmit = jest.fn(); easySwitchRender( <CustomizeMailImportModal foldersOpened={true} fields={fields} importedEmail="[email protected]" isLabelMapping={false} displayCategories={false} onSubmit={onSubmit} modalProps={getModalProps()} /> ); const input = screen.getByDisplayValue('Scheduled'); const rowSave = screen.getAllByTestId('CustomizeModal:rowSave'); const modalSave = screen.getByTestId('CustomizeModal:modalSave'); expect(modalSave).toBeDisabled(); expect(input).toBeInvalid(); rowSave.every((item) => expect(item).toBeDisabled()); fireEvent.click(modalSave); rowSave.forEach((item) => { fireEvent.click(item); }); expect(onSubmit).toHaveBeenCalledTimes(0); // Fix the error by changing input and click the buttons again fireEvent.change(input, { target: { value: 'New Name' } }); await waitFor(() => expect(input).toBeValid()); rowSave.every((item) => expect(item).toBeEnabled()); rowSave.forEach((item) => { fireEvent.click(item); }); expect(modalSave).toBeEnabled(); fireEvent.click(modalSave); expect(onSubmit).toHaveBeenCalledTimes(1); // Update initial mapping to have the new folder name const newMapping = fields.mapping; newMapping[0].protonPath = ['New Name']; expect(onSubmit).toHaveBeenCalledWith({ ...fields, mapping: newMapping }); }); it('Should update the payload when the selected period changes', () => { const onSubmit = jest.fn(); easySwitchRender( <CustomizeMailImportModal foldersOpened={false} fields={simpleFields} importedEmail="[email protected]" isLabelMapping={false} displayCategories={false} onSubmit={onSubmit} modalProps={getModalProps()} /> ); const select = screen.getByText('Last month only'); const rowSave = screen.queryAllByTestId('CustomizeModal:rowSave'); const modalSave = screen.getByTestId('CustomizeModal:modalSave'); expect(rowSave.length).toBe(0); fireEvent.click(select); fireEvent.click(screen.getByText('Last 3 months only')); fireEvent.click(modalSave); expect(onSubmit).toHaveBeenCalledTimes(1); expect(onSubmit).toHaveBeenCalledWith({ ...simpleFields, importPeriod: TIME_PERIOD.LAST_3_MONTHS }); }); it('Should display warning when cancelling changes in modal', () => { const onSubmit = jest.fn(); easySwitchRender( <CustomizeMailImportModal foldersOpened={false} fields={simpleFields} importedEmail="[email protected]" isLabelMapping={false} displayCategories={false} onSubmit={onSubmit} modalProps={getModalProps()} /> ); const select = screen.getByText('Last month only'); const rowSave = screen.queryAllByTestId('CustomizeModal:rowSave'); const modalCancel = screen.getByTestId('CustomizeModal:modalCancel'); expect(rowSave.length).toBe(0); fireEvent.click(select); fireEvent.click(screen.getByText('Last 3 months only')); fireEvent.click(modalCancel); screen.getByTestId('CancelModal:container'); }); it('Should indent folders in source and destination', () => { const providerFolders = [ 'Parent', 'Parent/Children', 'Parent/Children/SubChildren', 'Parent/Children/SubChildren/FinalChildren', ].map( (source) => ({ Source: source, Separator: '/', }) as ApiMailImporterFolder ); const nestedFields: MailImportFields = { mapping: new MailImportFoldersParser(providerFolders, isLabelMapping).folders, importLabel: { Color: '#fff', Name: 'label', Type: 1 }, importPeriod: TIME_PERIOD.LAST_MONTH, importAddress: address, importCategoriesDestination: MailImportDestinationFolder.ALL_DRAFTS, }; const onSubmit = jest.fn(); easySwitchRender( <CustomizeMailImportModal foldersOpened={true} fields={nestedFields} importedEmail="[email protected]" isLabelMapping={false} displayCategories={false} onSubmit={onSubmit} modalProps={getModalProps()} /> ); const sourceItems = screen.getAllByTestId('CustomizeModal:sourceItem'); sourceItems.every((item, index) => { expect(item).toHaveStyle(`--ml-custom: ${index + 1}em`); }); const destinationItem = screen.getAllByTestId('CustomizeModal:destinationItem'); destinationItem.forEach((item, index) => { if (index < 3) { expect(item).toHaveStyle(`--ml-custom: ${index + 1}em`); } else { expect(item).toHaveStyle('--ml-custom: 3em'); } }); }); it('Should display destinationFolder name instead of source in proton import column', () => { const providerFolders = [ { Source: 'INBOX', Separator: '/', DestinationFolder: 'Inbox', } as ApiMailImporterFolder, { Source: '[Gmail]/Sent Mail', Separator: '/', DestinationFolder: 'Sent', } as ApiMailImporterFolder, { Source: '[Gmail]/Drafts', Separator: '/', DestinationFolder: 'Drafts', } as ApiMailImporterFolder, ]; const nestedFields: MailImportFields = { mapping: new MailImportFoldersParser(providerFolders, isLabelMapping).folders, importLabel: { Color: '#fff', Name: 'label', Type: 1 }, importPeriod: TIME_PERIOD.LAST_MONTH, importAddress: address, importCategoriesDestination: MailImportDestinationFolder.ALL_DRAFTS, }; const onSubmit = jest.fn(); easySwitchRender( <CustomizeMailImportModal foldersOpened={true} fields={nestedFields} importedEmail="[email protected]" isLabelMapping={true} displayCategories={false} onSubmit={onSubmit} modalProps={getModalProps()} /> ); expect(screen.getAllByTestId('CustomizeModal:FolderRow:providerName').map((node) => node.textContent)).toEqual([ 'INBOX', '[Gmail]/Sent Mail', '[Gmail]/Drafts', ]); expect(screen.getAllByTestId('CustomizeModal:FolderRow:protonName').map((node) => node.textContent)).toEqual([ 'Inbox', 'Sent', 'Drafts', ]); }); });
4,814
0
petrpan-code/ProtonMail/WebClients/packages/activation/src/components/Modals
petrpan-code/ProtonMail/WebClients/packages/activation/src/components/Modals/CustomizeMailImportModal/CustomizeMailImportModalAddresses.test.tsx
import { fireEvent, screen, waitFor } from '@testing-library/dom'; import useAvailableAddresses from '@proton/activation/src/hooks/useAvailableAddresses'; import { generateMockAddressArray } from '@proton/activation/src/tests/data/addresses'; import { easySwitchRender } from '@proton/activation/src/tests/render'; import CustomizeMailImportModalAddresses from './CustomizeMailImportModalAddresses'; jest.mock('@proton/activation/src/hooks/useAvailableAddresses'); const mockUseAvailableAddresses = useAvailableAddresses as jest.MockedFunction<any>; const addresses = generateMockAddressArray(3, true); describe('CustomizeMailImportModalAddresses', () => { it('Should render simple field when one available address', async () => { mockUseAvailableAddresses.mockReturnValue({ availableAddresses: addresses, loading: false, defaultAddress: addresses[0], }); const onSubmit = jest.fn(); easySwitchRender(<CustomizeMailImportModalAddresses selectedAddressID={addresses[0].ID} onChange={onSubmit} />); const select = screen.getByTestId('CustomizeModal:addressSelect'); fireEvent.click(select); await waitFor(() => screen.getAllByTestId('CustomizeModal:addressRow')); const options = screen.getAllByTestId('CustomizeModal:addressRow'); expect(options).toHaveLength(options.length); fireEvent.click(options[1]); expect(onSubmit).toHaveBeenCalledTimes(1); expect(onSubmit).toHaveBeenCalledWith({ ...addresses[1] }); }); });
4,825
0
petrpan-code/ProtonMail/WebClients/packages/activation/src/components/Modals/CustomizeMailImportModal
petrpan-code/ProtonMail/WebClients/packages/activation/src/components/Modals/CustomizeMailImportModal/ManageFolders/useManageFolders.helpers.test.ts
import { ApiMailImporterFolder } from '@proton/activation/src/api/api.interface'; import MailImportFoldersParser from '@proton/activation/src/helpers/MailImportFoldersParser/MailImportFoldersParser'; import { folderWithChildren, getRenamedFolders } from '@proton/activation/src/tests/data/folders'; import { Label } from '@proton/shared/lib/interfaces'; import { Folder } from '@proton/shared/lib/interfaces/Folder'; import { formatItems, renameChildFolders } from './useManageFolders.helpers'; describe('renameChildFolders', () => { it('Should rename all child in proton path', () => { const folders = [...folderWithChildren]; const newFolders = [...folders]; const newFolder = { ...newFolders[0] }; const newName = 'newName'; newFolder.protonPath = [...newFolder.protonPath]; newFolder.protonPath[newFolder.protonPath.length - 1] = newName; newFolders[0] = newFolder; const renameFolders = renameChildFolders(newFolder, newFolders, newName); expect(renameFolders).toStrictEqual(getRenamedFolders(newName)); }); }); describe('formatItems', () => { it('should compare labels and not folders with mapping when isLabelMapping is false', () => { const apiFolders = ['flavien', 'guillaume'].map( (folder) => ({ Source: folder, Separator: '/' } as ApiMailImporterFolder) ); const isLabelMapping = false; const mapping = new MailImportFoldersParser(apiFolders, isLabelMapping).folders; const result = formatItems({ labels: [ { Name: 'flavien', Path: 'flavien', } as Label, ], folders: [ { Name: 'guillaume', Path: 'guillaume', } as Folder, ], isLabelMapping, mapping, }); expect(result.find((item) => item.id === 'flavien')?.errors).toContain('Unavailable names'); expect(result.find((item) => item.id === 'guillaume')?.errors).toEqual([]); }); it('should compare folders and not labels with mapping when isLabelMapping is true', () => { const apiFolders = ['flavien', 'guillaume'].map( (folder) => ({ Source: folder, Separator: '/' } as ApiMailImporterFolder) ); const isLabelMapping = true; const mapping = new MailImportFoldersParser(apiFolders, isLabelMapping).folders; const result = formatItems({ folders: [ { Name: 'flavien', Path: 'flavien', } as Folder, ], labels: [ { Name: 'guillaume', Path: 'guillaume', } as Label, ], isLabelMapping, mapping, }); expect(result.find((item) => item.id === 'flavien')?.errors).toContain('Unavailable names'); expect(result.find((item) => item.id === 'guillaume')?.errors).toEqual([]); }); });
4,830
0
petrpan-code/ProtonMail/WebClients/packages/activation/src/components/Modals/CustomizeMailImportModal/ManageFolders
petrpan-code/ProtonMail/WebClients/packages/activation/src/components/Modals/CustomizeMailImportModal/ManageFolders/ManageFoldersRow/ManageFoldersRowInput.test.tsx
import { fireEvent, screen } from '@testing-library/dom'; import { MailImportPayloadError } from '@proton/activation/src/interface'; import { easySwitchRender } from '@proton/activation/src/tests/render'; import ManageFolderRowInput from './ManageFoldersRowInput'; describe('ManageFoldersRowInput', () => { it('Should not display error', () => { easySwitchRender( <ManageFolderRowInput disabled={false} errors={[]} handleChange={jest.fn} handleSave={jest.fn} hasError={false} inputValue={''} inputRef={null} isLabelMapping={false} /> ); }); it('Should display too long error', async () => { easySwitchRender( <ManageFolderRowInput disabled={false} errors={[MailImportPayloadError.FOLDER_NAMES_TOO_LONG]} handleChange={jest.fn} handleSave={jest.fn} hasError={true} inputValue={'Testing'} inputRef={null} isLabelMapping={false} /> ); await screen.findByText('The folder name is too long. Please choose a different name.'); }); it('Should display too unavailable name error', async () => { easySwitchRender( <ManageFolderRowInput disabled={false} errors={[MailImportPayloadError.UNAVAILABLE_NAMES]} handleChange={jest.fn} handleSave={jest.fn} hasError={true} inputValue={'Testing'} inputRef={null} isLabelMapping={false} /> ); await screen.findByText('This folder name is not available. Please choose a different name.'); }); it('Should display too non empty name error', async () => { easySwitchRender( <ManageFolderRowInput disabled={false} errors={[MailImportPayloadError.EMPTY]} handleChange={jest.fn} handleSave={jest.fn} hasError={true} inputValue={'Testing'} inputRef={null} isLabelMapping={false} /> ); await screen.findByText('Folder name cannot be empty.'); }); it('Should display too reserved name error', async () => { easySwitchRender( <ManageFolderRowInput disabled={false} errors={[MailImportPayloadError.RESERVED_NAMES]} handleChange={jest.fn} handleSave={jest.fn} hasError={true} inputValue={'Testing'} inputRef={null} isLabelMapping={false} /> ); await screen.findByText('The folder name is invalid. Please choose a different name.'); }); it('Should run save method when enter is pressed', async () => { const handleSave = jest.fn(); easySwitchRender( <ManageFolderRowInput disabled={false} errors={[]} handleChange={jest.fn} handleSave={handleSave} hasError={false} inputValue={'Testing'} inputRef={null} isLabelMapping={false} /> ); const input = await screen.getByDisplayValue('Testing'); fireEvent.keyDown(input, { key: 'Enter', code: 'Enter', charCode: 13 }); expect(handleSave).toBeCalledTimes(1); }); it('Should not run save method when enter is pressed and component has error', async () => { const handleSave = jest.fn(); easySwitchRender( <ManageFolderRowInput disabled={false} errors={[MailImportPayloadError.EMPTY]} handleChange={jest.fn} handleSave={handleSave} hasError={true} inputValue={'Testing'} inputRef={null} isLabelMapping={false} /> ); const input = await screen.getByDisplayValue('Testing'); fireEvent.keyDown(input, { key: 'Enter', code: 'Enter', charCode: 13 }); expect(handleSave).toBeCalledTimes(0); }); });
4,834
0
petrpan-code/ProtonMail/WebClients/packages/activation/src/components/Modals/Imap
petrpan-code/ProtonMail/WebClients/packages/activation/src/components/Modals/Imap/ImapMailModal/ImapMailModal.test.tsx
import { fireEvent, screen, waitFor } from '@testing-library/react'; import { rest } from 'msw'; import { setupServer } from 'msw/node'; import { easySwitchRender } from '@proton/activation/src/tests/render'; import ImapMailModal from './ImapMailModal'; const server = setupServer(); beforeAll(() => { server.listen(); }); afterEach(() => server.resetHandlers()); afterAll(() => { server.close(); }); describe('IMAP Start Step', () => { it('Should render an empty form and fill server when email filled', async () => { easySwitchRender(<ImapMailModal />); const emailInput = screen.getByTestId('StepForm:emailInput'); const passwordInput = screen.getByTestId('StepForm:passwordInput'); const serverInput = screen.getByTestId('StepForm:serverInput'); const portInput = screen.getByTestId('StepForm:portInput'); const submitButton = screen.getByTestId('StepForm:submitButton'); fireEvent.change(emailInput, { target: { value: '[email protected]' } }); server.use( rest.get('/importer/v1/mail/importers/authinfo', (req, res, ctx) => { return res( ctx.set('date', '01/01/2022'), ctx.json({ Authentication: { ImapHost: 'imap.proton.ch', ImapPort: 993, }, }) ); }) ); await waitFor(() => expect(serverInput).toHaveValue('imap.proton.ch')); expect(portInput).toHaveValue('993'); expect(submitButton).toBeDisabled(); fireEvent.change(passwordInput, { target: { value: 'password' } }); await waitFor(() => expect(submitButton).toBeEnabled()); // Change server and port if there is an issue fireEvent.change(serverInput, { target: { value: 'imap.proton.me' } }); expect(serverInput).toHaveValue('imap.proton.me'); fireEvent.change(portInput, { target: { value: '995' } }); expect(portInput).toHaveValue('995'); }); });
4,842
0
petrpan-code/ProtonMail/WebClients/packages/activation/src/components/Modals/Imap/ImapMailModal/StepForm
petrpan-code/ProtonMail/WebClients/packages/activation/src/components/Modals/Imap/ImapMailModal/StepForm/hooks/useStepForm.helpers.test.ts
import { IMPORT_ERROR, ImportProvider } from '@proton/activation/src/interface'; import { getDefaultImap, getDefaultPort, validateStepForm } from './useStepForm.helpers'; import { StepFormBlur, StepFormState } from './useStepForm.interface'; describe('useStepForm', () => { it('Should validate step form without any issue', () => { const formValue: StepFormState = { emailAddress: '[email protected]', password: 'password', imap: 'imap.proton.me', port: '933', }; const blurred: StepFormBlur = { emailAddress: false, password: false, imap: false, port: false, }; const setErrors = jest.fn(); const setHasErrors = jest.fn(); validateStepForm(formValue, blurred, setErrors, setHasErrors); expect(setErrors).toHaveBeenCalledTimes(1); expect(setErrors).toHaveBeenCalledWith(undefined); expect(setHasErrors).toHaveBeenCalledTimes(1); expect(setHasErrors).toHaveBeenCalledWith(false); }); it('Should have all possible errors', () => { const formValue: StepFormState = { emailAddress: '', password: '', imap: '', port: '', }; const blurred: StepFormBlur = { emailAddress: true, password: true, imap: true, port: true, }; const setErrors = jest.fn(); const setHasErrors = jest.fn(); validateStepForm(formValue, blurred, setErrors, setHasErrors); expect(setErrors).toHaveBeenCalledTimes(1); expect(setErrors).toHaveBeenCalledWith({ emailAddress: 'Email address is required', password: 'Password is required', imap: 'IMAP server is required', port: 'Port is required', }); expect(setHasErrors).toHaveBeenCalledTimes(1); expect(setHasErrors).toHaveBeenCalledWith(true); }); it('Should test API code errors', () => { const formValue: StepFormState = { emailAddress: '[email protected]', password: 'password', imap: 'imap.proton.me', port: '933', }; const blurred: StepFormBlur = { emailAddress: false, password: false, imap: false, port: false, }; const setErrors = jest.fn(); const setHasErrors = jest.fn(); validateStepForm( formValue, blurred, setErrors, setHasErrors, IMPORT_ERROR.AUTHENTICATION_ERROR, 'api error message' ); expect(setErrors).toHaveBeenCalledTimes(1); expect(setErrors).toHaveBeenCalledWith({ emailAddress: 'api error message', password: 'api error message', }); validateStepForm( formValue, blurred, setErrors, setHasErrors, IMPORT_ERROR.IMAP_CONNECTION_ERROR, 'api error message' ); expect(setErrors).toHaveBeenCalledTimes(2); expect(setErrors).toHaveBeenCalledWith({ imap: 'api error message', port: 'api error message', }); validateStepForm( formValue, blurred, setErrors, setHasErrors, IMPORT_ERROR.ACCOUNT_DOES_NOT_EXIST, 'api error message' ); expect(setErrors).toHaveBeenCalledTimes(3); expect(setErrors).toHaveBeenCalledWith({ imap: 'api error message', port: 'api error message', }); }); it('Should return default imap and port', () => { const defaultImap = getDefaultImap(); const defaultPort = getDefaultPort(); expect(defaultImap).toStrictEqual(''); expect(defaultPort).toStrictEqual(''); const googleImap = getDefaultImap(ImportProvider.GOOGLE); const googlePort = getDefaultPort(ImportProvider.GOOGLE); expect(googleImap).toStrictEqual('imap.gmail.com'); expect(googlePort).toStrictEqual('993'); const yahooImap = getDefaultImap(ImportProvider.YAHOO); const yahooPort = getDefaultPort(ImportProvider.YAHOO); expect(yahooImap).toStrictEqual('export.imap.mail.yahoo.com'); expect(yahooPort).toStrictEqual('993'); const outlookImap = getDefaultImap(ImportProvider.OUTLOOK); const outlookPort = getDefaultPort(ImportProvider.OUTLOOK); expect(outlookImap).toStrictEqual('outlook.office365.com'); expect(outlookPort).toStrictEqual('993'); }); });
4,846
0
petrpan-code/ProtonMail/WebClients/packages/activation/src/components/Modals/Imap/ImapMailModal
petrpan-code/ProtonMail/WebClients/packages/activation/src/components/Modals/Imap/ImapMailModal/StepImporting/StepImporting.test.tsx
import { fireEvent, screen } from '@testing-library/dom'; import { easySwitchRender } from '@proton/activation/src/tests/render'; import StepImporting from './StepImporting'; describe('Step importing basic rendering testing', () => { it('Should correctly render the step importing', () => { easySwitchRender(<StepImporting />); const closeButton = screen.getByTestId('StepImport:closeButton'); fireEvent.click(closeButton); }); it('Should redirect user when not in easy switch', () => { easySwitchRender(<StepImporting />); const redirectButton = screen.getByTestId('StepImport:redirectButton'); fireEvent.click(redirectButton); }); });
4,849
0
petrpan-code/ProtonMail/WebClients/packages/activation/src/components/Modals/Imap/ImapMailModal
petrpan-code/ProtonMail/WebClients/packages/activation/src/components/Modals/Imap/ImapMailModal/StepPrepareImap/StepPrepareImap.helpers.test.ts
import { differenceInMonths, fromUnixTime } from 'date-fns'; import { ApiMailImporterFolder } from '@proton/activation/src/api/api.interface'; import MailImportFoldersParser from '@proton/activation/src/helpers/MailImportFoldersParser/MailImportFoldersParser'; import { MailImportDestinationFolder, MailImportMapping, TIME_PERIOD } from '@proton/activation/src/interface'; import { standardFolderResponse } from '@proton/activation/src/tests/data/gmail.formattedResponse'; import { gmailImapResponse } from '@proton/activation/src/tests/data/gmail.imap.formattedResponse'; import gmailImapModalLabels from '@proton/activation/src/tests/data/gmail.imap.providerFolders'; import labels from '@proton/activation/src/tests/data/gmail.providerFolders'; import { ADDRESS_STATUS, ADDRESS_TYPE } from '@proton/shared/lib/constants'; import { Address } from '@proton/shared/lib/interfaces'; import { formatPrepareStepPayload } from './StepPrepareImap.helpers'; import { StepPrepareData } from './useStepPrepareImap'; // used in MailFoldersMapping.getRandomLabelColor. jest.mock('@proton/utils/randomIntFromInterval', () => () => 0); const address: Address = { DisplayName: 'Testing', DomainID: 'proton.ch', Email: '[email protected]', HasKeys: 1, ID: 'ID', Keys: [], SignedKeyList: null, Order: 1, Priority: 1, Receive: 1, Send: 1, Signature: 'Testing signature', Status: ADDRESS_STATUS.STATUS_ENABLED, Type: ADDRESS_TYPE.TYPE_ORIGINAL, ProtonMX: true, ConfirmationState: 1, CatchAll: false, }; const providerLabels = labels.map((label) => { return { ...label, Size: 1 } as ApiMailImporterFolder; }); const correctData = { email: 'string', importerID: 'importerID', password: 'password', }; const updatedFields = { updatedLabel: true, updatedPeriod: true, updatedMapping: true, }; const isLabelMapping = true; function getBaseFields(labels?: ApiMailImporterFolder[]) { return { mapping: new MailImportFoldersParser(labels ?? providerLabels, isLabelMapping).folders, importLabel: { Color: '#fff', Name: 'label', Type: 1 }, importPeriod: TIME_PERIOD.BIG_BANG, importAddress: address, importCategoriesDestination: MailImportDestinationFolder.INBOX, }; } describe('Step prepare helpers tests', () => { describe('formatPrepareStepPayload', () => { it('Should return a standard payload (All time)', () => { const fields: StepPrepareData['fields'] = getBaseFields(); const res = formatPrepareStepPayload({ isLabelMapping, data: correctData, fields, updatedFields }); expect(res).toEqual(standardFolderResponse); }); it('Should return a standard payload (last year)', () => { const fieldsOneYear: StepPrepareData['fields'] = { ...getBaseFields(), importPeriod: TIME_PERIOD.LAST_YEAR, }; const res = formatPrepareStepPayload({ isLabelMapping, data: correctData, fields: fieldsOneYear, updatedFields, }); const { StartTime } = res.Mail; let diff = -1; if (StartTime instanceof Date) { diff = differenceInMonths(new Date(), StartTime); } else { const start = fromUnixTime(StartTime!); diff = differenceInMonths(new Date(), start); } expect(diff).toBe(12); }); it('Should return a standard payload (3 last months)', () => { const fieldsThreeMonts: StepPrepareData['fields'] = { ...getBaseFields(), importPeriod: TIME_PERIOD.LAST_3_MONTHS, }; const res = formatPrepareStepPayload({ isLabelMapping, data: correctData, fields: fieldsThreeMonts, updatedFields, }); const { StartTime } = res.Mail; let diff = -1; if (StartTime instanceof Date) { diff = differenceInMonths(new Date(), StartTime); } else { const start = fromUnixTime(StartTime!); diff = differenceInMonths(new Date(), start); } expect(diff).toBe(3); }); it('Should return a standard payload (last month)', () => { const fieldsOneMonth: StepPrepareData['fields'] = { ...getBaseFields(), importPeriod: TIME_PERIOD.LAST_MONTH, }; const res = formatPrepareStepPayload({ isLabelMapping, data: correctData, fields: fieldsOneMonth, updatedFields, }); const { StartTime } = res.Mail; let diff = -1; if (StartTime instanceof Date) { diff = differenceInMonths(new Date(), StartTime); } else { const start = fromUnixTime(StartTime!); diff = differenceInMonths(new Date(), start); } expect(diff).toBe(1); }); it('Should throw an error if importer ID is undefined ', () => { const fields: StepPrepareData['fields'] = getBaseFields(); const faultyData = { email: 'string', providerFolders: providerLabels, importerID: undefined, password: 'password', }; expect(() => formatPrepareStepPayload({ isLabelMapping, data: faultyData, fields, updatedFields }) ).toThrowError('Importer ID should be defined'); }); it('Should not submit unchecked folders', () => { const fields: StepPrepareData['fields'] = { ...getBaseFields(), mapping: new MailImportFoldersParser(providerLabels, isLabelMapping).folders.map((folder) => ({ ...folder, checked: false, })), }; expect( formatPrepareStepPayload({ isLabelMapping, data: correctData, fields, updatedFields }).Mail.Mapping .length ).toBe(0); }); it('Should send correctly formatted folders depth into payload', () => { const isLabelMapping = false; const fields: StepPrepareData['fields'] = { ...getBaseFields(), mapping: new MailImportFoldersParser( ['dude 1', 'dude 1/dude 2', 'dude 1/dude 2/dude 3', 'dude 1/dude 2/dude 3/dude 4'].map( (path) => ({ Source: path, Separator: '/', }) as ApiMailImporterFolder ), isLabelMapping ).folders, }; expect( formatPrepareStepPayload({ isLabelMapping, data: correctData, fields, updatedFields }).Mail.Mapping.map( (item) => item.Destinations.FolderPath ) ).toEqual(['dude 1', 'dude 1/dude 2', 'dude 1/dude 2/dude 3', 'dude 1/dude 2/dude 3\\/dude 4']); }); it('Should return correct payload when using Gmail account on IMAP modal', () => { const gmailImapLabels = gmailImapModalLabels.map((label) => { return { ...label, Size: 1 } as ApiMailImporterFolder; }); const fields: StepPrepareData['fields'] = getBaseFields(gmailImapLabels); const res = formatPrepareStepPayload({ isLabelMapping, data: correctData, fields, updatedFields, }); expect(res).toEqual(gmailImapResponse); }); describe('Should add `folderPath` and `label` on specific conditions', () => { const labels = getBaseFields( ['Inbox', 'dude 1', 'dude 1/dude 2'].map( (path) => ({ Source: path, Separator: '/', ...(path === 'Inbox' ? { DestinationFolder: 'Inbox' } : {}), }) as ApiMailImporterFolder ) ); const res = formatPrepareStepPayload({ isLabelMapping, data: correctData, fields: labels, updatedFields, }); it('should contain folderPath if destination folder', () => { const destinationFolder = res.Mail.Mapping.find( (label) => label.Source === 'Inbox' ) as MailImportMapping; expect(destinationFolder.Source).toEqual('Inbox'); expect('Labels' in destinationFolder.Destinations).toBe(false); expect('FolderPath' in destinationFolder.Destinations).toBe(true); expect(destinationFolder.Destinations.FolderPath).toBe('Inbox'); }); it('should contain Label if label', () => { const parentFolder = res.Mail.Mapping.find((label) => label.Source === 'dude 1') as MailImportMapping; expect(parentFolder.Source).toEqual('dude 1'); expect('Labels' in parentFolder.Destinations).toBe(true); expect('FolderPath' in parentFolder.Destinations).toBe(false); expect(parentFolder.Destinations.Labels?.[0].Name).toBe('dude 1'); }); }); }); });
4,851
0
petrpan-code/ProtonMail/WebClients/packages/activation/src/components/Modals/Imap/ImapMailModal
petrpan-code/ProtonMail/WebClients/packages/activation/src/components/Modals/Imap/ImapMailModal/StepPrepareImap/StepPrepareImap.test.tsx
import { fireEvent, screen } from '@testing-library/dom'; import useAvailableAddresses from '@proton/activation/src/hooks/useAvailableAddresses'; import { MailImportState } from '@proton/activation/src/logic/draft/imapDraft/imapDraft.interface'; import { generateMockAddressArray } from '@proton/activation/src/tests/data/addresses'; import { easySwitchRender } from '@proton/activation/src/tests/render'; import StepPrepare from './StepPrepareImap'; const data: MailImportState = { step: 'prepare-import', loading: false, domain: 'imap.proton.ch', email: '[email protected]', password: 'password', port: '993', }; jest.mock('react-redux', () => ({ ...jest.requireActual('react-redux'), useSelector: jest.fn().mockReturnValue({ mailImport: data }), })); const addresses = generateMockAddressArray(3, true); jest.mock('@proton/activation/src/hooks/useAvailableAddresses'); const mockUseAvailableAddresses = useAvailableAddresses as jest.MockedFunction<any>; describe('Step prepare basic rendering testing', () => { it('Should correctly render the step prepare', () => { mockUseAvailableAddresses.mockReturnValue({ availableAddresses: addresses, loading: false, defaultAddress: addresses[0], }); easySwitchRender(<StepPrepare />); const customizeButton = screen.getByTestId('StepPrepare:customizeButton'); fireEvent.click(customizeButton); screen.getByTestId('CustomizeModal:modalCancel'); }); });
4,868
0
petrpan-code/ProtonMail/WebClients/packages/activation/src/components/Modals
petrpan-code/ProtonMail/WebClients/packages/activation/src/components/Modals/OAuth/OAuthModal.helpers.test.ts
import { EasySwitchFeatureFlag, ImportProvider } from '@proton/activation/src/interface'; import isTruthy from '@proton/utils/isTruthy'; import { getEnabledFeature } from './OAuthModal.helpers'; describe('OAuthModal helpers', () => { it('Should return all feature enabled', () => { const featureMap: EasySwitchFeatureFlag = { GoogleMail: true, GoogleMailSync: true, GoogleCalendar: true, GoogleContacts: true, GoogleDrive: true, OutlookMail: true, OutlookCalendar: true, OutlookContacts: true, OtherMail: true, OtherCalendar: true, OtherContacts: true, OtherDrive: true, }; const googleService = getEnabledFeature(ImportProvider.GOOGLE, featureMap); expect(Object.values(googleService).every(isTruthy)).toBe(true); const outlookService = getEnabledFeature(ImportProvider.OUTLOOK, featureMap); expect(Object.values(outlookService).every(isTruthy)).toBe(true); const otherService = getEnabledFeature(ImportProvider.DEFAULT, featureMap); expect(Object.values(otherService).every(isTruthy)).toBe(false); }); it('Should return true for email and everything else false', () => { const featureMap: EasySwitchFeatureFlag = { GoogleMail: true, GoogleMailSync: true, GoogleCalendar: false, GoogleContacts: false, GoogleDrive: false, OutlookMail: true, OutlookCalendar: false, OutlookContacts: false, OtherMail: true, OtherCalendar: false, OtherContacts: false, OtherDrive: false, }; const expected = { isEmailsEnabled: true, isContactsEnabled: false, isCalendarsEnabled: false, }; const googleService = getEnabledFeature(ImportProvider.GOOGLE, featureMap); expect(googleService).toStrictEqual(expected); const outlookService = getEnabledFeature(ImportProvider.OUTLOOK, featureMap); expect(outlookService).toStrictEqual(expected); const otherService = getEnabledFeature(ImportProvider.DEFAULT, featureMap); expect(Object.values(otherService).every(isTruthy)).toBe(false); }); it('Should return true for calendar and everything else false', () => { const featureMap: EasySwitchFeatureFlag = { GoogleMail: false, GoogleMailSync: false, GoogleCalendar: true, GoogleContacts: false, GoogleDrive: false, OutlookMail: false, OutlookCalendar: true, OutlookContacts: false, OtherMail: false, OtherCalendar: true, OtherContacts: false, OtherDrive: false, }; const expected = { isEmailsEnabled: false, isContactsEnabled: false, isCalendarsEnabled: true, }; const googleService = getEnabledFeature(ImportProvider.GOOGLE, featureMap); expect(googleService).toStrictEqual(expected); const outlookService = getEnabledFeature(ImportProvider.OUTLOOK, featureMap); expect(outlookService).toStrictEqual(expected); const otherService = getEnabledFeature(ImportProvider.DEFAULT, featureMap); expect(Object.values(otherService).every(isTruthy)).toBe(false); }); it('Should return true for contact and everything else false', () => { const featureMap: EasySwitchFeatureFlag = { GoogleMail: false, GoogleMailSync: false, GoogleCalendar: false, GoogleContacts: true, GoogleDrive: false, OutlookMail: false, OutlookCalendar: false, OutlookContacts: true, OtherMail: false, OtherCalendar: false, OtherContacts: false, OtherDrive: true, }; const expected = { isEmailsEnabled: false, isContactsEnabled: true, isCalendarsEnabled: false, }; const googleService = getEnabledFeature(ImportProvider.GOOGLE, featureMap); expect(googleService).toStrictEqual(expected); const outlookService = getEnabledFeature(ImportProvider.OUTLOOK, featureMap); expect(outlookService).toStrictEqual(expected); const otherService = getEnabledFeature(ImportProvider.DEFAULT, featureMap); expect(Object.values(otherService).every(isTruthy)).toBe(false); }); });
4,870
0
petrpan-code/ProtonMail/WebClients/packages/activation/src/components/Modals
petrpan-code/ProtonMail/WebClients/packages/activation/src/components/Modals/OAuth/OAuthModal.test.tsx
import { fireEvent, screen, waitFor } from '@testing-library/react'; import { rest } from 'msw'; import { setupServer } from 'msw/node'; import { easySwitchRender } from '@proton/activation/src/tests/render'; import ProviderCards from '../../SettingsArea/ProviderCards/ProviderCards'; const server = setupServer(); jest.mock('@proton/components/hooks/useApiEnvironmentConfig', () => () => [ { 'importer.google.client_id': 'string', 'importer.outlook.client_id': 'string', }, false, ]); jest.mock('@proton/components/hooks/useUser', () => () => [ { isAdmin: true, isFree: true, isMember: true, isPaid: true, isPrivate: true, isSubUser: true, isDelinquent: true, hasNonDelinquentScope: true, hasPaidMail: true, hasPaidVpn: true, canPay: true, }, false, ]); jest.mock('@proton/components/hooks/useFeature', () => () => { return { feature: { Code: 'EasySwitch', Type: 'boolean', Global: true, DefaultValue: { GoogleMail: true, GoogleMailSync: true, GoogleCalendar: true, GoogleContacts: true, OutlookMail: true, OutlookCalendar: true, OutlookContacts: true, OtherMail: true, OtherCalendar: true, OtherContacts: true, }, Value: { GoogleMail: true, GoogleMailSync: true, GoogleCalendar: true, GoogleContacts: true, OutlookMail: true, OutlookCalendar: true, OutlookContacts: true, OtherMail: true, OtherCalendar: true, OtherContacts: true, }, Writable: false, }, }; }); beforeAll(() => { server.listen(); server.use( rest.get('/core/v4/system/config', (req, res, ctx) => { return res(ctx.set('date', '01/01/2022'), ctx.json({})); }), rest.get('/calendar/v1', (req, res, ctx) => { return res(ctx.set('date', '01/01/2022'), ctx.json({})); }) ); }); afterEach(() => { server.resetHandlers(); }); afterAll(() => { server.close(); }); describe('OAuth start step', () => { it.skip('Should render the product selection modal when clicking on Google', async () => { easySwitchRender(<ProviderCards />); const google = screen.getByTestId('ProviderCard:googleCard'); expect(google).toBeEnabled(); fireEvent.click(google); await waitFor(() => screen.getByTestId('StepProducts:modal')); }); it.skip('Should render the product selection modal when clicking on Outlook', async () => { easySwitchRender(<ProviderCards />); const outlook = screen.getByTestId('ProviderCard:outlookCard'); expect(outlook).toBeEnabled(); fireEvent.click(outlook); await waitFor(() => screen.getByTestId('StepProducts:modal')); }); it('Should render the instruction modal if Google is selected', async () => { easySwitchRender(<ProviderCards />); // Open the product modal const google = screen.getByTestId('ProviderCard:googleCard'); expect(google).toBeEnabled(); fireEvent.click(google); await waitFor(() => screen.getByTestId('StepProducts:modal')); // Submit products modal const submitProducts = screen.getByTestId('StepProducts:submit'); fireEvent.click(submitProducts); // Wait for instructions modal await waitFor(() => screen.getByTestId('StepInstruction:modal')); // Press back button on instruction modal const backButton = screen.getByTestId('StepInstruction:back'); fireEvent.click(backButton); // Expect to see products modal again await waitFor(() => screen.getByTestId('StepProducts:modal')); }); it('Should render the product modal and fire submit', async () => { server.use( rest.get('/calendar/v1', (req, res, ctx) => { return res(ctx.set('date', '01/01/2022'), ctx.json({})); }) ); easySwitchRender(<ProviderCards />); // Open the product modal const outlook = screen.getByTestId('ProviderCard:outlookCard'); expect(outlook).toBeEnabled(); fireEvent.click(outlook); await waitFor(() => screen.getByTestId('StepProducts:modal')); // Submit products modal const submitProducts = screen.getByTestId('StepProducts:submit'); fireEvent.click(submitProducts); }); it('Should render the product and instructions modal when Google is selected', async () => { server.use( rest.get('/calendar/v1', (req, res, ctx) => { return res(ctx.set('date', '01/01/2022'), ctx.json({})); }) ); easySwitchRender(<ProviderCards />); // Open the product modal const google = screen.getByTestId('ProviderCard:googleCard'); expect(google).toBeEnabled(); fireEvent.click(google); await waitFor(() => screen.getByTestId('StepProducts:modal')); // Submit products modal const submitProducts = screen.getByTestId('StepProducts:submit'); fireEvent.click(submitProducts); // Wait for instructions modal await waitFor(() => screen.getByTestId('StepInstruction:modal')); // Press submit button on instruction modal const submitButton = screen.getByTestId('StepInstruction:submit'); fireEvent.click(submitButton); }); });
4,874
0
petrpan-code/ProtonMail/WebClients/packages/activation/src/components/Modals/OAuth
petrpan-code/ProtonMail/WebClients/packages/activation/src/components/Modals/OAuth/StepLoading/StepLoadingImporter.test.tsx
import { screen } from '@testing-library/dom'; import { easySwitchRender } from '@proton/activation/src/tests/render'; import StepLoadingImporter from './StepLoadingImporter'; describe('Test correct rendering of loading importer', () => { it('Should render importer', () => { easySwitchRender(<StepLoadingImporter />); screen.getByTestId('StepLoadingImporter:modal'); }); });
4,876
0
petrpan-code/ProtonMail/WebClients/packages/activation/src/components/Modals/OAuth
petrpan-code/ProtonMail/WebClients/packages/activation/src/components/Modals/OAuth/StepLoading/StepLoadingImporting.test.tsx
import { screen } from '@testing-library/dom'; import { easySwitchRender } from '@proton/activation/src/tests/render'; import StepLoadingImporting from './StepLoadingImporting'; import useStepLoadingImporting from './useStepLoadingImporting'; jest.mock('./useStepLoadingImporting', () => ({ __esModule: true, default: jest.fn(), })); const mockStepLoadingImporting = useStepLoadingImporting as any as jest.Mock< ReturnType<typeof useStepLoadingImporting> >; describe('Test correct rendering of loading importing different states', () => { it('Should render creating importing calendar state', () => { mockStepLoadingImporting.mockImplementation(() => { return { createdCalendarCount: 10, calendarsToBeCreated: 10, isCreatingCalendar: true, isCreatingImportTask: false, }; }); easySwitchRender(<StepLoadingImporting />); screen.getByTestId('StepLoadingImporting:modal'); }); it('Should render creating importing finishing state', () => { mockStepLoadingImporting.mockImplementation(() => { return { createdCalendarCount: 10, calendarsToBeCreated: 10, isCreatingCalendar: false, isCreatingImportTask: true, }; }); easySwitchRender(<StepLoadingImporting />); screen.getByTestId('StepLoadingImporting:modal'); }); it('Should render empty state', () => { mockStepLoadingImporting.mockImplementation(() => { return { createdCalendarCount: 10, calendarsToBeCreated: 10, isCreatingCalendar: false, isCreatingImportTask: false, }; }); easySwitchRender(<StepLoadingImporting />); screen.getByTestId('StepLoadingImporting:modal'); }); });
4,880
0
petrpan-code/ProtonMail/WebClients/packages/activation/src/components/Modals/OAuth
petrpan-code/ProtonMail/WebClients/packages/activation/src/components/Modals/OAuth/StepPrepareOAuth/StepPrepareOAuth.test.tsx
import { screen } from '@testing-library/dom'; import { ApiMailImporterFolder } from '@proton/activation/src/api/api.interface'; import MailImportFoldersParser from '@proton/activation/src/helpers/MailImportFoldersParser/MailImportFoldersParser'; import { ImportType, MailImportDestinationFolder, TIME_PERIOD } from '@proton/activation/src/interface'; import { selectOauthImportStateImporterData } from '@proton/activation/src/logic/draft/oauthDraft/oauthDraft.selector'; import { generateMockAddress } from '@proton/activation/src/tests/data/addresses'; import { prepareState } from '@proton/activation/src/tests/data/prepareState'; import { easySwitchRender } from '@proton/activation/src/tests/render'; import { MailImportFields } from '../../CustomizeMailImportModal/CustomizeMailImportModal.interface'; import StepPrepare from './StepPrepareOAuth'; import useStepPrepare from './hooks/useStepPrepareOAuth'; import useStepPrepareEmailSummary from './hooks/useStepPrepareOAuthEmailSummary'; jest.mock('./hooks/useStepPrepareOAuth', () => ({ __esModule: true, default: jest.fn(), })); jest.mock('./hooks/useStepPrepareOAuthEmailSummary', () => ({ __esModule: true, default: jest.fn(), })); jest.mock('@proton/activation/src/logic/draft/oauthDraft/oauthDraft.selector', () => ({ ...jest.requireActual('@proton/activation/src/logic/draft/oauthDraft/oauthDraft.selector'), selectOauthImportStateImporterData: jest.fn(), })); const isLabelMapping = false; const simpleProviderFolders: ApiMailImporterFolder[] = [ { Source: 'New Name', Separator: '/', Size: 10, Flags: [], }, ]; const simpleFields: MailImportFields = { mapping: new MailImportFoldersParser(simpleProviderFolders, isLabelMapping).folders, importLabel: { Color: '#fff', Name: 'label', Type: 1 }, importPeriod: TIME_PERIOD.LAST_MONTH, importAddress: generateMockAddress(1, true), importCategoriesDestination: MailImportDestinationFolder.INBOX, }; const emailSummary = { fields: simpleFields, errors: [], summary: '', toEmail: '', handleSubmitCustomizeModal: () => {}, }; const mockedUseStepPrepare = useStepPrepare as jest.Mock<ReturnType<typeof useStepPrepare>>; const mockedUseStepPrepareEmailSummary = useStepPrepareEmailSummary as jest.Mock< ReturnType<typeof useStepPrepareEmailSummary> >; const mockSelectorImporterData = selectOauthImportStateImporterData as any as jest.Mock< ReturnType<typeof selectOauthImportStateImporterData> >; describe('StepPrepare test the product display, only selected products should be displayed', () => { const defaultStepPrepare = { products: [ImportType.CALENDAR, ImportType.CONTACTS, ImportType.MAIL], emailChecked: true, setEmailChecked: () => {}, contactChecked: true, setContactChecked: () => {}, calendarChecked: true, setCalendarChecked: () => {}, importerData: prepareState.mailImport!.importerData!, handleCancel: () => {}, handleSubmit: () => {}, emailTitle: 'title', hasErrors: false, enabledFeatures: { isEmailsEnabled: true, isContactsEnabled: true, isCalendarsEnabled: true, }, allCheckboxUnselected: false, }; it('Should render all products', () => { mockSelectorImporterData.mockImplementation(() => prepareState.mailImport?.importerData); mockedUseStepPrepare.mockImplementation(() => defaultStepPrepare); mockedUseStepPrepareEmailSummary.mockImplementation(() => emailSummary); easySwitchRender(<StepPrepare />); screen.getByTestId('StepPrepareEmailsSummary:summary'); screen.getByTestId('StepPrepareContactsSummary:summary'); screen.getByTestId('StepPrepareCalendarSummary:summary'); }); it('Should render only email product', () => { const emailState = { ...defaultStepPrepare, products: [ImportType.MAIL] }; mockedUseStepPrepare.mockImplementation(() => emailState); mockedUseStepPrepareEmailSummary.mockImplementation(() => emailSummary); easySwitchRender(<StepPrepare />); screen.getByTestId('StepPrepareEmailsSummary:summary'); expect(screen.queryByTestId('StepPrepareContactsSummary:summary')).toBeNull(); expect(screen.queryByTestId('StepPrepareCalendarSummary:summary')).toBeNull(); }); it('Should render only contact product', () => { const emailState = { ...defaultStepPrepare, products: [ImportType.CONTACTS] }; mockedUseStepPrepare.mockImplementation(() => emailState); mockedUseStepPrepareEmailSummary.mockImplementation(() => emailSummary); easySwitchRender(<StepPrepare />); expect(screen.queryByTestId('StepPrepareEmailsSummary:summary')).toBeNull(); screen.getByTestId('StepPrepareContactsSummary:summary'); expect(screen.queryByTestId('StepPrepareCalendarSummary:summary')).toBeNull(); }); it('Should render only calendar product', () => { const emailState = { ...defaultStepPrepare, products: [ImportType.CALENDAR] }; mockedUseStepPrepare.mockImplementation(() => emailState); mockedUseStepPrepareEmailSummary.mockImplementation(() => emailSummary); easySwitchRender(<StepPrepare />); expect(screen.queryByTestId('StepPrepareEmailsSummary:summary')).toBeNull(); expect(screen.queryByTestId('StepPrepareContactsSummary:summary')).toBeNull(); screen.getByTestId('StepPrepareCalendarSummary:summary'); }); }); describe('Render errors on products', () => { const defaultStepPrepare = { products: [ImportType.CALENDAR, ImportType.CONTACTS, ImportType.MAIL], emailChecked: true, setEmailChecked: () => {}, contactChecked: true, setContactChecked: () => {}, calendarChecked: true, setCalendarChecked: () => {}, importerData: prepareState.mailImport!.importerData!, handleCancel: () => {}, handleSubmit: () => {}, emailTitle: 'title', hasErrors: false, enabledFeatures: { isEmailsEnabled: true, isContactsEnabled: true, isCalendarsEnabled: true, }, allCheckboxUnselected: false, }; it('Should render error box if an error is present', () => { const stepPrepareWithError = { ...defaultStepPrepare, hasErrors: true }; mockSelectorImporterData.mockImplementation(() => prepareState.mailImport?.importerData); mockedUseStepPrepare.mockImplementation(() => stepPrepareWithError); mockedUseStepPrepareEmailSummary.mockImplementation(() => emailSummary); easySwitchRender(<StepPrepare />); screen.getByTestId('StepPrepareErrorBox:container'); }); it('should disable the submit button if all checkboxes are unchecked', () => { const noCheckboxSelected = { ...defaultStepPrepare, emailChecked: false, contactChecked: false, calendarChecked: false, allCheckboxUnselected: true, }; mockSelectorImporterData.mockImplementation(() => prepareState.mailImport?.importerData); mockedUseStepPrepare.mockImplementation(() => noCheckboxSelected); mockedUseStepPrepareEmailSummary.mockImplementation(() => emailSummary); easySwitchRender(<StepPrepare />); const submitButton = screen.getByText('Start import'); expect(submitButton).toBeDisabled(); }); });
4,890
0
petrpan-code/ProtonMail/WebClients/packages/activation/src/components/Modals/OAuth/StepPrepareOAuth
petrpan-code/ProtonMail/WebClients/packages/activation/src/components/Modals/OAuth/StepPrepareOAuth/CustomizeCalendarImportModal/CustomizeCalendarImportModal.test.tsx
import { fireEvent, screen } from '@testing-library/dom'; import useAvailableAddresses from '@proton/activation/src/hooks/useAvailableAddresses'; import { ImporterCalendar } from '@proton/activation/src/logic/draft/oauthDraft/oauthDraft.interface'; import { selectOauthImportStateImporterData } from '@proton/activation/src/logic/draft/oauthDraft/oauthDraft.selector'; import { generateMockAddressArray } from '@proton/activation/src/tests/data/addresses'; import { prepareState } from '@proton/activation/src/tests/data/prepareState'; import { easySwitchRender } from '@proton/activation/src/tests/render'; import { ModalStateProps } from '@proton/components/index'; import { CALENDAR_DISPLAY, CALENDAR_TYPE } from '@proton/shared/lib/calendar/constants'; import { CalendarMember, VisualCalendar } from '@proton/shared/lib/interfaces/calendar'; import CustomizeCalendarImportModal from './CustomizeCalendarImportModal'; import { DerivedCalendarType } from './useCustomizeCalendarImportModal'; const modalProps: ModalStateProps = { key: 'modalProps', open: true, onClose: () => {}, onExit: () => {}, }; const calendarMember: CalendarMember = { ID: 'id', CalendarID: 'CalendarID', AddressID: 'AddressID', Flags: 1, Name: 'Name', Description: 'Description', Email: 'Email', Permissions: 1, Color: 'Color', Display: CALENDAR_DISPLAY.VISIBLE, Priority: 1, }; const visualCalendar: VisualCalendar = { Owner: { Email: '[email protected]' }, Members: [calendarMember], ID: 'id', Type: CALENDAR_TYPE.PERSONAL, Name: 'visualCalendar', Description: 'visualCalendar', Color: 'visualCalendar', Display: CALENDAR_DISPLAY.VISIBLE, Email: '[email protected]', Flags: 1, Permissions: 1, Priority: 1, }; const importerCalendar: ImporterCalendar = { source: 'testing', description: 'testing', id: 'testing', checked: true, }; const derivedValuesNoErrors: DerivedCalendarType = { selectedCalendars: [importerCalendar], calendarsToBeCreatedCount: 1, calendarLimitReached: false, selectedCalendarsCount: 1, disabled: false, calendarsToFixCount: 0, canMerge: true, totalCalendarsCount: 10, calendarsToBeMergedCount: 2, }; jest.mock('@proton/activation/src/logic/draft/oauthDraft/oauthDraft.selector', () => ({ ...jest.requireActual('@proton/activation/src/logic/draft/oauthDraft/oauthDraft.selector'), selectOauthImportStateImporterData: jest.fn(), })); const addresses = generateMockAddressArray(3, true); const mockUseAddressValue = { availableAddresses: addresses, loading: false, defaultAddress: addresses[0], }; jest.mock('@proton/activation/src/hooks/useAvailableAddresses'); const mockUseAvailableAddresses = useAvailableAddresses as jest.MockedFunction<any>; const mockSelectorImporterData = selectOauthImportStateImporterData as any as jest.Mock< ReturnType<typeof selectOauthImportStateImporterData> >; describe('CustomizeCalendarImportModal', () => { it('Should render customize calendar modal', () => { mockUseAvailableAddresses.mockReturnValue(mockUseAddressValue); mockSelectorImporterData.mockImplementation(() => prepareState.mailImport?.importerData); const standardProps = { modalProps, providerCalendarsState: [importerCalendar], derivedValues: derivedValuesNoErrors, activeWritableCalendars: [visualCalendar], handleSubmit: () => {}, handleCalendarToggle: () => {}, handleMappingChange: () => {}, }; easySwitchRender(<CustomizeCalendarImportModal {...standardProps} />); screen.getByTestId('CustomizeCalendarImportModal:description'); }); it('Should render calendar limit reached', () => { mockUseAvailableAddresses.mockReturnValue(mockUseAddressValue); mockSelectorImporterData.mockImplementation(() => prepareState.mailImport?.importerData); const derivedValuesWithErrors = { ...derivedValuesNoErrors, calendarLimitReached: true }; const standardProps = { modalProps, providerCalendarsState: [importerCalendar], derivedValues: derivedValuesWithErrors, activeWritableCalendars: [visualCalendar], handleSubmit: () => {}, handleCalendarToggle: () => {}, handleMappingChange: () => {}, }; easySwitchRender(<CustomizeCalendarImportModal {...standardProps} />); screen.getByTestId('CustomizeCalendarImportModalLimitReached:container'); }); it('Should render different elements if cannot merge', () => { mockUseAvailableAddresses.mockReturnValue(mockUseAddressValue); mockSelectorImporterData.mockImplementation(() => prepareState.mailImport?.importerData); const derivedValuesNoMerge = { ...derivedValuesNoErrors, canMerge: false }; const standardProps = { modalProps, providerCalendarsState: [importerCalendar], derivedValues: derivedValuesNoMerge, activeWritableCalendars: [visualCalendar], handleSubmit: () => {}, handleCalendarToggle: () => {}, handleMappingChange: () => {}, }; easySwitchRender(<CustomizeCalendarImportModal {...standardProps} />); screen.getByTestId('CustomizeCalendarImportModal:description'); }); it('Should click the checkbox of a calendar', () => { mockUseAvailableAddresses.mockReturnValue(mockUseAddressValue); mockSelectorImporterData.mockImplementation(() => prepareState.mailImport?.importerData); const standardProps = { modalProps, providerCalendarsState: [importerCalendar], derivedValues: derivedValuesNoErrors, activeWritableCalendars: [visualCalendar], handleSubmit: () => {}, handleCalendarToggle: () => {}, handleMappingChange: () => {}, }; easySwitchRender(<CustomizeCalendarImportModal {...standardProps} />); const checkboxes = screen.getAllByTestId('CustomizeCalendarImportRow:checkbox'); expect(checkboxes).toHaveLength(standardProps.providerCalendarsState.length); fireEvent.click(checkboxes[0]); }); });
4,897
0
petrpan-code/ProtonMail/WebClients/packages/activation/src/components/Modals/OAuth/StepPrepareOAuth
petrpan-code/ProtonMail/WebClients/packages/activation/src/components/Modals/OAuth/StepPrepareOAuth/hooks/useStepPrepareOAuth.helpers.test.ts
import { MailImportFolder } from '@proton/activation/src/helpers/MailImportFoldersParser/MailImportFoldersParser'; import { ImportType, MailImportDestinationFolder, MailImportGmailCategories, TIME_PERIOD, } from '@proton/activation/src/interface'; import { ImporterCalendar, ImporterData } from '@proton/activation/src/logic/draft/oauthDraft/oauthDraft.interface'; import { generateMockAddress } from '@proton/activation/src/tests/data/addresses'; import { Label } from '@proton/shared/lib/interfaces'; import { Folder } from '@proton/shared/lib/interfaces/Folder'; import { VisualCalendar } from '@proton/shared/lib/interfaces/calendar'; import { generateOwnedPersonalCalendars } from '@proton/testing/lib/builders'; import { getMailCustomLabel, importerHasErrors } from './useStepPrepareOAuth.helpers'; const dummyCalendar: ImporterCalendar = { source: 'source', description: 'description', id: 'id 1', checked: true, }; const dummyFolder: MailImportFolder = { id: 'id', checked: true, color: 'test color', isSystemFolderChild: false, folderChildIDS: [''], protonPath: [ 'Lorem ipsum dolor sit amet, consectetuer adipiscing elit. Aenean commodo ligula eget dolor. Aenean m', ], providerPath: ['providerPath'], separator: '/', size: 0, category: undefined, folderParentID: '', systemFolder: MailImportDestinationFolder.ARCHIVE, }; const dummyShortPathFolder: MailImportFolder = { id: 'id', checked: true, color: 'test color', isSystemFolderChild: false, folderChildIDS: [''], protonPath: ['Lorem'], providerPath: ['providerPath'], separator: '/', size: 0, category: undefined, folderParentID: '', systemFolder: MailImportDestinationFolder.ARCHIVE, }; describe('getMailCustomLabel', () => { it('Should return the appropriate mail label', () => { const labelBigBang = getMailCustomLabel(TIME_PERIOD.BIG_BANG); expect(labelBigBang).toBe('Emails (all messages)'); const labelLastYear = getMailCustomLabel(TIME_PERIOD.LAST_YEAR); expect(labelLastYear).toBe('Emails (last 12 months)'); const label3Month = getMailCustomLabel(TIME_PERIOD.LAST_3_MONTHS); expect(label3Month).toBe('Emails (last 3 months)'); const label1Month = getMailCustomLabel(TIME_PERIOD.LAST_MONTH); expect(label1Month).toBe('Emails (last month)'); const labelDefault = getMailCustomLabel(); expect(labelDefault).toBe('Email'); }); }); describe('importerHasErrors calendar tests', () => { it('Should return an error if number of calendars exceed MAX_CALENDARS_PAID for paid user (max 25)', () => { const dummyCalendarArray = Array(20).fill(dummyCalendar); const products: ImportType[] = [ImportType.CALENDAR]; const importerData: ImporterData = { importedEmail: '[email protected]', importerId: '1', calendars: { calendars: dummyCalendarArray }, }; const labels: Label[] = []; const folders: Folder[] = []; const calendars: VisualCalendar[] = generateOwnedPersonalCalendars(10); const mailChecked = false; const calendarChecked = true; const isFreeUser = false; const errors = importerHasErrors( products, importerData, labels, folders, calendars, mailChecked, calendarChecked, true, isFreeUser ); expect(errors).toBe(true); }); it('Should NOT return an error if number of calendars is below MAX_CALENDARS_PAID for paid user (max 25)', () => { const dummyCalendarArray = Array(20).fill(dummyCalendar); const products: ImportType[] = [ImportType.CALENDAR]; const importerData: ImporterData = { importedEmail: '[email protected]', importerId: '1', calendars: { calendars: dummyCalendarArray }, }; const labels: Label[] = []; const folders: Folder[] = []; const calendars: VisualCalendar[] = generateOwnedPersonalCalendars(2); const mailChecked = false; const calendarChecked = true; const isFreeUser = false; const errors = importerHasErrors( products, importerData, labels, folders, calendars, mailChecked, calendarChecked, true, isFreeUser ); expect(errors).toBe(false); }); it('Should return an error if number of calendars exceed MAX_CALENDARS_FREE for free user (max 3)', () => { const dummyCalendarArray = Array(25).fill(dummyCalendar); const products: ImportType[] = [ImportType.CALENDAR]; const importerData: ImporterData = { importedEmail: '[email protected]', importerId: '1', calendars: { calendars: dummyCalendarArray }, }; const labels: Label[] = []; const folders: Folder[] = []; const calendars: VisualCalendar[] = generateOwnedPersonalCalendars(10); const mailChecked = false; const calendarChecked = true; const isFreeUser = true; const errors = importerHasErrors( products, importerData, labels, folders, calendars, mailChecked, calendarChecked, true, isFreeUser ); expect(errors).toBe(true); }); it('Should NOT return an error if number of calendars is below MAX_CALENDARS_FREE for paid user (max 3)', () => { const dummyCalendarArray = Array(1).fill(dummyCalendar); const products: ImportType[] = [ImportType.CALENDAR]; const importerData: ImporterData = { importedEmail: '[email protected]', importerId: '1', calendars: { calendars: dummyCalendarArray }, }; const labels: Label[] = []; const folders: Folder[] = []; const calendars: VisualCalendar[] = generateOwnedPersonalCalendars(1); const mailChecked = false; const calendarChecked = true; const isFreeUser = true; const errors = importerHasErrors( products, importerData, labels, folders, calendars, mailChecked, calendarChecked, true, isFreeUser ); expect(errors).toBe(false); }); }); describe('importerHasErrors test check and general behavior', () => { it('Should not return an error if number of calendars exceed MAX_CALENDARS_PAID but no calendar product', () => { const dummyCalendarArray = Array(20).fill(dummyCalendar); const products: ImportType[] = [ImportType.CONTACTS]; const importerData: ImporterData = { importedEmail: '[email protected]', importerId: '1', calendars: { calendars: dummyCalendarArray }, }; const labels: Label[] = []; const folders: Folder[] = []; const calendars: VisualCalendar[] = generateOwnedPersonalCalendars(1); const mailChecked = false; const calendarChecked = true; const errors = importerHasErrors( products, importerData, labels, folders, calendars, mailChecked, calendarChecked, true, true ); expect(errors).toBe(false); }); it('Should not return an error if number of calendars exceed MAX_CALENDARS_PAID but calendar not checked', () => { const dummyCalendarArray = Array(20).fill(dummyCalendar); const products: ImportType[] = [ImportType.CALENDAR]; const importerData: ImporterData = { importedEmail: '[email protected]', importerId: '1', calendars: { calendars: dummyCalendarArray }, }; const labels: Label[] = []; const folders: Folder[] = []; const calendars: VisualCalendar[] = generateOwnedPersonalCalendars(1); const mailChecked = false; const calendarChecked = false; const errors = importerHasErrors( products, importerData, labels, folders, calendars, mailChecked, calendarChecked, true, false ); expect(errors).toBe(false); }); it('Should return no errors', () => { const products: ImportType[] = [ImportType.CONTACTS]; const importerData: ImporterData = { importedEmail: '[email protected]', importerId: '1' }; const labels: Label[] = []; const folders: Folder[] = []; const calendars: VisualCalendar[] = []; const mailChecked = false; const calendarChecked = false; const errors = importerHasErrors( products, importerData, labels, folders, calendars, mailChecked, calendarChecked, true, true ); expect(errors).toBe(false); }); it('Should return an error if email mapping has errors', () => { const products: ImportType[] = [ImportType.MAIL]; const importerData: ImporterData = { importedEmail: '[email protected]', importerId: '1', emails: { fields: { importAddress: generateMockAddress(0, true), mapping: [dummyFolder, dummyFolder], importPeriod: TIME_PERIOD.BIG_BANG, importLabel: { Color: 'red', Name: 'name', Type: 1 }, importCategoriesDestination: MailImportDestinationFolder.ALL_DRAFTS, }, }, }; const labels: Label[] = []; const folders: Folder[] = [ { ID: 'id', Name: 'path', Color: 'red', Path: 'path', Expanded: 1, Type: 1, Order: 1, ParentID: '', Notify: 1, }, ]; const calendars: VisualCalendar[] = []; const mailChecked = true; const calendarChecked = false; const errors = importerHasErrors( products, importerData, labels, folders, calendars, mailChecked, calendarChecked, true, false ); expect(errors).toBe(true); }); it('Should not return an error if email mapping has errors but is not in products', () => { const products: ImportType[] = [ImportType.CONTACTS]; const importerData: ImporterData = { importedEmail: '[email protected]', importerId: '1', emails: { fields: { importAddress: generateMockAddress(0, true), mapping: [dummyFolder, dummyFolder], importPeriod: TIME_PERIOD.BIG_BANG, importLabel: { Color: 'red', Name: 'name', Type: 1 }, importCategoriesDestination: MailImportDestinationFolder.ALL_DRAFTS, }, }, }; const labels: Label[] = []; const folders: Folder[] = [ { ID: 'id', Name: 'path', Color: 'red', Path: 'path', Expanded: 1, Type: 1, Order: 1, ParentID: '', Notify: 1, }, ]; const calendars: VisualCalendar[] = []; const mailChecked = false; const calendarChecked = false; const errors = importerHasErrors( products, importerData, labels, folders, calendars, mailChecked, calendarChecked, true, false ); expect(errors).toBe(false); }); it('Should not return an error if email mapping has errors but is unchecked', () => { const products: ImportType[] = [ImportType.MAIL]; const importerData: ImporterData = { importedEmail: '[email protected]', importerId: '1', emails: { fields: { importAddress: generateMockAddress(0, true), mapping: [dummyFolder, dummyFolder], importPeriod: TIME_PERIOD.BIG_BANG, importLabel: { Color: 'red', Name: 'name', Type: 1 }, importCategoriesDestination: MailImportDestinationFolder.ALL_DRAFTS, }, }, }; const labels: Label[] = []; const folders: Folder[] = [ { ID: 'id', Name: 'path', Color: 'red', Path: 'path', Expanded: 1, Type: 1, Order: 1, ParentID: '', Notify: 1, }, ]; const calendars: VisualCalendar[] = []; const mailChecked = false; const calendarChecked = false; const errors = importerHasErrors( products, importerData, labels, folders, calendars, mailChecked, calendarChecked, true, false ); expect(errors).toBe(false); }); it('Should not return an error if email mapping has errors but no mapping', () => { const products: ImportType[] = [ImportType.MAIL]; const importerData: ImporterData = { importedEmail: '[email protected]', importerId: '1', }; const labels: Label[] = []; const folders: Folder[] = [ { ID: 'id', Name: 'path', Color: 'red', Path: 'path', Expanded: 1, Type: 1, Order: 1, ParentID: '', Notify: 1, }, ]; const calendars: VisualCalendar[] = []; const mailChecked = false; const calendarChecked = false; const errors = importerHasErrors( products, importerData, labels, folders, calendars, mailChecked, calendarChecked, true, false ); expect(errors).toBe(false); }); }); describe('importerHasErrors test for Gmail imports', () => { const socialFolder = { id: 'id', checked: true, color: 'test color', isSystemFolderChild: false, folderChildIDS: [''], protonPath: ['Social'], providerPath: ['Social'], separator: '/', size: 0, category: MailImportGmailCategories.SOCIAL, folderParentID: '', systemFolder: MailImportDestinationFolder.ARCHIVE, }; it('Should not return an error when Social folder and label exists when Gmail import', () => { const products: ImportType[] = [ImportType.MAIL]; const importerData: ImporterData = { importedEmail: '[email protected]', importerId: '1', emails: { fields: { importAddress: generateMockAddress(0, true), mapping: [dummyShortPathFolder, dummyShortPathFolder, socialFolder], importPeriod: TIME_PERIOD.BIG_BANG, importLabel: { Color: 'red', Name: 'name', Type: 1 }, importCategoriesDestination: MailImportDestinationFolder.ALL_DRAFTS, }, }, }; const labels: Label[] = [ { ID: 'id', Name: 'Social', Color: 'color', Type: 1, Order: 1, Path: 'Social', }, ]; const folders: Folder[] = [ { ID: 'id', Name: 'Social', Color: 'red', Path: '/Social', Expanded: 1, Type: 1, Order: 1, ParentID: '', Notify: 1, }, ]; const calendars: VisualCalendar[] = []; const mailChecked = true; const calendarChecked = false; const errors = importerHasErrors( products, importerData, labels, folders, calendars, mailChecked, calendarChecked, true, false ); expect(errors).toBe(false); }); it('Should not return an error when Social folder and label exists when non Gmail import', () => { const products: ImportType[] = [ImportType.MAIL]; const importerData: ImporterData = { importedEmail: '[email protected]', importerId: '1', emails: { fields: { importAddress: generateMockAddress(0, true), mapping: [dummyShortPathFolder, dummyShortPathFolder, socialFolder], importPeriod: TIME_PERIOD.BIG_BANG, importLabel: { Color: 'red', Name: 'name', Type: 1 }, importCategoriesDestination: MailImportDestinationFolder.ALL_DRAFTS, }, }, }; const labels: Label[] = [ { ID: 'id', Name: 'Social', Color: 'color', Type: 1, Order: 1, Path: 'Social', }, ]; const folders: Folder[] = [ { ID: 'id', Name: 'Social', Color: 'red', Path: '/Social', Expanded: 1, Type: 1, Order: 1, ParentID: '', Notify: 1, }, ]; const calendars: VisualCalendar[] = []; const mailChecked = true; const calendarChecked = false; const errors = importerHasErrors( products, importerData, labels, folders, calendars, mailChecked, calendarChecked, false, false ); expect(errors).toBe(true); }); });
4,903
0
petrpan-code/ProtonMail/WebClients/packages/activation/src/components/Modals/OAuth
petrpan-code/ProtonMail/WebClients/packages/activation/src/components/Modals/OAuth/StepProducts/StepProductsRowItem.test.tsx
import { fireEvent, screen } from '@testing-library/dom'; import { easySwitchRender } from '@proton/activation/src/tests/render'; import StepProductsRowItem from './StepProductsRowItem'; describe('StepProductsRowItem', () => { it('Should render the default component when no errors', () => { easySwitchRender(<StepProductsRowItem id="mail" label="label" value={true} setValue={jest.fn} />); screen.getByTestId('StepProductsRowItem:label'); }); it('Should render the error component when has errors', () => { easySwitchRender( <StepProductsRowItem id="mail" label="label" value={true} setValue={jest.fn} error={'There is an error'} /> ); screen.getByText('There is an error'); }); it('Should render a warning when the component is disabled', () => { easySwitchRender( <StepProductsRowItem id="mail" label="label" value={true} setValue={jest.fn} disabled={true} /> ); screen.getByText('(Temporarily unavailable. Please check back later.)'); }); it('Should update the value when the checkbox is clicked', () => { const setValue = jest.fn(); easySwitchRender(<StepProductsRowItem id="mail" label="label" value={true} setValue={setValue} />); const label = screen.getByTestId('StepProductsRowItem:label'); fireEvent.click(label); expect(setValue).toBeCalledTimes(1); }); });
4,905
0
petrpan-code/ProtonMail/WebClients/packages/activation/src/components/Modals/OAuth
petrpan-code/ProtonMail/WebClients/packages/activation/src/components/Modals/OAuth/StepProducts/useStepProducts.helpers.test.ts
import { G_OAUTH_SCOPE_CALENDAR, G_OAUTH_SCOPE_CONTACTS, G_OAUTH_SCOPE_DEFAULT, G_OAUTH_SCOPE_MAIL_READONLY, O_OAUTH_SCOPE_CALENDAR, O_OAUTH_SCOPE_CONTACTS, O_OAUTH_SCOPE_DEFAULT, O_OAUTH_SCOPE_MAIL, } from '@proton/activation/src/constants'; import { ImportProvider, ImportType } from '@proton/activation/src/interface'; import { getScopeFromProvider } from './useStepProducts.helpers'; describe('useStepProducts tests', () => { it('Should return empty array', () => { const scope = getScopeFromProvider(ImportProvider.DEFAULT, [ ImportType.CALENDAR, ImportType.CONTACTS, ImportType.MAIL, ]); expect(scope).toStrictEqual([]); }); it('Should test all possible outlook scopes', () => { const scopeEmail = getScopeFromProvider(ImportProvider.OUTLOOK, [ImportType.MAIL]); expect(scopeEmail).toStrictEqual([...O_OAUTH_SCOPE_DEFAULT, ...O_OAUTH_SCOPE_MAIL]); const scopeContact = getScopeFromProvider(ImportProvider.OUTLOOK, [ImportType.CONTACTS]); expect(scopeContact).toStrictEqual([...O_OAUTH_SCOPE_DEFAULT, ...O_OAUTH_SCOPE_CONTACTS]); const scopeCalendar = getScopeFromProvider(ImportProvider.OUTLOOK, [ImportType.CALENDAR]); expect(scopeCalendar).toStrictEqual([...O_OAUTH_SCOPE_DEFAULT, ...O_OAUTH_SCOPE_CALENDAR]); }); it('Should test all possible gmail scopes', () => { const scopeEmail = getScopeFromProvider(ImportProvider.GOOGLE, [ImportType.MAIL]); expect(scopeEmail).toStrictEqual([...G_OAUTH_SCOPE_DEFAULT, ...G_OAUTH_SCOPE_MAIL_READONLY]); const scopeContact = getScopeFromProvider(ImportProvider.GOOGLE, [ImportType.CONTACTS]); expect(scopeContact).toStrictEqual([...G_OAUTH_SCOPE_DEFAULT, ...G_OAUTH_SCOPE_CONTACTS]); const scopeCalendar = getScopeFromProvider(ImportProvider.GOOGLE, [ImportType.CALENDAR]); expect(scopeCalendar).toStrictEqual([...G_OAUTH_SCOPE_DEFAULT, ...G_OAUTH_SCOPE_CALENDAR]); }); });
4,908
0
petrpan-code/ProtonMail/WebClients/packages/activation/src/components/Modals/OAuth
petrpan-code/ProtonMail/WebClients/packages/activation/src/components/Modals/OAuth/StepSuccess/StepSuccess.test.tsx
import { useLocation } from 'react-router-dom'; import { fireEvent, screen } from '@testing-library/dom'; import { easySwitchRender } from '@proton/activation/src/tests/render'; import StepSuccess from './StepSuccess'; jest.mock('react-router-dom', () => ({ ...jest.requireActual('react-router-dom'), useLocation: jest.fn() })); const mockedUseLocation = useLocation as jest.Mock; describe('StepSuccess tests', () => { it('Should render simple success step, no settings button while in settings', async () => { mockedUseLocation.mockImplementation(() => { return { pathname: '/easy-switch' }; }); easySwitchRender(<StepSuccess />); screen.getByTestId('StepSuccess:Modal'); expect(screen.queryByTestId('StepSuccess:SettingsLink')).toBeNull(); const closeButton = screen.getByTestId('StepSuccess:CloseButton'); fireEvent.click(closeButton); }); it('Should renter the settings link button if not in settings', () => { mockedUseLocation.mockImplementation(() => { return { pathname: '/mail' }; }); easySwitchRender(<StepSuccess />); screen.getByTestId('StepSuccess:Modal'); screen.getByTestId('StepSuccess:SettingsLink'); screen.getByTestId('StepSuccess:RedirectFooter'); const submitFooter = screen.getByTestId('StepSuccess:RedirectFooterSubmit'); fireEvent.click(submitFooter); }); });
4,911
0
petrpan-code/ProtonMail/WebClients/packages/activation/src/components
petrpan-code/ProtonMail/WebClients/packages/activation/src/components/OAuthImportButton/OAuthImportButton.test.tsx
import { fireEvent, screen } from '@testing-library/dom'; import { EASY_SWITCH_SOURCE, ImportProvider, ImportType } from '@proton/activation/src/interface'; import { easySwitchRender } from '@proton/activation/src/tests/render'; import OAuthImportButton from './OAuthImportButton'; describe('Test correct rendering of loading importer', () => { it('Should render importer', () => { easySwitchRender( <OAuthImportButton source={EASY_SWITCH_SOURCE.EASY_SWITCH_SETTINGS} defaultCheckedTypes={[ImportType.MAIL]} displayOn="GoogleCalendar" provider={ImportProvider.GOOGLE} /> ); const button = screen.getByTestId('OAuthImportButton:button:google'); fireEvent.click(button); }); });
4,914
0
petrpan-code/ProtonMail/WebClients/packages/activation/src/components
petrpan-code/ProtonMail/WebClients/packages/activation/src/components/ReportsTable/ReportsTable.test.tsx
import { fireEvent, screen, waitFor } from '@testing-library/dom'; import { rest } from 'msw'; import { setupServer } from 'msw/node'; import { easySwitchRender } from '@proton/activation/src/tests/render'; import ReportsTable from './ReportsTable'; const server = setupServer(); beforeAll(() => { server.listen(); }); afterEach(() => server.resetHandlers()); afterAll(() => { server.close(); }); describe('Reports table testing', () => { it('Should display placeholder text when no imports available', async () => { server.use( rest.get('importer/v1/reports', (req, res, ctx) => res(ctx.set('date', '01/01/2022'), ctx.json([]))), rest.get('importer/v1/importers', (req, res, ctx) => res(ctx.set('date', '01/01/2022'), ctx.json([]))), rest.get('importer/v1/sync', (req, res, ctx) => res(ctx.set('date', '01/01/2022'), ctx.json([]))) ); easySwitchRender(<ReportsTable />); screen.getByTestId('reportsTable:noImports'); }); it('Should display the list of finished importer', async () => { const finishedReport = { Code: 1000, Reports: [ { ID: 'testingImporter', CreateTime: 1671548668, EndTime: 1671548773, Provider: 1, Account: '[email protected]', State: 1, Summary: { Calendar: { State: 2, NumEvents: 0, TotalSize: 0, RollbackState: 0, }, Contacts: { State: 2, NumContacts: 100, NumGroups: 1, TotalSize: 55003, RollbackState: 0, }, Mail: { State: 2, NumMessages: 88, TotalSize: 1393911, RollbackState: 1, CanDeleteSource: 0, }, }, TotalSize: 1448914, }, ], }; server.use( rest.get('importer/v1/reports', (req, res, ctx) => res(ctx.set('date', '01/01/2022'), ctx.json(finishedReport)) ) ); easySwitchRender(<ReportsTable />); const reportRows = await waitFor(() => screen.findAllByTestId('reportsTable:reportRow')); expect(reportRows).toHaveLength(3); const deleteReport = screen.getAllByTestId('ReportsTable:deleteReport'); fireEvent.click(deleteReport[0]); await waitFor(() => screen.getByTestId('ReportsTable:deleteModal')); }); it('Should allow reconnection when importer has failed', async () => { const importerData = { ID: 'testingImporter', Account: '[email protected]', Product: ['Mail'], Provider: 0, TokenID: null, ImapHost: 'imap.proton.ch', ImapPort: 993, Email: '[email protected]', Sasl: 'PLAIN', AllowSelfSigned: 0, MailboxSize: { Archive: 0, Draft: 2191, Inbox: 315729, Sent: 5862, "Spéciæl charaters-&'(yeah": 0, "Spéciæl charaters-&'(yeah/sub spécïªl charaters": 7549, 'Test folder': 134826, 'Test folder/a test folder with big name': 10100, 'Test folder/a test folder with big name/a sub sub folder': 13120, 'another test foldr with a really long name hey hye hey': 226333, }, Active: { Mail: { CreateTime: 1671630060, State: 4, ErrorCode: 1, }, }, }; const apiCallSpy = jest.fn(); const importersSpy = jest.fn(); const singleImporterSpy = jest.fn(); server.use( rest.get('/core/v4/features', (req, res, ctx) => { apiCallSpy(); return res(ctx.set('date', '01/01/2022'), ctx.json({})); }), rest.get('/importer/v1/mail/importers/authinfo', (req, res, ctx) => { apiCallSpy(); return res(ctx.set('date', '01/01/2022'), ctx.json({})); }), rest.get('/core/v4/system/config', (req, res, ctx) => { apiCallSpy(); return res(ctx.set('date', '01/01/2022'), ctx.json({})); }), rest.get('importer/v1/importers', (req, res, ctx) => { importersSpy(); return res( ctx.set('date', '01/01/2022'), ctx.json({ Code: 1000, Importers: [importerData], }) ); }), rest.get(`importer/v1/importers/${importerData.ID}`, (req, res, ctx) => { singleImporterSpy(); return res( ctx.set('date', '01/01/2022'), ctx.json({ Code: 1000, Importer: importerData, }) ); }) ); easySwitchRender(<ReportsTable />); await waitFor(() => expect(importersSpy).toHaveBeenCalledTimes(1)); await waitFor(() => expect(apiCallSpy).toHaveBeenCalled()); const reconnectButton = screen.getByTestId('ReportsTable:reconnectImporter'); fireEvent.click(reconnectButton); await waitFor(() => expect(singleImporterSpy).toHaveBeenCalledTimes(1)); const emailInput = screen.getByTestId('StepForm:emailInput'); const passwordInput = screen.getByTestId('StepForm:passwordInput'); const serverInput = screen.getByTestId('StepForm:serverInput'); const portInput = screen.getByTestId('StepForm:portInput'); const submitButton = screen.getByTestId('StepForm:submitButton'); expect(emailInput).toHaveValue(importerData.Account); expect(serverInput).toHaveValue(importerData.ImapHost); expect(portInput).toHaveValue('993'); expect(emailInput).toBeDisabled(); expect(submitButton).toBeDisabled(); fireEvent.change(passwordInput, { target: { value: 'app password' } }); await waitFor(() => expect(submitButton).toBeEnabled()); }); it('Should display the list of ongoing forwarding', async () => { const ongoingForward = { Code: 1000, Syncs: [ { ID: 'forward-1', ImporterID: 'forwardImporter-1', Account: '[email protected]', Product: 'Mail', State: 1, CreateTime: 1677771164, LastRenewTime: 1677771164, LastImportTime: 0, }, ], }; const apiCallSpy = jest.fn(); const importersSpy = jest.fn(); server.use( rest.get('/core/v4/features', (req, res, ctx) => { apiCallSpy(); return res(ctx.set('date', '01/01/2022'), ctx.json({})); }), rest.get('/importer/v1/mail/importers/authinfo', (req, res, ctx) => { apiCallSpy(); return res(ctx.set('date', '01/01/2022'), ctx.json({})); }), rest.get('/core/v4/system/config', (req, res, ctx) => { apiCallSpy(); return res(ctx.set('date', '01/01/2022'), ctx.json({})); }), rest.get('importer/v1/sync', (req, res, ctx) => { importersSpy(); return res(ctx.set('date', '01/01/2022'), ctx.json(ongoingForward)); }) ); easySwitchRender(<ReportsTable />); await waitFor(() => expect(apiCallSpy).toHaveBeenCalled()); await waitFor(() => expect(importersSpy).toHaveBeenCalledTimes(1)); const reportRows = screen.getAllByTestId('reportsTable:syncRow'); expect(reportRows).toHaveLength(1); const deleteReport = screen.getAllByTestId('ReportsTable:deleteForward'); fireEvent.click(deleteReport[0]); await waitFor(() => screen.getByTestId('ReportsTable:deleteModal')); }); });
4,916
0
petrpan-code/ProtonMail/WebClients/packages/activation/src/components
petrpan-code/ProtonMail/WebClients/packages/activation/src/components/ReportsTable/ReportsTableCell.helpers.test.ts
import { ImportType } from '@proton/activation/src/interface'; import { getImportIconNameByProduct, getImportProductName } from './ReportsTableCell.helpers'; describe('ReportsTableCell.helpers', () => { it('getImportProductName - test all types', () => { const mail = getImportProductName(ImportType.MAIL); const calendar = getImportProductName(ImportType.CALENDAR); const contact = getImportProductName(ImportType.CONTACTS); expect(mail).toStrictEqual('Mail'); expect(calendar).toStrictEqual('Calendar'); expect(contact).toStrictEqual('Contacts'); }); it('getImportIconNameByProduct - test all types', () => { const mail = getImportIconNameByProduct(ImportType.MAIL); const calendar = getImportIconNameByProduct(ImportType.CALENDAR); const contact = getImportIconNameByProduct(ImportType.CONTACTS); expect(mail).toStrictEqual('envelope'); expect(calendar).toStrictEqual('calendar-grid'); expect(contact).toStrictEqual('users'); }); });
4,922
0
petrpan-code/ProtonMail/WebClients/packages/activation/src/components/ReportsTable
petrpan-code/ProtonMail/WebClients/packages/activation/src/components/ReportsTable/Importers/ImporterRowStatus.test.tsx
import { screen } from '@testing-library/dom'; import { ApiImporterError, ApiImporterState } from '@proton/activation/src/api/api.interface'; import { easySwitchRender } from '@proton/activation/src/tests/render'; import ImporterRowStatus from './ImporterRowStatus'; describe('ReportRowStatus', () => { it('Should display PAUSED status%', () => { easySwitchRender(<ImporterRowStatus state={ApiImporterState.PAUSED} errorCode={undefined} />); screen.getByText('Paused'); }); it('Should display PAUSED status', () => { easySwitchRender(<ImporterRowStatus state={ApiImporterState.PAUSED} errorCode={undefined} />); screen.getByText('Paused'); }); it('Should display PAUSED status ERROR_CODE_IMAP_CONNECTION', () => { easySwitchRender( <ImporterRowStatus state={ApiImporterState.PAUSED} errorCode={ApiImporterError.ERROR_CODE_IMAP_CONNECTION} /> ); screen.getByTestId('ImporterRowStatus:IMAP_Error'); }); it('Should display PAUSED status ERROR_CODE_QUOTA_LIMIT', () => { easySwitchRender( <ImporterRowStatus state={ApiImporterState.PAUSED} errorCode={ApiImporterError.ERROR_CODE_QUOTA_LIMIT} /> ); screen.getByTestId('ImporterRowStatus:quota_Error'); }); it('Should display QUEUED status', () => { easySwitchRender(<ImporterRowStatus state={ApiImporterState.QUEUED} errorCode={undefined} />); screen.getByText('Started'); }); it('Should display CANCELED status', () => { easySwitchRender(<ImporterRowStatus state={ApiImporterState.CANCELED} errorCode={undefined} />); screen.getByText('Canceling'); }); it('Should display DELAYED status', () => { easySwitchRender(<ImporterRowStatus state={ApiImporterState.DELAYED} errorCode={undefined} />); screen.getByText('Delayed'); }); });
4,926
0
petrpan-code/ProtonMail/WebClients/packages/activation/src/components/ReportsTable
petrpan-code/ProtonMail/WebClients/packages/activation/src/components/ReportsTable/Reports/ReportRowStatus.test.tsx
import { screen } from '@testing-library/dom'; import { ApiImporterState, ApiReportRollbackState } from '@proton/activation/src/api/api.interface'; import { easySwitchRender } from '@proton/activation/src/tests/render'; import ReportRowStatus from './ReportRowStatus'; describe('ReportRowStatus', () => { it('Should display paused status', () => { easySwitchRender(<ReportRowStatus status={ApiImporterState.PAUSED} rollbackState={undefined} />); screen.getByText('Paused'); }); it('Should display canceled status', () => { easySwitchRender(<ReportRowStatus status={ApiImporterState.CANCELED} rollbackState={undefined} />); screen.getByText('Canceled'); }); it('Should display Completed status', () => { easySwitchRender(<ReportRowStatus status={ApiImporterState.DONE} rollbackState={undefined} />); screen.getByText('Completed'); }); it('Should display FAILED status', () => { easySwitchRender(<ReportRowStatus status={ApiImporterState.FAILED} rollbackState={undefined} />); screen.getByText('Failed'); }); it('Should display ROLLED_BACK status', () => { easySwitchRender( <ReportRowStatus status={ApiImporterState.FAILED} rollbackState={ApiReportRollbackState.ROLLED_BACK} /> ); screen.getByText('Undo finished'); }); it('Should display ROLLING_BACK status', () => { easySwitchRender( <ReportRowStatus status={ApiImporterState.FAILED} rollbackState={ApiReportRollbackState.ROLLING_BACK} /> ); screen.getByText('Undo in progress'); }); });
4,930
0
petrpan-code/ProtonMail/WebClients/packages/activation/src/components/ReportsTable
petrpan-code/ProtonMail/WebClients/packages/activation/src/components/ReportsTable/Sync/SyncRowStatus.test.tsx
import { screen } from '@testing-library/dom'; import { ApiSyncState } from '@proton/activation/src/api/api.interface'; import { easySwitchRender } from '@proton/activation/src/tests/render'; import SyncRowStatus from './SyncRowStatus'; describe('SyncRowStatus', () => { it('Should display active when status is ACTIVE', () => { easySwitchRender(<SyncRowStatus state={ApiSyncState.ACTIVE} />); screen.getByText('Active'); }); it('Should display paused when status is EXPIRED', () => { easySwitchRender(<SyncRowStatus state={ApiSyncState.EXPIRED} />); screen.getByText('Paused'); }); it('Should display paused when status is OFFLINE', () => { easySwitchRender(<SyncRowStatus state={ApiSyncState.OFFLINE} />); screen.getByText('Paused'); }); });
4,932
0
petrpan-code/ProtonMail/WebClients/packages/activation/src/components
petrpan-code/ProtonMail/WebClients/packages/activation/src/components/SettingsArea/GmailForwarding.test.tsx
import { screen } from '@testing-library/dom'; import { useFlag } from '@proton/components/containers/unleash'; import { useUser } from '@proton/components/hooks/useUser'; import { easySwitchRender } from '../../tests/render'; import GmailForwarding from './GmailForwarding'; jest.mock('@proton/components/hooks/useUser'); const mockUseUser = useUser as jest.MockedFunction<any>; jest.mock('@proton/components/containers/unleash'); const mockUseFlag = useFlag as unknown as jest.MockedFunction<any>; describe('GmailForwarding', () => { it('Should be enabled if user is not delinquent', () => { mockUseFlag.mockReturnValue(false); mockUseUser.mockReturnValue([{ hasNonDelinquentScope: true }, false]); easySwitchRender(<GmailForwarding />); const gmailForward = screen.getByTestId('ProviderCard:googleCardForward').firstChild; expect(gmailForward).toBeEnabled(); }); it('Should be disabled if user is delinquent', () => { mockUseFlag.mockReturnValue(false); mockUseUser.mockReturnValue([{ hasNonDelinquentScope: false }, false]); easySwitchRender(<GmailForwarding />); const gmailForward = screen.getByTestId('ProviderCard:googleCardForward'); expect(gmailForward).toBeDisabled(); }); it('Should be disabled if loading user is true', () => { mockUseFlag.mockReturnValue(false); mockUseUser.mockReturnValue([{ hasNonDelinquentScope: true }, true]); easySwitchRender(<GmailForwarding />); const gmailForward = screen.getByTestId('ProviderCard:googleCardForward'); expect(gmailForward).toBeDisabled(); }); it('Should be disabled if maintenance mode is enabled', () => { mockUseFlag.mockReturnValue(true); mockUseUser.mockReturnValue([{ hasNonDelinquentScope: true }, false]); easySwitchRender(<GmailForwarding />); const gmailForward = screen.getByTestId('ProviderCard:googleCardForward'); expect(gmailForward).toBeDisabled(); }); });
4,934
0
petrpan-code/ProtonMail/WebClients/packages/activation/src/components
petrpan-code/ProtonMail/WebClients/packages/activation/src/components/SettingsArea/SettingsArea.test.tsx
import { screen } from '@testing-library/dom'; import useFeature from '@proton/components/hooks/useFeature'; import { easySwitchRender } from '../../tests/render'; import SettingsArea from './SettingsArea'; const settingsAreaConfig = { text: 'Import via Easy Switch', to: '/easy-switch', icon: 'arrow-down-to-square', available: true, description: 'Complete the transition to privacy with our secure importing and forwarding tools.', subsections: [ { text: 'Set up forwarding', id: 'start-forward', }, { text: 'Import messages', id: 'start-import', }, { text: 'History', id: 'import-list', }, ], }; jest.mock('@proton/components/hooks/useFeature'); const mockUseFeature = useFeature as jest.MockedFunction<any>; describe('SettingsArea', () => { it('Should render a loader while loading feature flag', async () => { mockUseFeature.mockReturnValue({ feature: { Value: { GoogleMailSync: true } }, loading: true }); easySwitchRender(<SettingsArea config={settingsAreaConfig} />); const forwardSection = screen.queryByTestId('SettingsArea:forwardSection'); expect(forwardSection).toBeNull(); }); it('Should render the forward section if feature is enabled', async () => { mockUseFeature.mockReturnValue({ feature: { Value: { GoogleMailSync: true } }, loading: false }); easySwitchRender(<SettingsArea config={settingsAreaConfig} />); const googleInScreen = screen.getAllByText('Google'); const gmailInScreen = screen.getByTestId('ProviderCard:googleCardForward'); screen.getByTestId('SettingsArea:forwardSection'); expect(googleInScreen).toHaveLength(1); expect(gmailInScreen).toBeVisible(); }); });
4,938
0
petrpan-code/ProtonMail/WebClients/packages/activation/src/components/SettingsArea
petrpan-code/ProtonMail/WebClients/packages/activation/src/components/SettingsArea/ProviderCards/ProviderCards.test.tsx
import { fireEvent, screen, waitFor } from '@testing-library/dom'; import { rest } from 'msw'; import { setupServer } from 'msw/node'; import { easySwitchRender } from '@proton/activation/src/tests/render'; import { useUser } from '@proton/components/index'; import ProviderCards from './ProviderCards'; const defaultUseUser = [ { isAdmin: true, isFree: true, isMember: true, isPaid: true, isPrivate: true, isSubUser: true, isDelinquent: true, hasNonDelinquentScope: true, hasPaidMail: true, hasPaidVpn: true, canPay: true, }, false, ]; jest.mock('@proton/components/hooks/useUser'); const mockUseUser = useUser as jest.MockedFunction<any>; jest.mock('@proton/components/hooks/useFeature', () => () => { return { feature: { Code: 'EasySwitch', Type: 'mixed', Global: true, DefaultValue: { GoogleMail: true, GoogleCalendar: true, GoogleContacts: true, GoogleDrive: false, OutlookMail: true, OutlookCalendar: true, OutlookContacts: true, OtherMail: true, OtherCalendar: true, OtherContacts: true, OtherDrive: false, }, Value: { GoogleMail: true, GoogleCalendar: true, GoogleContacts: true, GoogleDrive: false, OutlookMail: true, OutlookCalendar: true, OutlookContacts: true, OtherMail: true, OtherCalendar: true, OtherContacts: true, OtherDrive: false, }, Writable: false, }, }; }); jest.mock('@proton/components/hooks/useCalendars', () => () => [ [ { ID: 'calendarId', Name: '[email protected]', Description: '', Type: 0, Owner: { Email: '[email protected]', }, Flags: 1, Members: [ { ID: 'memberId', Permissions: 127, Email: '[email protected]', AddressID: 'addressID', CalendarID: 'calendarId', Name: '[email protected]', Description: '', Color: '#273EB2', Display: 1, Flags: 1, }, ], Color: '#273EB2', Display: 1, Email: '[email protected]', Permissions: 127, }, ], false, ]); const server = setupServer(); beforeAll(() => { server.listen(); server.use( rest.get('/core/v4/features', (req, res, ctx) => { return res(ctx.set('date', '01/01/2022'), ctx.json({})); }), rest.get('/importer/v1/mail/importers/authinfo', (req, res, ctx) => { return res(ctx.set('date', '01/01/2022'), ctx.json({})); }), rest.get('/core/v4/system/config', (req, res, ctx) => { return res(ctx.set('date', '01/01/2022'), ctx.json({})); }), rest.get('/calendar/v1', (req, res, ctx) => { return res(ctx.set('date', '01/01/2022'), ctx.json({})); }) ); }); afterEach(() => server.resetHandlers()); afterAll(() => { server.close(); }); describe('Provider cards process testing', () => { it('Should display the four cards on the page without user data', async () => { mockUseUser.mockReturnValue(defaultUseUser); easySwitchRender(<ProviderCards />); const google = screen.getByTestId('ProviderCard:googleCard'); const yahoo = screen.getByTestId('ProviderCard:yahooCard'); const outlook = screen.getByTestId('ProviderCard:outlookCard'); const imap = screen.getByTestId('ProviderCard:imapCard'); expect(google).toBeEnabled(); expect(yahoo).toBeEnabled(); expect(outlook).toBeEnabled(); expect(imap).toBeEnabled(); // Open imap modal fireEvent.click(imap); await waitFor(() => screen.getByTestId('MailModal:ProductModal')); let productButtons = screen.getAllByTestId('MailModal:ProductButton'); expect(productButtons).toHaveLength(3); // Close imap modal let closeButton = screen.getByTestId('modal:close'); fireEvent.click(closeButton); await waitFor(() => screen.queryAllByTestId('MailModal:ProductModal')); productButtons = screen.queryAllByTestId('MailModal:ProductButton'); expect(productButtons).toStrictEqual([]); // Open yahoo modal fireEvent.click(yahoo); await waitFor(() => screen.getByTestId('MailModal:ProductModal')); productButtons = screen.getAllByTestId('MailModal:ProductButton'); expect(productButtons).toHaveLength(3); closeButton = screen.getByTestId('modal:close'); // Close yahoo modal closeButton = screen.getByTestId('modal:close'); fireEvent.click(closeButton); await waitFor(() => screen.queryAllByTestId('MailModal:ProductModal')); productButtons = screen.queryAllByTestId('MailModal:ProductButton'); expect(productButtons).toStrictEqual([]); }); it('Should trigger yahoo auth error', async () => { mockUseUser.mockReturnValue(defaultUseUser); server.use( rest.get('/core/v4/features', (req, res, ctx) => { return res(ctx.set('date', '01/01/2022'), ctx.json({})); }), rest.get('/importer/v1/mail/importers/authinfo', (req, res, ctx) => { return res(ctx.set('date', '01/01/2022'), ctx.json({})); }), rest.get('/core/v4/system/config', (req, res, ctx) => { return res(ctx.set('date', '01/01/2022'), ctx.json({})); }), rest.get('/calendar/v1', (req, res, ctx) => { return res(ctx.set('date', '01/01/2022'), ctx.json({})); }), rest.get('/settings/calendar', (req, res, ctx) => { return res(ctx.set('date', '01/01/2022'), ctx.json({})); }), rest.post('/importer/v1/importers', (req, res, ctx) => { return res( ctx.set('date', '01/01/2022'), ctx.status(422), ctx.json({ Code: 2901, Error: 'Invalid credentials', Details: { ProviderError: 'AUTHENTICATE command failed: NO [AUTHENTICATIONFAILED] AUTHENTICATE Invalid credentials\r\n', }, }) ); }) ); easySwitchRender(<ProviderCards />); const yahoo = screen.getByTestId('ProviderCard:yahooCard'); // Open imap product modal and click calendar fireEvent.click(yahoo); await waitFor(() => screen.getByTestId('MailModal:ProductModal')); const productButtons = screen.getAllByTestId('MailModal:ProductButton'); expect(productButtons).toHaveLength(3); fireEvent.click(productButtons[0]); // SKip instructions and expect to see calendar modal fireEvent.click(screen.getByTestId('Instruction:continue')); const emailInput = screen.getByTestId('StepForm:emailInput'); const passwordInput = screen.getByTestId('StepForm:passwordInput'); fireEvent.change(emailInput, { target: { value: '[email protected]' } }); fireEvent.change(passwordInput, { target: { value: 'password' } }); const nextButton = screen.getByTestId('StepForm:submitButton'); await waitFor(() => expect(nextButton).toBeEnabled()); fireEvent.click(nextButton); await waitFor(() => screen.getByTestId('StepForm:yahooAuthError')); }); it('Should click on imap calendar product', async () => { mockUseUser.mockReturnValue(defaultUseUser); easySwitchRender(<ProviderCards />); const imap = screen.getByTestId('ProviderCard:imapCard'); // Open imap product modal and click calendar fireEvent.click(imap); await waitFor(() => screen.getByTestId('MailModal:ProductModal')); const productButtons = screen.getAllByTestId('MailModal:ProductButton'); expect(productButtons).toHaveLength(3); fireEvent.click(productButtons[1]); // SKip instructions and expect to see calendar modal fireEvent.click(screen.getByTestId('Instruction:continue')); }); it('Should click on every product in the imap modal', async () => { mockUseUser.mockReturnValue(defaultUseUser); easySwitchRender(<ProviderCards />); const imap = screen.getByTestId('ProviderCard:imapCard'); // Open imap modal and click on email fireEvent.click(imap); await waitFor(() => screen.getByTestId('MailModal:ProductModal')); let productButtons = screen.getAllByTestId('MailModal:ProductButton'); expect(productButtons).toHaveLength(3); fireEvent.click(productButtons[0]); await waitFor(() => screen.getByTestId('Instruction:defaultMailInstructions')); fireEvent.click(screen.getByTestId('Instruction:close')); // Open imap modal and click on contact fireEvent.click(imap); await waitFor(() => screen.getByTestId('MailModal:ProductModal')); productButtons = screen.getAllByTestId('MailModal:ProductButton'); expect(productButtons).toHaveLength(3); fireEvent.click(productButtons[1]); await waitFor(() => screen.getByTestId('Instruction:defaultCalendarInstructions')); fireEvent.click(screen.getByTestId('Instruction:close')); // Open imap modal and click on contact fireEvent.click(imap); await waitFor(() => screen.getByTestId('MailModal:ProductModal')); productButtons = screen.getAllByTestId('MailModal:ProductButton'); expect(productButtons).toHaveLength(3); fireEvent.click(productButtons[2]); await waitFor(() => screen.getByTestId('Instruction:defaultContactInstructions')); fireEvent.click(screen.getByTestId('Instruction:close')); }); it('Should click on every product in the yahoo modal', async () => { mockUseUser.mockReturnValue(defaultUseUser); easySwitchRender(<ProviderCards />); const yahoo = screen.getByTestId('ProviderCard:yahooCard'); // Open yahoo modal and click on email fireEvent.click(yahoo); await waitFor(() => screen.getByTestId('MailModal:ProductModal')); let productButtons = screen.getAllByTestId('MailModal:ProductButton'); expect(productButtons).toHaveLength(3); fireEvent.click(productButtons[0]); await waitFor(() => screen.getByTestId('Instruction:yahooMailInstructions')); fireEvent.click(screen.getByTestId('Instruction:close')); // Open yahoo modal and click on contact fireEvent.click(yahoo); await waitFor(() => screen.getByTestId('MailModal:ProductModal')); productButtons = screen.getAllByTestId('MailModal:ProductButton'); expect(productButtons).toHaveLength(3); fireEvent.click(productButtons[1]); await waitFor(() => screen.getByTestId('Instruction:yahooCalendarInstructions')); fireEvent.click(screen.getByTestId('Instruction:close')); // Open yahoo modal and click on contact fireEvent.click(yahoo); await waitFor(() => screen.getByTestId('MailModal:ProductModal')); productButtons = screen.getAllByTestId('MailModal:ProductButton'); expect(productButtons).toHaveLength(3); fireEvent.click(productButtons[2]); await waitFor(() => screen.getByTestId('Instruction:yahooContactInstructions')); fireEvent.click(screen.getByTestId('Instruction:close')); }); it('Should disable all cards if user is delinquent', () => { mockUseUser.mockReturnValue([{ hasNonDelinquentScope: false }, false]); easySwitchRender(<ProviderCards />); const google = screen.getByTestId('ProviderCard:googleCard'); const yahoo = screen.getByTestId('ProviderCard:yahooCard'); const outlook = screen.getByTestId('ProviderCard:outlookCard'); const imap = screen.getByTestId('ProviderCard:imapCard'); expect(google).toBeDisabled(); expect(yahoo).toBeDisabled(); expect(outlook).toBeDisabled(); expect(imap).toBeDisabled(); }); it('Should disable all cards while user is loading', () => { mockUseUser.mockReturnValue([{ hasNonDelinquentScope: true }, true]); easySwitchRender(<ProviderCards />); const google = screen.getByTestId('ProviderCard:googleCard'); const yahoo = screen.getByTestId('ProviderCard:yahooCard'); const outlook = screen.getByTestId('ProviderCard:outlookCard'); const imap = screen.getByTestId('ProviderCard:imapCard'); expect(google).toBeDisabled(); expect(yahoo).toBeDisabled(); expect(outlook).toBeDisabled(); expect(imap).toBeDisabled(); }); });
4,940
0
petrpan-code/ProtonMail/WebClients/packages/activation/src
petrpan-code/ProtonMail/WebClients/packages/activation/src/helpers/easyTrans.test.ts
import { EasyTrans } from './easyTrans'; describe('Testing instances returned by easy trans', () => { it('Should return labelInstance', () => { const trans = EasyTrans.get(true).hide(); expect(trans).toStrictEqual('Hide labels'); }); it('Should return folderInstance', () => { const trans = EasyTrans.get(false).hide(); expect(trans).toStrictEqual('Hide folders'); }); });
4,942
0
petrpan-code/ProtonMail/WebClients/packages/activation/src
petrpan-code/ProtonMail/WebClients/packages/activation/src/helpers/errorsMapping.test.ts
import { Label } from '@proton/shared/lib/interfaces'; import { Folder } from '@proton/shared/lib/interfaces/Folder'; import MailImportFoldersParser from './MailImportFoldersParser/MailImportFoldersParser'; import { getApiFoldersTestHelper } from './MailImportFoldersParser/MailImportFoldersParser.test'; import { isNameAlreadyUsed, isNameEmpty, isNameReserved, isNameTooLong } from './errorsMapping'; const smallString = '6NLaLHynY3YPM8gGLncefo5PP7n2Db'; const longString = 'wIfm5MY1a2j7MwYAFNzQapBIXZdBxZaqRGwun6UBFNVimgw38tmmLhn7HewkHhvuNYf5QlC8a2NmfctV42tdfrJJm10okXooWV5f'; describe('Activation errors mapping', () => { describe('isNameTooLong', () => { it('Should return false if the folder/label name is smaller than limit', () => { const res = isNameTooLong(smallString); expect(res).toBe(false); }); it('Should return true if the folder/label name is longer than limit', () => { const res = isNameTooLong(longString); expect(res).toBe(true); }); }); describe('isNameReserved', () => { it('Should return false if the name is not reserved', () => { const res = isNameReserved('folder'); expect(res).toBe(false); }); it('Should return true if the name is reserved and capitalized', () => { const res = isNameReserved('Scheduled'); expect(res).toBe(true); }); it('Should return true if the name is reserved and lowercase', () => { const res = isNameReserved('scheduled'); expect(res).toBe(true); }); }); describe('isNameAlreadyUsed', () => { describe('Is folder mapping', () => { const isLabelMapping = false; it('Should return false if the name not present in collection', () => { const collection = new MailImportFoldersParser( getApiFoldersTestHelper(['path1', 'path2', 'path3']), isLabelMapping ).folders; const item = collection[0]; const res = isNameAlreadyUsed(item, collection, [], [], isLabelMapping); expect(res).toBe(false); }); it('Should return false if a parent has same name as the child', () => { const collection = new MailImportFoldersParser( getApiFoldersTestHelper(['marco', 'marco/marco']), isLabelMapping ).folders; const item = collection[0]; const res = isNameAlreadyUsed(item, collection, [], [], isLabelMapping); expect(res).toBe(false); }); it('Should return false if name not present in array', () => { const collection = new MailImportFoldersParser( getApiFoldersTestHelper(['path1', 'path2']), isLabelMapping ).folders; const item = new MailImportFoldersParser(getApiFoldersTestHelper(['path3']), isLabelMapping).folders[0]; const res = isNameAlreadyUsed(item, collection, [], [], isLabelMapping); expect(res).toBe(false); }); it('Should return false if name not present in array', () => { const item = new MailImportFoldersParser(getApiFoldersTestHelper(['path3']), isLabelMapping).folders[0]; const collection = new MailImportFoldersParser( getApiFoldersTestHelper(['path1', 'path2']), isLabelMapping ).folders; const res = isNameAlreadyUsed(item, collection, [], [], isLabelMapping); expect(res).toBe(false); }); it('Should return true if name present in array', () => { const item = new MailImportFoldersParser(getApiFoldersTestHelper(['path3']), isLabelMapping).folders[0]; // @ts-expect-error need to override the ID because test will think it's the same item item.id = 'anothername'; const collection = new MailImportFoldersParser( getApiFoldersTestHelper(['path1', 'path2', 'path3']), isLabelMapping ).folders; const res = isNameAlreadyUsed(item, collection, [], [], isLabelMapping); expect(res).toBe(true); }); it('Should return false if name present in an empty array', () => { const item = new MailImportFoldersParser(getApiFoldersTestHelper(['path1']), isLabelMapping).folders[0]; const collection = new MailImportFoldersParser(getApiFoldersTestHelper([]), isLabelMapping).folders; const res = isNameAlreadyUsed(item, collection, [], [], isLabelMapping); expect(res).toBe(false); }); it('Should return false if label with similar name exists', () => { const item = new MailImportFoldersParser(getApiFoldersTestHelper(['path1']), isLabelMapping).folders[0]; const collection = new MailImportFoldersParser(getApiFoldersTestHelper([]), isLabelMapping).folders; const res = isNameAlreadyUsed(item, collection, [], [], isLabelMapping); expect(res).toBe(false); }); it('Should return true if label has same name', () => { const item = new MailImportFoldersParser(getApiFoldersTestHelper(['path1']), isLabelMapping).folders[0]; const res = isNameAlreadyUsed(item, [], [{ Path: 'path1' } as Label], [], isLabelMapping); expect(res).toBe(true); }); it('Should return false if folder has same name', () => { const item = new MailImportFoldersParser(getApiFoldersTestHelper(['path1']), isLabelMapping).folders[0]; const res = isNameAlreadyUsed(item, [], [], [{ Path: 'path1' } as Folder], isLabelMapping); expect(res).toBe(false); }); }); describe('Is label mapping', () => { const isLabelMapping = true; it('Should return false if the name not present in collection', () => { const collection = new MailImportFoldersParser( getApiFoldersTestHelper(['path1', 'path2', 'path3']), isLabelMapping ).folders; const item = collection[0]; const res = isNameAlreadyUsed(item, collection, [], [], isLabelMapping); expect(res).toBe(false); }); it('Should return false if a parent has same name as the child', () => { const collection = new MailImportFoldersParser( getApiFoldersTestHelper(['marco', 'marco/marco']), isLabelMapping ).folders; const item = collection[0]; const res = isNameAlreadyUsed(item, collection, [], [], isLabelMapping); expect(res).toBe(false); }); it('Should return false if name not present in array', () => { const collection = new MailImportFoldersParser( getApiFoldersTestHelper(['path1', 'path2']), isLabelMapping ).folders; const item = new MailImportFoldersParser(getApiFoldersTestHelper(['path3']), isLabelMapping).folders[0]; const res = isNameAlreadyUsed(item, collection, [], [], isLabelMapping); expect(res).toBe(false); }); it('Should return false if name not present in array', () => { const item = new MailImportFoldersParser(getApiFoldersTestHelper(['path3']), isLabelMapping).folders[0]; const collection = new MailImportFoldersParser( getApiFoldersTestHelper(['path1', 'path2']), isLabelMapping ).folders; const res = isNameAlreadyUsed(item, collection, [], [], isLabelMapping); expect(res).toBe(false); }); it('Should return true if name present in array', () => { const item = new MailImportFoldersParser(getApiFoldersTestHelper(['path3']), isLabelMapping).folders[0]; // @ts-expect-error need to override the ID because test will think it's the same item item.id = 'anothername'; const collection = new MailImportFoldersParser( getApiFoldersTestHelper(['path1', 'path2', 'path3']), isLabelMapping ).folders; const res = isNameAlreadyUsed(item, collection, [], [], isLabelMapping); expect(res).toBe(true); }); it('Should return false if name present in an empty array', () => { const item = new MailImportFoldersParser(getApiFoldersTestHelper(['path1']), isLabelMapping).folders[0]; const collection = new MailImportFoldersParser(getApiFoldersTestHelper([]), isLabelMapping).folders; const res = isNameAlreadyUsed(item, collection, [], [], isLabelMapping); expect(res).toBe(false); }); it('Should return false if label has same name', () => { const item = new MailImportFoldersParser(getApiFoldersTestHelper(['path1']), isLabelMapping).folders[0]; const res = isNameAlreadyUsed(item, [], [{ Path: 'path1' } as Label], [], isLabelMapping); expect(res).toBe(false); }); it('Should return true if folder has same name', () => { const item = new MailImportFoldersParser(getApiFoldersTestHelper(['path1']), isLabelMapping).folders[0]; const res = isNameAlreadyUsed(item, [], [], [{ Path: 'path1' } as Folder], isLabelMapping); expect(res).toBe(true); }); }); describe('Spaces checks', () => { it('Should return true if name in collection contains a space before', () => { const isLabelMapping = false; const item = new MailImportFoldersParser(getApiFoldersTestHelper([' path3']), isLabelMapping) .folders[0]; // @ts-expect-error need to override the ID because test will think it's the same item item.id = 'anothername'; const collection = new MailImportFoldersParser( getApiFoldersTestHelper(['path1', 'path2', 'path3']), isLabelMapping ).folders; const res = isNameAlreadyUsed(item, collection, [], [], false); expect(res).toBe(true); }); it('Should return true if name in item contains a space after', () => { const isLabelMapping = false; const item = new MailImportFoldersParser(getApiFoldersTestHelper(['path3 ']), isLabelMapping) .folders[0]; // @ts-expect-error need to override the ID because test will think it's the same item item.id = 'anothername'; const collection = new MailImportFoldersParser( getApiFoldersTestHelper(['path1', 'path2', 'path3']), isLabelMapping ).folders; const res = isNameAlreadyUsed(item, collection, [], [], false); expect(res).toBe(true); }); it('Should return true if name in item contains a space before and after', () => { const isLabelMapping = false; const item = new MailImportFoldersParser(getApiFoldersTestHelper([' path3 ']), isLabelMapping) .folders[0]; // @ts-expect-error need to override the ID because test will think it's the same item item.id = 'anothername'; const collection = new MailImportFoldersParser( getApiFoldersTestHelper(['path1', 'path2', 'path3']), isLabelMapping ).folders; const res = isNameAlreadyUsed(item, collection, [], [], false); expect(res).toBe(true); }); it('Should return true if the name present in item contains a space before and after and is capitalized', () => { const isLabelMapping = false; const item = new MailImportFoldersParser(getApiFoldersTestHelper([' Path3 ']), isLabelMapping) .folders[0]; // @ts-expect-error need to override the ID because test will think it's the same item item.id = 'anothername'; const collection = new MailImportFoldersParser( getApiFoldersTestHelper(['path1', 'path2', 'path3']), isLabelMapping ).folders; const res = isNameAlreadyUsed(item, collection, [], [], false); expect(res).toBe(true); }); it('Should return true if the name present in item contains two space before', () => { const isLabelMapping = false; const item = new MailImportFoldersParser(getApiFoldersTestHelper([' Path3']), isLabelMapping) .folders[0]; // @ts-expect-error need to override the ID because test will think it's the same item item.id = 'anothername'; const collection = new MailImportFoldersParser( getApiFoldersTestHelper(['path1', 'path2', 'path3']), isLabelMapping ).folders; const res = isNameAlreadyUsed(item, collection, [], [], false); expect(res).toBe(true); }); it('Should return true if the name in collection contains a space before and after', () => { const isLabelMapping = false; const item = new MailImportFoldersParser(getApiFoldersTestHelper(['path3']), isLabelMapping).folders[0]; // @ts-expect-error need to override the ID because test will think it's the same item item.id = 'anothername'; const collection = new MailImportFoldersParser( getApiFoldersTestHelper(['path1', 'path2', ' path3 ']), isLabelMapping ).folders; const res = isNameAlreadyUsed(item, collection, [], [], false); expect(res).toBe(true); }); it('Should return true if the name passed in collection contains a space before and after and is capitalized', () => { const isLabelMapping = false; const item = new MailImportFoldersParser(getApiFoldersTestHelper(['path3']), isLabelMapping).folders[0]; // @ts-expect-error need to override the ID because test will think it's the same item item.id = 'anothername'; const collection = new MailImportFoldersParser( getApiFoldersTestHelper(['path1', 'path2', ' Path3 ']), isLabelMapping ).folders; const res = isNameAlreadyUsed(item, collection, [], [], false); expect(res).toBe(true); }); }); }); describe('isNameEmpty', () => { it('Should return false if the name is not empty', () => { const res = isNameEmpty('folder'); expect(res).toBe(false); }); it('Should return true if the name is an empty string', () => { const res = isNameEmpty(''); expect(res).toBe(true); }); it('Should return true if the name is undefined', () => { const res = isNameEmpty(undefined); expect(res).toBe(true); }); }); describe('hasMergeWarning', () => {}); });
4,944
0
petrpan-code/ProtonMail/WebClients/packages/activation/src
petrpan-code/ProtonMail/WebClients/packages/activation/src/helpers/getDefaultImportCategories.test.ts
import { MailImportDestinationFolder, MailImportGmailCategories } from '../interface'; import { MailImportFolder } from './MailImportFoldersParser/MailImportFoldersParser'; import { getDefaultImportCategoriesDestination } from './getDefaultImportCategories'; const dummyEmail: MailImportFolder = { id: 'id', checked: true, color: 'test color', isSystemFolderChild: false, folderChildIDS: [''], protonPath: ['path'], providerPath: ['providerPath'], separator: '/', size: 0, category: undefined, folderParentID: '', systemFolder: MailImportDestinationFolder.ARCHIVE, }; const dummyEmailWithCategory: MailImportFolder = { id: 'id', checked: true, color: 'test color', isSystemFolderChild: false, folderChildIDS: [''], protonPath: ['path'], providerPath: ['providerPath'], separator: '/', size: 0, category: MailImportGmailCategories.SOCIAL, folderParentID: '', systemFolder: MailImportDestinationFolder.ARCHIVE, }; const dummyEmailWithCategoryAndSystem: MailImportFolder = { id: 'id', checked: true, color: 'test color', isSystemFolderChild: false, folderChildIDS: [''], protonPath: ['path'], providerPath: ['providerPath'], separator: '/', size: 0, category: MailImportGmailCategories.SOCIAL, folderParentID: '', systemFolder: undefined, }; describe('get default import category', () => { it('Should return inbox if no category folder', () => { const mapping: MailImportFolder[] = [dummyEmail, dummyEmail]; const defaultDestination = getDefaultImportCategoriesDestination(mapping); expect(defaultDestination).toStrictEqual(MailImportDestinationFolder.INBOX); }); it('Should return inbox if category but no system folder', () => { const mapping: MailImportFolder[] = [dummyEmail, dummyEmail, dummyEmailWithCategory]; const defaultDestination = getDefaultImportCategoriesDestination(mapping); expect(defaultDestination).toStrictEqual(dummyEmailWithCategory.systemFolder); }); it('Should return system folder if category', () => { const mapping: MailImportFolder[] = [dummyEmail, dummyEmail, dummyEmailWithCategoryAndSystem]; const defaultDestination = getDefaultImportCategoriesDestination(mapping); expect(defaultDestination).toStrictEqual(MailImportDestinationFolder.INBOX); }); });
4,946
0
petrpan-code/ProtonMail/WebClients/packages/activation/src
petrpan-code/ProtonMail/WebClients/packages/activation/src/helpers/getDefaultTimePeriod.test.ts
import { UserModel } from '@proton/shared/lib/interfaces'; import { TIME_PERIOD } from '../interface'; import { getDefaultTimePeriod } from './getDefaultTimePeriod'; describe('get getDefault time period', () => { it('Should return 3 month for free users', () => { const user: Partial<UserModel> = { hasPaidMail: false, }; const timePeriod = getDefaultTimePeriod(user as UserModel); expect(timePeriod).toBe(TIME_PERIOD.LAST_3_MONTHS); }); it('Should return big bang for free users', () => { const user: Partial<UserModel> = { hasPaidMail: true, }; const timePeriod = getDefaultTimePeriod(user as UserModel); expect(timePeriod).toBe(TIME_PERIOD.BIG_BANG); }); });
4,948
0
petrpan-code/ProtonMail/WebClients/packages/activation/src
petrpan-code/ProtonMail/WebClients/packages/activation/src/helpers/getImportProviderFromApiProvider.test.ts
import { ApiImportProvider } from '../api/api.interface'; import { ImportProvider } from '../interface'; import { getImportProviderFromApiProvider } from './getImportProviderFromApiProvider'; describe('getImportProviderFromApiProvider', () => { it('Should return Google provider', () => { expect(getImportProviderFromApiProvider(ApiImportProvider.GOOGLE)).toBe(ImportProvider.GOOGLE); }); it('Should return Outlook provider', () => { expect(getImportProviderFromApiProvider(ApiImportProvider.OUTLOOK)).toBe(ImportProvider.OUTLOOK); }); it('Should return IMAP provider', () => { expect(getImportProviderFromApiProvider(ApiImportProvider.IMAP)).toBe(ImportProvider.DEFAULT); }); });
4,951
0
petrpan-code/ProtonMail/WebClients/packages/activation/src/helpers
petrpan-code/ProtonMail/WebClients/packages/activation/src/helpers/MailImportFoldersParser/MailImportFoldersParser.test.ts
import { ApiMailImporterFolder } from '@proton/activation/src/api/api.interface'; import { MailImportDestinationFolder } from '@proton/activation/src/interface'; import MailImportFoldersParser, { MailImportFolder } from './MailImportFoldersParser'; /** * List of provider folders paths * * It should respect the parent/child order. No childs can be before their parent * * Naming: * - p => parent * - c => child * - cc => subchild * - ... */ const paths = [ 'Inbox', 'p', 'p/c', 'p/c2', 'p/c2/cc', 'p/c3', 'p2', 'p2/c', 'p2/c/cc', 'p2/c/cc/ccc', 'p2/c/cc/ccc/cccc', 'p2/c/cc/ccc/cccc', ]; /** Basic ApiMailImporterFolders: Source is the minimal required fields */ export const getApiFoldersTestHelper = (paths: string[]) => paths.map( (path) => ({ Source: path, Separator: '/', ...(Object.values(MailImportDestinationFolder).some((dest) => dest.toLowerCase() === path.toLowerCase()) ? { DestinationFolder: path } : {}), } as ApiMailImporterFolder) ); /** Used for testing purpose: Allows to navigate quickier through results */ export const getMappingTestHelper = (folders: MailImportFolder[]) => folders.reduce<Record<string, MailImportFolder>>((acc, folder) => { acc[folder.id] = folder; return acc; }, {}); describe('MailFolderMapping', () => { describe('Folders', () => { it('Should contain expected ids', () => { const isLabelMapping = false; const foldersMapping = getMappingTestHelper( new MailImportFoldersParser(getApiFoldersTestHelper(paths), isLabelMapping).folders ); expect(paths.every((path) => path in foldersMapping)).toBe(true); }); it('Should contain expected path', () => { const isLabelMapping = false; const foldersMapping = getMappingTestHelper( new MailImportFoldersParser(getApiFoldersTestHelper(paths), isLabelMapping).folders ); expect(foldersMapping.Inbox.protonPath).toEqual(['Inbox']); expect(foldersMapping['p/c2/cc'].protonPath).toEqual(['p', 'c2', 'cc']); }); it('Should have color defined', () => { const isLabelMapping = false; const foldersMapping = getMappingTestHelper( new MailImportFoldersParser(getApiFoldersTestHelper(paths), isLabelMapping).folders ); expect(foldersMapping.Inbox.color).toBeDefined(); expect(foldersMapping['p/c2/cc'].color).toBeDefined(); }); it('Should contain expected folderParentIDs', () => { const isLabelMapping = false; const foldersMapping = getMappingTestHelper( new MailImportFoldersParser(getApiFoldersTestHelper(paths), isLabelMapping).folders ); expect(foldersMapping.Inbox.folderParentID).toBeUndefined(); expect(foldersMapping['p/c2'].folderParentID).toBe('p'); expect(foldersMapping['p/c3'].folderParentID).toBe('p'); expect(foldersMapping['p/c2/cc'].folderParentID).toBe('p/c2'); }); it('Should contain expected childIDS', () => { const isLabelMapping = false; const foldersMapping = getMappingTestHelper( new MailImportFoldersParser(getApiFoldersTestHelper(paths), isLabelMapping).folders ); expect(foldersMapping.Inbox.folderChildIDS).toEqual([]); expect(foldersMapping.p.folderChildIDS).toEqual(['p/c', 'p/c2', 'p/c2/cc', 'p/c3']); expect(foldersMapping['p/c2'].folderChildIDS).toEqual(['p/c2/cc']); expect(foldersMapping['p/c2'].folderChildIDS).toEqual(['p/c2/cc']); }); it('Should contain a valid protonPath for folders', () => { const isLabelMapping = false; const foldersMapping = getMappingTestHelper( new MailImportFoldersParser(getApiFoldersTestHelper(paths), isLabelMapping).folders ); expect(foldersMapping['p2/c/cc/ccc/cccc'].protonPath).toEqual(['p2', 'c', 'cc/ccc/cccc']); }); it('Should contain a valid protonPath for labels', () => { const isLabelMapping = true; const foldersMapping = getMappingTestHelper( new MailImportFoldersParser(getApiFoldersTestHelper(paths), isLabelMapping).folders ); expect(foldersMapping['p2/c'].protonPath).toEqual(['p2-c']); expect(foldersMapping['p2/c/cc/ccc/cccc'].protonPath).toEqual(['p2-c-cc-ccc-cccc']); }); it('Should have a specific syntax when system folders have subfolders', () => { const apiFolders = getApiFoldersTestHelper([ 'Inbox', 'Inbox/c', 'Inbox/c/cc', 'Inbox/c/cc/ccc', 'Inbox/c/cc/ccc/cccc', ]); const foldersMapping = getMappingTestHelper(new MailImportFoldersParser(apiFolders, false).folders); expect(foldersMapping['Inbox/c'].protonPath).toEqual(['[Inbox]c']); expect(foldersMapping['Inbox/c/cc'].protonPath).toEqual(['[Inbox]c', 'cc']); expect(foldersMapping['Inbox/c/cc/ccc'].protonPath).toEqual(['[Inbox]c', 'cc', 'ccc']); expect(foldersMapping['Inbox/c/cc/ccc/cccc'].protonPath).toEqual(['[Inbox]c', 'cc', 'ccc/cccc']); const labelsMapping = getMappingTestHelper(new MailImportFoldersParser(apiFolders, true).folders); expect(labelsMapping['Inbox/c'].protonPath).toEqual(['[Inbox]c']); expect(labelsMapping['Inbox/c/cc'].protonPath).toEqual(['[Inbox]c-cc']); }); it('Should tag systemfoldersChilds', () => { const apiFolders = getApiFoldersTestHelper([ 'Inbox', 'Inbox/c', 'Inbox/c/cc', 'Inbox/c/cc/ccc', 'dude', 'dude/c', ]); const foldersMapping = getMappingTestHelper(new MailImportFoldersParser(apiFolders, false).folders); expect(foldersMapping.Inbox.isSystemFolderChild).toBe(false); expect(foldersMapping['Inbox/c'].isSystemFolderChild).toBe(true); expect(foldersMapping['Inbox/c/cc'].isSystemFolderChild).toBe(true); expect(foldersMapping['Inbox/c/cc/ccc'].isSystemFolderChild).toBe(true); expect(foldersMapping.dude.isSystemFolderChild).toBe(false); expect(foldersMapping['dude/c'].isSystemFolderChild).toBe(false); }); it('Should reorder correctly', () => { // Reorder when child before a parent let apiFolders = getApiFoldersTestHelper(['p/c', 'p']); let foldersMapping = new MailImportFoldersParser(apiFolders, false).folders; expect(foldersMapping.map((f) => f.id)).toEqual(['p', 'p/c']); // Reorders nothing when everything is correctly ordered apiFolders = getApiFoldersTestHelper(paths); foldersMapping = new MailImportFoldersParser(apiFolders, false).folders; expect(foldersMapping.map((f) => f.id)).toEqual(paths); // Reorders when system folders has child in wrong place apiFolders = getApiFoldersTestHelper(['inbox', '1234', 'inbox/c']); foldersMapping = new MailImportFoldersParser(apiFolders, false).folders; expect(foldersMapping.map((f) => f.id)).toEqual(['inbox', 'inbox/c', '1234']); // Reorders when system folders has child in wrong place // Non system folders moves dowmside when above system folder apiFolders = getApiFoldersTestHelper([ 'inbox', 'drafts/c/cc', 'dude', 'drafts/c', 'drafts', 'inbox/c', 'inbox/c/cc', 'dude/child', 'adude', ]); foldersMapping = new MailImportFoldersParser(apiFolders, false).folders; expect(foldersMapping.map((f) => f.id)).toEqual([ 'inbox', 'inbox/c', 'inbox/c/cc', 'drafts', 'drafts/c', 'drafts/c/cc', 'adude', 'dude', 'dude/child', ]); }); it('Should ensure that a folder with no parents containing separator is a valid folder', () => { const apiFolders = getApiFoldersTestHelper(['p/c/cc', 'parent', 'parent/child', 'marco', 'marco/marco']); const foldersMapping = getMappingTestHelper(new MailImportFoldersParser(apiFolders, false).folders); expect(foldersMapping['p/c/cc'].protonPath).toEqual(['p/c/cc']); expect(foldersMapping['p/c/cc'].providerPath).toEqual(['p/c/cc']); expect(foldersMapping['marco/marco'].providerPath).toEqual(['marco', 'marco']); const labelsMapping = getMappingTestHelper(new MailImportFoldersParser(apiFolders, true).folders); expect(labelsMapping['p/c/cc'].protonPath).toEqual(['p/c/cc']); expect(labelsMapping['p/c/cc'].providerPath).toEqual(['p/c/cc']); expect(labelsMapping['marco/marco'].providerPath).toEqual(['marco', 'marco']); const apiFoldersA = getApiFoldersTestHelper(['p/c', 'parent', 'parent/child']); const foldersMappingA = getMappingTestHelper(new MailImportFoldersParser(apiFoldersA, false).folders); expect(foldersMappingA['p/c'].protonPath).toEqual(['p/c']); expect(foldersMappingA['p/c'].providerPath).toEqual(['p/c']); const labelsMappingA = getMappingTestHelper(new MailImportFoldersParser(apiFoldersA, true).folders); expect(labelsMappingA['p/c'].protonPath).toEqual(['p/c']); expect(labelsMappingA['p/c'].providerPath).toEqual(['p/c']); const apiFoldersB = getApiFoldersTestHelper(['p', 'p/c', 'p/c/cc/ccc']); const foldersMappingB = getMappingTestHelper(new MailImportFoldersParser(apiFoldersB, false).folders); expect(foldersMappingB['p/c/cc/ccc'].protonPath).toEqual(['p', 'c/cc/ccc']); expect(foldersMappingB['p/c/cc/ccc'].providerPath).toEqual(['p', 'c/cc/ccc']); const apiFoldersC = getApiFoldersTestHelper(['p', 'p/c', 'p/c/cc', 'p/c/cc/ccc', 'p/c/cc/ccc/cccc/ccccc']); const foldersMappingC = getMappingTestHelper(new MailImportFoldersParser(apiFoldersC, false).folders); expect(foldersMappingC['p/c/cc/ccc/cccc/ccccc'].protonPath).toEqual(['p', 'c', 'cc/ccc/cccc/ccccc']); expect(foldersMappingC['p/c/cc/ccc/cccc/ccccc'].providerPath).toEqual(['p', 'c', 'cc', 'ccc/cccc/ccccc']); const labelsMappingC = getMappingTestHelper(new MailImportFoldersParser(apiFoldersC, true).folders); expect(labelsMappingC['p/c/cc/ccc/cccc/ccccc'].providerPath).toEqual(['p', 'c', 'cc', 'ccc/cccc/ccccc']); expect(labelsMappingC['p/c/cc/ccc/cccc/ccccc'].protonPath).toEqual(['p-c-cc-ccc/cccc/ccccc']); }); }); });
4,953
0
petrpan-code/ProtonMail/WebClients/packages/activation/src
petrpan-code/ProtonMail/WebClients/packages/activation/src/hooks/useAvailableAddresses.test.ts
import { renderHook } from '@testing-library/react-hooks'; import { useAddresses } from '@proton/components/index'; import { ADDRESS_TYPE } from '@proton/shared/lib/constants'; import { generateMockAddress, generateMockAddressArray } from '../tests/data/addresses'; import useAvailableAddresses from './useAvailableAddresses'; jest.mock('@proton/components/hooks/useAddresses'); const mockUseAddresses = useAddresses as jest.MockedFunction<any>; describe('useAvailableAddresses', () => { it('Should return empty addresses', () => { mockUseAddresses.mockReturnValue([[], false]); const { result } = renderHook(() => useAvailableAddresses()); expect(result.current).toStrictEqual({ availableAddresses: [], defaultAddress: undefined, loading: false }); }); it('Should return available addresses with active keys', () => { const activeAddresses = generateMockAddressArray(2, true); const disabledAddress = generateMockAddress(3, false); mockUseAddresses.mockReturnValue([[...activeAddresses, disabledAddress], false]); const { result } = renderHook(() => useAvailableAddresses()); expect(result.current.availableAddresses).toHaveLength(2); expect(result.current).toStrictEqual({ availableAddresses: activeAddresses, defaultAddress: activeAddresses[0], loading: false, }); }); it('Should return available addresses and filter external addresses', () => { const activeAddresses = generateMockAddressArray(2, true); const externalAddress = generateMockAddress(3, true, ADDRESS_TYPE.TYPE_EXTERNAL); mockUseAddresses.mockReturnValue([[...activeAddresses, externalAddress], false]); const { result } = renderHook(() => useAvailableAddresses()); expect(result.current.availableAddresses).toHaveLength(2); expect(result.current).toStrictEqual({ availableAddresses: activeAddresses, defaultAddress: activeAddresses[0], loading: false, }); }); });
4,955
0
petrpan-code/ProtonMail/WebClients/packages/activation/src
petrpan-code/ProtonMail/WebClients/packages/activation/src/hooks/useOAuthPopup.helpers.test.ts
import { getScopeFromProvider } from '../components/Modals/OAuth/StepProducts/useStepProducts.helpers'; import { ImportProvider, ImportType, OAUTH_PROVIDER } from '../interface'; import { getOAuthAuthorizationUrl, getOAuthRedirectURL, getProviderNumber } from './useOAuthPopup.helpers'; describe('OAuth url generation', () => { it('Should throw an error when unsupported provider (getProviderNumber)', () => { expect(() => getProviderNumber(ImportProvider.DEFAULT)).toThrowError('Provider does not exist'); }); it('Should throw an error when unsupported provider (getOAuthRedirectURL)', () => { expect(() => getOAuthRedirectURL(ImportProvider.DEFAULT)).toThrowError('Provider does not exist'); }); it('Should throw an error when unsupported provider (getOAuthAuthorizationUrl)', () => { const config = { 'importer.google.client_id': 'string', 'importer.outlook.client_id': 'string', }; expect(() => getOAuthAuthorizationUrl({ provider: ImportProvider.DEFAULT, scope: '', config })).toThrowError( 'Provider does not exist' ); }); it('Should return appropriate number for each supported providers', () => { const googleNumber = getProviderNumber(ImportProvider.GOOGLE); expect(googleNumber).toStrictEqual(OAUTH_PROVIDER.GOOGLE); const outlookNumber = getProviderNumber(ImportProvider.OUTLOOK); expect(outlookNumber).toStrictEqual(OAUTH_PROVIDER.OUTLOOK); }); it('Should return appropriate Google redirect URL', () => { Object.defineProperty(window, 'location', { configurable: true, enumerable: true, value: new URL(window.location.href), }); const expectedUrl = 'https://www.protontesting.com/mypath'; window.location.href = expectedUrl; const redirectUrl = getOAuthRedirectURL(ImportProvider.GOOGLE); expect(redirectUrl).toStrictEqual('https://www.protontesting.com/oauth/callback'); }); it('Should return appropriate Outlook redirect URL', () => { Object.defineProperty(window, 'location', { configurable: true, enumerable: true, value: new URL(window.location.href), }); const expectedUrl = 'https://www.protontesting.com/mypath'; window.location.href = expectedUrl; const redirectUrl = getOAuthRedirectURL(ImportProvider.OUTLOOK); expect(redirectUrl).toStrictEqual('https://www.protontesting.com/oauth/callback'); }); it('Should return appropriate Outlook OAuth URL', () => { const provider = ImportProvider.OUTLOOK; const scopesMail = getScopeFromProvider(provider, [ImportType.MAIL]); const config = { 'importer.google.client_id': 'string', 'importer.outlook.client_id': 'string', }; const outlookMailsRedirect = getOAuthAuthorizationUrl({ provider, scope: scopesMail.join(' '), config }); expect(outlookMailsRedirect).toStrictEqual( 'https://login.microsoftonline.com/common/oauth2/v2.0/authorize?redirect_uri=https%3A%2F%2Fwww.protontesting.com%2Foauth%2Fcallback&response_type=code&scope=email+openid+User.Read+offline_access+Mail.read&prompt=consent&client_id=string' ); const scopesContact = getScopeFromProvider(provider, [ImportType.CONTACTS]); const outlookContactsRedirect = getOAuthAuthorizationUrl({ provider, scope: scopesContact.join(' '), config }); expect(outlookContactsRedirect).toStrictEqual( 'https://login.microsoftonline.com/common/oauth2/v2.0/authorize?redirect_uri=https%3A%2F%2Fwww.protontesting.com%2Foauth%2Fcallback&response_type=code&scope=email+openid+User.Read+offline_access+Contacts.read&prompt=consent&client_id=string' ); const outlookHintRedirect = getOAuthAuthorizationUrl({ provider, scope: scopesContact.join(' '), config, loginHint: 'login hint', }); expect(outlookHintRedirect).toStrictEqual( 'https://login.microsoftonline.com/common/oauth2/v2.0/authorize?redirect_uri=https%3A%2F%2Fwww.protontesting.com%2Foauth%2Fcallback&response_type=code&scope=email+openid+User.Read+offline_access+Contacts.read&prompt=consent&client_id=string' ); const scopesCalendars = getScopeFromProvider(provider, [ImportType.CALENDAR]); const outlookCalendarsRedirect = getOAuthAuthorizationUrl({ provider, scope: scopesCalendars.join(' '), config, }); expect(outlookCalendarsRedirect).toStrictEqual( 'https://login.microsoftonline.com/common/oauth2/v2.0/authorize?redirect_uri=https%3A%2F%2Fwww.protontesting.com%2Foauth%2Fcallback&response_type=code&scope=email+openid+User.Read+offline_access+Calendars.read&prompt=consent&client_id=string' ); const scopesAll = getScopeFromProvider(provider, [ImportType.CALENDAR, ImportType.CONTACTS, ImportType.MAIL]); const outlookAllScopes = getOAuthAuthorizationUrl({ provider, scope: scopesAll.join(' '), config, }); expect(outlookAllScopes).toStrictEqual( 'https://login.microsoftonline.com/common/oauth2/v2.0/authorize?redirect_uri=https%3A%2F%2Fwww.protontesting.com%2Foauth%2Fcallback&response_type=code&scope=email+openid+User.Read+offline_access+Mail.read+Calendars.read+Contacts.read&prompt=consent&client_id=string' ); }); it('Should return appropriate Google OAuth URL', () => { const provider = ImportProvider.GOOGLE; const scopesMail = getScopeFromProvider(provider, [ImportType.MAIL]); const config = { 'importer.google.client_id': 'string', 'importer.outlook.client_id': 'string', }; const googleMailsRedirect = getOAuthAuthorizationUrl({ provider, scope: scopesMail.join(' '), config }); expect(googleMailsRedirect).toStrictEqual( 'https://accounts.google.com/o/oauth2/v2/auth?redirect_uri=https%3A%2F%2Fwww.protontesting.com%2Foauth%2Fcallback&response_type=code&scope=email+openid+https%3A%2F%2Fwww.googleapis.com%2Fauth%2Fgmail.readonly&prompt=consent&access_type=offline&client_id=string' ); const scopesContact = getScopeFromProvider(provider, [ImportType.CONTACTS]); const googleContactsRedirect = getOAuthAuthorizationUrl({ provider, scope: scopesContact.join(' '), config, }); expect(googleContactsRedirect).toStrictEqual( 'https://accounts.google.com/o/oauth2/v2/auth?redirect_uri=https%3A%2F%2Fwww.protontesting.com%2Foauth%2Fcallback&response_type=code&scope=email+openid+https%3A%2F%2Fwww.googleapis.com%2Fauth%2Fcontacts.readonly&prompt=consent&access_type=offline&client_id=string' ); const googleHintRedirect = getOAuthAuthorizationUrl({ provider, scope: scopesContact.join(' '), config, loginHint: 'login hint', }); expect(googleHintRedirect).toStrictEqual( 'https://accounts.google.com/o/oauth2/v2/auth?redirect_uri=https%3A%2F%2Fwww.protontesting.com%2Foauth%2Fcallback&response_type=code&scope=email+openid+https%3A%2F%2Fwww.googleapis.com%2Fauth%2Fcontacts.readonly&prompt=consent&access_type=offline&client_id=string&login_hint=login+hint' ); const scopesCalendars = getScopeFromProvider(provider, [ImportType.CALENDAR]); const googleCalendarsRedirect = getOAuthAuthorizationUrl({ provider, scope: scopesCalendars.join(' '), config, }); expect(googleCalendarsRedirect).toStrictEqual( 'https://accounts.google.com/o/oauth2/v2/auth?redirect_uri=https%3A%2F%2Fwww.protontesting.com%2Foauth%2Fcallback&response_type=code&scope=email+openid+https%3A%2F%2Fwww.googleapis.com%2Fauth%2Fcalendar.readonly&prompt=consent&access_type=offline&client_id=string' ); const scopesAll = getScopeFromProvider(provider, [ImportType.CALENDAR, ImportType.CONTACTS, ImportType.MAIL]); const googleAllScopes = getOAuthAuthorizationUrl({ provider, scope: scopesAll.join(' '), config, }); expect(googleAllScopes).toStrictEqual( 'https://accounts.google.com/o/oauth2/v2/auth?redirect_uri=https%3A%2F%2Fwww.protontesting.com%2Foauth%2Fcallback&response_type=code&scope=email+openid+https%3A%2F%2Fwww.googleapis.com%2Fauth%2Fgmail.readonly+https%3A%2F%2Fwww.googleapis.com%2Fauth%2Fcalendar.readonly+https%3A%2F%2Fwww.googleapis.com%2Fauth%2Fcontacts.readonly&prompt=consent&access_type=offline&client_id=string' ); }); });
4,961
0
petrpan-code/ProtonMail/WebClients/packages/activation/src/logic
petrpan-code/ProtonMail/WebClients/packages/activation/src/logic/draft/draft.selector.test.ts
import { ImportType } from '@proton/activation/src/interface'; import { ImportProvider } from '@proton/activation/src/interface'; import { EasySwitchState } from '../store'; import { selectDraftModal } from './draft.selector'; const BASE_STATE: Omit<EasySwitchState, 'oauthDraft' | 'imapDraft'> = { importers: { importers: {}, activeImporters: {}, loading: 'idle' }, reports: { reports: {}, summaries: {}, loading: 'idle' }, sync: { syncs: {}, listLoading: 'idle', creatingLoading: 'idle' }, }; describe('EasySwitch draft selectors', () => { describe('SelectDraftModal', () => { it('Should return null when idle', () => { const state: EasySwitchState = { ...BASE_STATE, oauthDraft: { step: 'idle', }, imapDraft: { step: 'idle', }, }; expect(selectDraftModal(state)).toEqual(null); }); it('Should return null if imap and oauth started', () => { const state: EasySwitchState = { ...BASE_STATE, oauthDraft: { step: 'started', }, imapDraft: { step: 'started', }, }; expect(selectDraftModal(state)).toEqual(null); }); it('Should return "select-product" when start', () => { const state: EasySwitchState = { ...BASE_STATE, oauthDraft: { step: 'idle', }, imapDraft: { step: 'started', provider: ImportProvider.DEFAULT, hasReadInstructions: false, }, }; expect(selectDraftModal(state)).toEqual('select-product'); }); it('Should return "select-product" when start', () => { const state: EasySwitchState = { ...BASE_STATE, oauthDraft: { step: 'idle', }, imapDraft: { step: 'started', provider: ImportProvider.DEFAULT, product: ImportType.MAIL, hasReadInstructions: false, }, }; expect(selectDraftModal(state)).toEqual('read-instructions'); }); it('Should return "import-{type}" when start import email', () => { const state: EasySwitchState = { ...BASE_STATE, oauthDraft: { step: 'idle', }, imapDraft: { step: 'started', provider: ImportProvider.DEFAULT, product: ImportType.MAIL, hasReadInstructions: true, }, }; expect(selectDraftModal(state)).toEqual('import-Mail'); const state2: EasySwitchState = { ...BASE_STATE, oauthDraft: { step: 'idle', }, imapDraft: { step: 'started', provider: ImportProvider.DEFAULT, product: ImportType.CALENDAR, hasReadInstructions: true, }, }; expect(selectDraftModal(state2)).toEqual('import-Calendar'); const state3: EasySwitchState = { ...BASE_STATE, oauthDraft: { step: 'idle', }, imapDraft: { step: 'started', provider: ImportProvider.DEFAULT, product: ImportType.CONTACTS, hasReadInstructions: true, }, }; expect(selectDraftModal(state3)).toEqual('import-Contacts'); }); it('Should return "oauth" when selecting OAuth import', () => { const state: EasySwitchState = { ...BASE_STATE, oauthDraft: { step: 'started', mailImport: { products: [ImportType.MAIL, ImportType.CALENDAR], }, provider: ImportProvider.GOOGLE, }, imapDraft: { step: 'idle', }, }; expect(selectDraftModal(state)).toEqual('oauth'); }); }); });
5,022
0
petrpan-code/ProtonMail/WebClients/packages/atoms
petrpan-code/ProtonMail/WebClients/packages/atoms/Avatar/Avatar.test.tsx
import { render } from '@testing-library/react'; import Avatar from './Avatar'; describe('<Avatar />', () => { it('accepts a custom class attribute', () => { const child = 'MJ'; const { getByText } = render(<Avatar className="custom">{child}</Avatar>); const element = getByText(child); expect(element).toHaveClass('custom'); expect(element.getAttribute('class')).not.toBe('custom'); }); });
5,027
0
petrpan-code/ProtonMail/WebClients/packages/atoms
petrpan-code/ProtonMail/WebClients/packages/atoms/Button/Button.test.tsx
import { render } from '@testing-library/react'; import { Button } from './Button'; describe('<Button />', () => { it('has button root', () => { const { container } = render(<Button />); const button = container.querySelector('button'); expect(button).toBeVisible(); }); it('has type="button" attribute', () => { const { container } = render(<Button />); const rootElement = container.firstChild; expect(rootElement).toHaveAttribute('type', 'button'); }); });
5,030
0
petrpan-code/ProtonMail/WebClients/packages/atoms
petrpan-code/ProtonMail/WebClients/packages/atoms/Button/ButtonLike.test.tsx
/* eslint-disable jsx-a11y/tabindex-no-positive */ import { fireEvent, render } from '@testing-library/react'; import ButtonLike from './ButtonLike'; const testid = 'button-like'; describe('<ButtonLike />', () => { it('renders with children', () => { const children = 'hello'; const { container } = render(<ButtonLike>{children}</ButtonLike>); const rootElement = container.firstChild; expect(rootElement?.textContent).toBe(children); }); it('adds button class by default', () => { const { container } = render(<ButtonLike />); const rootElement = container.firstChild; expect(rootElement).toHaveClass('button'); }); it('forwards className', () => { const className = 'should-be-forwarded'; const { container } = render(<ButtonLike className={className} />); const rootElement = container.firstChild; expect(rootElement).toHaveClass(className); }); it('allows clicking of button', () => { const mockOnClick = jest.fn(); const { getByTestId } = render(<ButtonLike onClick={mockOnClick} data-testid={testid} />); const rootElement = getByTestId(testid); fireEvent.click(rootElement); expect(rootElement).not.toBeDisabled(); expect(mockOnClick).toHaveBeenCalledTimes(1); }); it('allows setting of tabIndex', () => { const { container } = render(<ButtonLike tabIndex={0} />); const rootElement = container.firstChild; expect(rootElement).toHaveAttribute('tabIndex', '0'); }); it('sets aria-busy attribute to false by default', () => { const { container } = render(<ButtonLike />); const rootElement = container.firstChild; expect(rootElement).toHaveAttribute('aria-busy', 'false'); }); it('does not show loader component by default', () => { const { container } = render(<ButtonLike />); const loaderComponent = container.querySelector('.button-loader-container'); expect(loaderComponent).toBeNull(); }); describe('as', () => { it('defaults to button element', () => { const { container } = render(<ButtonLike />); const button = container.querySelector('button'); expect(button).toBeVisible(); }); it('allows setting of root element', () => { const { container } = render(<ButtonLike as="a" />); const button = container.querySelector('button'); const a = container.querySelector('a'); expect(button).toBeNull(); expect(a).toBeVisible(); }); it(`adds 'inline-block text-center' classes if 'as' prop is not 'button'`, () => { const { container } = render(<ButtonLike as="a" />); const rootElement = container.firstChild; expect(rootElement).toHaveClass('inline-block'); expect(rootElement).toHaveClass('text-center'); }); }); describe('loading', () => { it('disables button', () => { const mockOnClick = jest.fn(); const { getByTestId } = render(<ButtonLike loading onClick={mockOnClick} data-testid={testid} />); const rootElement = getByTestId(testid); fireEvent.click(rootElement); expect(rootElement).toBeDisabled(); expect(mockOnClick).toHaveBeenCalledTimes(0); }); it('adds aria-busy attribute when loading', () => { const { container } = render(<ButtonLike loading />); const rootElement = container.firstChild; expect(rootElement).toHaveAttribute('aria-busy', 'true'); }); it('sets tabIndex to -1', () => { const { container } = render(<ButtonLike loading tabIndex={0} />); const rootElement = container.firstChild; expect(rootElement).toHaveAttribute('tabIndex', '-1'); }); it('renders loader component', () => { const { container } = render(<ButtonLike loading />); const loaderComponent = container.querySelector('.button-loader-container'); expect(loaderComponent).toBeVisible(); }); }); describe('disabled', () => { it('sets tabIndex to -1', () => { const { container } = render(<ButtonLike disabled tabIndex={0} />); const rootElement = container.firstChild; expect(rootElement).toHaveAttribute('tabIndex', '-1'); }); it('disables button', () => { const mockOnClick = jest.fn(); const { getByTestId } = render(<ButtonLike disabled onClick={mockOnClick} data-testid={testid} />); const rootElement = getByTestId(testid); fireEvent.click(rootElement); expect(rootElement).toBeDisabled(); expect(mockOnClick).toHaveBeenCalledTimes(0); }); }); describe('shape', () => { it('defaults to outline if color is weak', () => { const { container } = render(<ButtonLike color="weak" />); const rootElement = container.firstChild; expect(rootElement).toHaveClass('button-outline-weak'); }); it('defaults to solid if color is not weak', () => { const { container } = render(<ButtonLike color="norm" />); const rootElement = container.firstChild; expect(rootElement).toHaveClass('button-solid-norm'); }); describe('solid', () => { it('uses button-solid-weak class', () => { const { container } = render(<ButtonLike shape="solid" />); const rootElement = container.firstChild; expect(rootElement).toHaveClass('button-solid-weak'); }); }); describe('outline', () => { it('uses button-outline-weak class', () => { const { container } = render(<ButtonLike shape="outline" />); const rootElement = container.firstChild; expect(rootElement).toHaveClass('button-outline-weak'); }); }); describe('ghost', () => { it('uses button-ghost-weak class', () => { const { container } = render(<ButtonLike shape="ghost" />); const rootElement = container.firstChild; expect(rootElement).toHaveClass('button-ghost-weak'); }); }); describe('underline', () => { it('removes button class', () => { const { container } = render(<ButtonLike shape="underline" />); const rootElement = container.firstChild; expect(rootElement).not.toHaveClass('button'); }); it('adds button-underline class', () => { const { container } = render(<ButtonLike shape="underline" />); const rootElement = container.firstChild; expect(rootElement).toHaveClass('button-underline'); }); it('does not render as pill even if pill is true', () => { const { container } = render(<ButtonLike shape="underline" pill />); const rootElement = container.firstChild; expect(rootElement).not.toHaveClass('button-pill'); }); it('does not render as icon even if icon is true', () => { const { container } = render(<ButtonLike shape="underline" icon />); const rootElement = container.firstChild; expect(rootElement).not.toHaveClass('button-for-icon'); }); it('does not render full width even if fullWidth is true', () => { const { container } = render(<ButtonLike shape="underline" fullWidth />); const rootElement = container.firstChild; expect(rootElement).not.toHaveClass('w-full'); }); }); }); describe('color', () => { it('defaults to weak', () => { const { container } = render(<ButtonLike />); const rootElement = container.firstChild; expect(rootElement).toHaveClass('button-outline-weak'); }); describe('norm', () => { it('uses button-solid-norm class', () => { const { container } = render(<ButtonLike color="norm" />); const rootElement = container.firstChild; expect(rootElement).toHaveClass('button-solid-norm'); }); }); describe('weak', () => { it('uses button-solid-weak class', () => { const { container } = render(<ButtonLike color="weak" />); const rootElement = container.firstChild; expect(rootElement).toHaveClass('button-outline-weak'); }); }); describe('danger', () => { it('uses button-solid-danger class', () => { const { container } = render(<ButtonLike color="danger" />); const rootElement = container.firstChild; expect(rootElement).toHaveClass('button-solid-danger'); }); }); describe('warning', () => { it('uses button-solid-warning class', () => { const { container } = render(<ButtonLike color="warning" />); const rootElement = container.firstChild; expect(rootElement).toHaveClass('button-solid-warning'); }); }); describe('success', () => { it('uses button-solid-success class', () => { const { container } = render(<ButtonLike color="success" />); const rootElement = container.firstChild; expect(rootElement).toHaveClass('button-solid-success'); }); }); describe('info', () => { it('uses button-solid-info class', () => { const { container } = render(<ButtonLike color="info" />); const rootElement = container.firstChild; expect(rootElement).toHaveClass('button-solid-info'); }); }); }); describe('size', () => { it('defaults to medium', () => { const { container } = render(<ButtonLike />); const rootElement = container.firstChild; /** * There is no button-medium class, * so we assert that the other size classes aren't included */ expect(rootElement).not.toHaveClass('button-large'); expect(rootElement).not.toHaveClass('button-small'); }); it('adds button-small class when size is small', () => { const { container } = render(<ButtonLike size="small" />); const rootElement = container.firstChild; expect(rootElement).toHaveClass('button-small'); }); it('adds button-large class when size is large', () => { const { container } = render(<ButtonLike size="large" />); const rootElement = container.firstChild; expect(rootElement).toHaveClass('button-large'); }); }); describe('fullWidth', () => { it('adds w-full class if fullWidth is true', () => { const { container } = render(<ButtonLike fullWidth />); const rootElement = container.firstChild; expect(rootElement).toHaveClass('w-full'); }); it('does not add w-full class by default', () => { const { container } = render(<ButtonLike />); const rootElement = container.firstChild; expect(rootElement).not.toHaveClass('w-full'); }); }); describe('pill', () => { it('adds button-pill class if pill is true', () => { const { container } = render(<ButtonLike pill />); const rootElement = container.firstChild; expect(rootElement).toHaveClass('button-pill'); }); it('does not add button-pill class by default', () => { const { container } = render(<ButtonLike />); const rootElement = container.firstChild; expect(rootElement).not.toHaveClass('button-pill'); }); }); describe('icon', () => { it('adds button-for-icon class if icon is true', () => { const { container } = render(<ButtonLike icon />); const rootElement = container.firstChild; expect(rootElement).toHaveClass('button-for-icon'); }); it('does not add button-for-icon class by default', () => { const { container } = render(<ButtonLike />); const rootElement = container.firstChild; expect(rootElement).not.toHaveClass('button-for-icon'); }); }); describe('group', () => { it('adds button-group-item class if group is true', () => { const { container } = render(<ButtonLike group />); const rootElement = container.firstChild; expect(rootElement).toHaveClass('button-group-item'); }); it('does not add button-group-item class by default', () => { const { container } = render(<ButtonLike />); const rootElement = container.firstChild; expect(rootElement).not.toHaveClass('button-group-item'); }); }); describe('selected', () => { it('adds is-selected class if group and selected is true', () => { const { container } = render(<ButtonLike group selected />); const rootElement = container.firstChild; expect(rootElement).toHaveClass('is-selected'); }); it('does not add is-selected class if group is false and selected is true', () => { const { container } = render(<ButtonLike selected />); const rootElement = container.firstChild; expect(rootElement).not.toHaveClass('is-selected'); }); it('does not add is-selected by default', () => { const { container } = render(<ButtonLike />); const rootElement = container.firstChild; expect(rootElement).not.toHaveClass('is-selected'); }); }); describe('roleProps', () => { it('adds no role by default', () => { const { container } = render(<ButtonLike />); const rootElement = container.firstChild; expect(rootElement).not.toHaveAttribute('role'); }); it('adds button role if onClick handler exists and no type is defined', () => { const { container } = render(<ButtonLike onClick={() => {}} type={undefined} />); const rootElement = container.firstChild; expect(rootElement).toHaveAttribute('role', 'button'); }); it('adds no role if type is defined', () => { const { container } = render(<ButtonLike type="button" />); const rootElement = container.firstChild; expect(rootElement).not.toHaveAttribute('role'); }); }); });
5,035
0
petrpan-code/ProtonMail/WebClients/packages/atoms
petrpan-code/ProtonMail/WebClients/packages/atoms/Card/Card.test.tsx
import { render } from '@testing-library/react'; import Card from './Card'; describe('<Card />', () => { it('renders with a border and background by default', () => { const { container } = render(<Card>Lorem ipsum dolor sit amet consectetur adipisicing elit.</Card>); expect(container.firstChild).toHaveClass('border'); expect(container.firstChild).toHaveClass('bg-weak'); }); it('renders without a border and background if explicitly specified', () => { const { container } = render( <Card bordered={false} background={false}> Lorem ipsum dolor sit amet consectetur adipisicing elit. </Card> ); expect(container.firstChild).not.toHaveClass('border'); expect(container.firstChild).not.toHaveClass('bg-weak'); }); it('renders rounded', () => { const { container } = render(<Card rounded>Lorem ipsum dolor sit amet consectetur adipisicing elit.</Card>); expect(container.firstChild).toHaveClass('rounded'); }); });
5,041
0
petrpan-code/ProtonMail/WebClients/packages/atoms
petrpan-code/ProtonMail/WebClients/packages/atoms/CircleLoader/CircleLoader.test.tsx
import { render } from '@testing-library/react'; import CircleLoader from './CircleLoader'; const circleLoaderTestId = 'circle-loader'; describe('<CircleLoader />', () => { it('passes className', () => { const { getByTestId } = render(<CircleLoader className="should-be-passed" data-testid={circleLoaderTestId} />); const circleLoaderElement = getByTestId(circleLoaderTestId); expect(circleLoaderElement).toHaveClass('should-be-passed'); }); it('defaults to small size', () => { const { getByTestId } = render(<CircleLoader data-testid={circleLoaderTestId} />); const circleLoaderElement = getByTestId(circleLoaderTestId); expect(circleLoaderElement).toHaveClass('circle-loader'); }); it('adds is-medium class when size is medium', () => { const { getByTestId } = render(<CircleLoader size="medium" data-testid={circleLoaderTestId} />); const circleLoaderElement = getByTestId(circleLoaderTestId); expect(circleLoaderElement).toHaveClass('is-medium'); }); it('adds is-large class when size is large', () => { const { getByTestId } = render(<CircleLoader size="large" data-testid={circleLoaderTestId} />); const circleLoaderElement = getByTestId(circleLoaderTestId); expect(circleLoaderElement).toHaveClass('is-large'); }); it('renders sr-only item', () => { const { getByTestId } = render(<CircleLoader data-testid={circleLoaderTestId} />); const circleLoaderElement = getByTestId(circleLoaderTestId); const srElement = circleLoaderElement.nextSibling; expect(srElement).toHaveClass('sr-only'); expect(srElement?.textContent).toBe('Loading'); }); });
5,046
0
petrpan-code/ProtonMail/WebClients/packages/atoms
petrpan-code/ProtonMail/WebClients/packages/atoms/Donut/Donut.test.tsx
import { render } from '@testing-library/react'; import { ThemeColor } from '@proton/colors/types'; import Donut from './Donut'; describe('<Donut />', () => { it('renders specified segments', () => { const { container } = render( <Donut segments={[ [20, ThemeColor.Danger], [10, ThemeColor.Warning], ]} /> ); expect(container.querySelectorAll('rect')).toHaveLength(4); expect(container.querySelectorAll('circle')).toHaveLength(3); }); });
5,051
0
petrpan-code/ProtonMail/WebClients/packages/atoms
petrpan-code/ProtonMail/WebClients/packages/atoms/Href/Href.test.tsx
import { render } from '@testing-library/react'; import Href from './Href'; describe('<Href />', () => { it('defaults href to #', () => { const { container } = render(<Href>Link text</Href>); expect(container.firstChild).toHaveAttribute('href', '#'); }); it('allows setting of href', () => { const href = 'hello'; const { container } = render(<Href href={href}>Link text</Href>); expect(container.firstChild).toHaveAttribute('href', href); }); it(`defaults target to '_blank'`, () => { const { container } = render(<Href>Link text</Href>); expect(container.firstChild).toHaveAttribute('target', '_blank'); }); it('allows setting of target', () => { const target = 'target'; const { container } = render(<Href target={target}>Link text</Href>); expect(container.firstChild).toHaveAttribute('target', target); }); it(`defaults rel to 'noopener noreferrer nofollow'`, () => { const { container } = render(<Href>Link text</Href>); expect(container.firstChild).toHaveAttribute('rel', 'noopener noreferrer nofollow'); }); it('allows setting of rel', () => { const rel = 'rel'; const { container } = render(<Href rel={rel}>Link text</Href>); expect(container.firstChild).toHaveAttribute('rel', rel); }); it('forwards anchor props', () => { const className = 'className'; const childText = 'Link text'; const { container } = render(<Href className={className}>{childText}</Href>); expect(container.firstChild).toHaveClass(className); expect(container.firstChild?.textContent).toBe(childText); }); });
5,056
0
petrpan-code/ProtonMail/WebClients/packages/atoms
petrpan-code/ProtonMail/WebClients/packages/atoms/Input/Input.test.tsx
import { Matcher, MatcherOptions, fireEvent, render } from '@testing-library/react'; import { Input } from './Input'; type GetByTestIdType = (id: Matcher, options?: MatcherOptions | undefined) => HTMLElement; const inputRootTestid = 'input-root'; const inputElementTestid = 'input-input-element'; describe('<Input />', () => { describe('uncontrolled', () => { it('sets input element value', () => { const { getByTestId } = render(<Input />); const input = getByTestId(inputElementTestid); fireEvent.input(input, { target: { value: 'a' } }); expect(input).toHaveValue('a'); }); }); describe('onValue', () => { it('calls onValue with value when input is fired', () => { const onValue = jest.fn(); const { getByTestId } = render(<Input onValue={onValue} />); const input = getByTestId(inputElementTestid); fireEvent.input(input, { target: { value: 'a' } }); expect(onValue).toHaveBeenCalledWith('a'); }); }); describe('onChange', () => { it('calls onChange when input is fired', () => { const onChange = jest.fn(); const { getByTestId } = render(<Input onChange={onChange} />); const input = getByTestId(inputElementTestid); fireEvent.input(input, { target: { value: 'a' } }); expect(onChange.mock.lastCall[0].target.value).toEqual('a'); }); }); describe('disableChange', () => { describe('true', () => { it('does not call onValue when input is fired', () => { const onValue = jest.fn(); const { getByTestId } = render(<Input onValue={onValue} disableChange />); const input = getByTestId(inputElementTestid); fireEvent.input(input, { target: { value: 'a' } }); expect(onValue).not.toHaveBeenCalled(); }); it('does not call onChange when input is fired', () => { const onChange = jest.fn(); const { getByTestId } = render(<Input onChange={onChange} disableChange />); const input = getByTestId(inputElementTestid); fireEvent.input(input, { target: { value: 'a' } }); expect(onChange).not.toHaveBeenCalled(); }); }); describe('false', () => { it('calls onValue when input is fired', () => { const onValue = jest.fn(); const { getByTestId } = render(<Input onValue={onValue} />); const input = getByTestId(inputElementTestid); fireEvent.input(input, { target: { value: 'a' } }); expect(onValue).toHaveBeenCalled(); }); it('calls onChange when input is fired', () => { const onChange = jest.fn(); const { getByTestId } = render(<Input onChange={onChange} />); const input = getByTestId(inputElementTestid); fireEvent.input(input, { target: { value: 'a' } }); expect(onChange).toHaveBeenCalled(); }); }); }); describe('disabled', () => { it('does not add disabled class by default', () => { const { getByTestId } = render(<Input />); const inputRoot = getByTestId(inputRootTestid); expect(inputRoot).not.toHaveClass('disabled'); }); it('does not set disabled attribute by default', () => { const { getByTestId } = render(<Input />); const input = getByTestId(inputElementTestid); expect(input).not.toHaveAttribute('disabled'); }); describe('when false', () => { it('adds disabled class', () => { const { getByTestId } = render(<Input disabled={false} />); const inputRoot = getByTestId(inputRootTestid); expect(inputRoot).not.toHaveClass('disabled'); }); it('sets disabled attribute to true', () => { const { getByTestId } = render(<Input disabled={false} />); const input = getByTestId(inputElementTestid); expect(input).not.toHaveAttribute('disabled'); }); }); describe('when true', () => { it('adds disabled class', () => { const { getByTestId } = render(<Input disabled />); const inputRoot = getByTestId(inputRootTestid); expect(inputRoot).toHaveClass('disabled'); }); it('sets disabled attribute to true', () => { const { getByTestId } = render(<Input disabled />); const input = getByTestId(inputElementTestid); expect(input).toHaveAttribute('disabled'); }); }); }); describe('error', () => { it('does not add error class by default', () => { const { getByTestId } = render(<Input />); const inputRoot = getByTestId(inputRootTestid); expect(inputRoot).not.toHaveClass('error'); }); it('does not set aria-invalid by default', () => { const { getByTestId } = render(<Input />); const inputElement = getByTestId(inputElementTestid); expect(inputElement).toHaveAttribute('aria-invalid', 'false'); }); describe('falsey', () => { const assertNoError = (getByTestId: GetByTestIdType) => { const inputRoot = getByTestId(inputRootTestid); const inputElement = getByTestId(inputElementTestid); expect(inputRoot).not.toHaveClass('error'); expect(inputElement).toHaveAttribute('aria-invalid', 'false'); }; it('does not add error if error is false', () => { const { getByTestId } = render(<Input error={false} />); assertNoError(getByTestId); }); it('does not add error if error is empty string', () => { const { getByTestId } = render(<Input error="" />); assertNoError(getByTestId); }); }); describe('truthy', () => { const assertError = (getByTestId: GetByTestIdType) => { const inputRoot = getByTestId(inputRootTestid); const inputElement = getByTestId(inputElementTestid); expect(inputRoot).toHaveClass('error'); expect(inputElement).toHaveAttribute('aria-invalid', 'true'); }; it('does not add error if error is true', () => { const { getByTestId } = render(<Input error={true} />); assertError(getByTestId); }); it('does not add error if error is non empty string', () => { const { getByTestId } = render(<Input error="hello" />); assertError(getByTestId); }); it('does not add error if error is <></>', () => { const { getByTestId } = render(<Input error={<></>} />); assertError(getByTestId); }); }); }); describe('unstyled', () => { it('does not add unstyled class by default', () => { const { getByTestId } = render(<Input />); const inputRoot = getByTestId(inputRootTestid); expect(inputRoot).not.toHaveClass('unstyled'); }); describe('when false', () => { it('does not add unstyled class', () => { const { getByTestId } = render(<Input unstyled={false} />); const inputRoot = getByTestId(inputRootTestid); expect(inputRoot).not.toHaveClass('unstyled'); }); }); describe('when true', () => { it('adds unstyled class', () => { const { getByTestId } = render(<Input unstyled />); const inputRoot = getByTestId(inputRootTestid); expect(inputRoot).toHaveClass('unstyled'); }); }); }); });
5,062
0
petrpan-code/ProtonMail/WebClients/packages/atoms
petrpan-code/ProtonMail/WebClients/packages/atoms/Kbd/Kbd.test.tsx
import { render } from '@testing-library/react'; import Kbd from './Kbd'; describe('<Kbd />', () => { it('should render with className kbd and additional className', () => { const { container } = render(<Kbd shortcut="N" className="should-be-passed" />); expect(container.firstChild).toHaveClass('kbd'); expect(container.firstChild).toHaveClass('should-be-passed'); }); it('should render element with text content N', () => { const { container } = render(<Kbd shortcut="N" />); expect(container.textContent).toBe('N'); }); });
5,079
0
petrpan-code/ProtonMail/WebClients/packages/atoms
petrpan-code/ProtonMail/WebClients/packages/atoms/Slider/Slider.test.tsx
import { fireEvent, render } from '@testing-library/react'; import Slider from './Slider'; describe('<Slider />', () => { it('renders min and max mark labels', () => { const { getByTestId } = render(<Slider marks min={10} max={100} />); expect(getByTestId('slider-mark-min').textContent).toBe('10'); expect(getByTestId('slider-mark-max').textContent).toBe('100'); }); /** * Again, rather a safeguard than a recommended use-case */ it("inverts directionality (and doesn't break) if min is larger than max", () => { const { getByTestId } = render(<Slider marks min={100} max={10} />); expect(getByTestId('slider-mark-min').textContent).toBe('100'); expect(getByTestId('slider-mark-max').textContent).toBe('10'); }); it('restricts a value to stay within min & max bounds', () => { const min = 10; const max = 100; const { getByTestId } = render(<Slider value={50} min={min} max={max} />); const input = getByTestId('slider-input'); fireEvent.input(input, { target: { value: '0' } }); expect(getByTestId('slider-input').getAttribute('aria-valuenow')).toEqual(String(min)); fireEvent.input(input, { target: { value: '110' } }); expect(getByTestId('slider-input').getAttribute('aria-valuenow')).toEqual(String(max)); }); });
5,090
0
petrpan-code/ProtonMail/WebClients/packages/atoms
petrpan-code/ProtonMail/WebClients/packages/atoms/Stepper/Stepper.test.tsx
import { render } from '@testing-library/react'; import Step from './Step'; import Stepper from './Stepper'; describe('<Stepper />', () => { it('renders a label for each item', () => { const { container } = render( <Stepper activeStep={0}> <Step>Item 1</Step> <Step>Item 2</Step> </Stepper> ); const labelSteps = container.querySelectorAll('.stepper-labels li'); const labelSelector = 'span'; expect(labelSteps[0].querySelector(labelSelector)?.textContent).toBe('Item 1'); expect(labelSteps[1].querySelector(labelSelector)?.textContent).toBe('Item 2'); }); it('renders a dot for each item', () => { const { container } = render( <Stepper activeStep={0}> <Step>Item 1</Step> <Step>Item 2</Step> </Stepper> ); const indicatorSteps = container.querySelectorAll('.stepper-indicators li'); const dotSelector = '.stepper-item-dot'; expect(indicatorSteps[0].querySelector(dotSelector)).not.toBeNull(); expect(indicatorSteps[1].querySelector(dotSelector)).not.toBeNull(); }); it('renders connector if step is not the first step', () => { const { container } = render( <Stepper activeStep={0}> <Step>Item 1</Step> <Step>Item 2</Step> </Stepper> ); const indicatorSteps = container.querySelectorAll('.stepper-indicators li'); const dotSelector = '.stepper-item-connector'; expect(indicatorSteps[0].querySelector(dotSelector)).toBeNull(); expect(indicatorSteps[1].querySelector(dotSelector)).not.toBeNull(); }); it('adds active class to current step', () => { const { container } = render( <Stepper activeStep={0}> <Step>Item 1</Step> <Step>Item 2</Step> </Stepper> ); const indicatorSteps = container.querySelectorAll('.stepper-indicators li'); const labelSteps = container.querySelectorAll('.stepper-labels li'); expect(indicatorSteps[0]).toHaveClass('stepper-item--active'); expect(labelSteps[0]).toHaveClass('stepper-item--active'); }); it('adds completed class to previous step', () => { const { container } = render( <Stepper activeStep={1}> <Step>Item 1</Step> <Step>Item 2</Step> </Stepper> ); const indicatorSteps = container.querySelectorAll('.stepper-indicators li'); const labelSteps = container.querySelectorAll('.stepper-labels li'); expect(indicatorSteps[0]).toHaveClass('stepper-item--completed'); expect(labelSteps[0]).toHaveClass('stepper-item--completed'); }); });
5,098
0
petrpan-code/ProtonMail/WebClients/packages/atoms
petrpan-code/ProtonMail/WebClients/packages/atoms/VerticalSteps/VerticalSteps.test.tsx
import { RenderResult, render } from '@testing-library/react'; import VerticalStep from './VerticalStep'; import VerticalSteps from './VerticalSteps'; function renderBasicVerticalSteps() { return render( <VerticalSteps> <VerticalStep icon="checkmark" title="Choose a username" description="You successfully selected your new email address." status="passed" /> <VerticalStep icon="lock" title="Today: get instant access" description="15 GB secure mailbox with unlimited personalisation." status="done" /> <VerticalStep icon="bell" title="Day 24: Trial end reminder" description="We’ll send you a notice. Cancel anytime." /> <VerticalStep icon="calendar-row" title="Day 30: Trial ends" description="Your subscription will start Jan 16th. Cancel anytime before." /> </VerticalSteps> ); } describe('<VerticalSteps /> with basic render', () => { let output: RenderResult<typeof import('@testing-library/dom/types/queries'), HTMLElement, HTMLElement>; beforeEach(() => { output = renderBasicVerticalSteps(); }); it('should display 4 steps', () => { const { container } = output; expect(container.querySelectorAll('li')).toHaveLength(4); }); it('should display titles', () => { const { container } = output; const titles = container.querySelectorAll('.vertical-steps-item-text > span:first-child'); expect(titles).toHaveLength(4); expect(titles[0].textContent).toBe('Choose a username'); expect(titles[1].textContent).toBe('Today: get instant access'); expect(titles[2].textContent).toBe('Day 24: Trial end reminder'); expect(titles[3].textContent).toBe('Day 30: Trial ends'); }); it('should display descriptions', () => { const { container } = output; const descriptions = container.querySelectorAll('.vertical-steps-item-text > span:last-child'); expect(descriptions).toHaveLength(4); expect(descriptions[0].textContent).toBe('You successfully selected your new email address.'); expect(descriptions[1].textContent).toBe('15 GB secure mailbox with unlimited personalisation.'); expect(descriptions[2].textContent).toBe('We’ll send you a notice. Cancel anytime.'); expect(descriptions[3].textContent).toBe('Your subscription will start Jan 16th. Cancel anytime before.'); }); });
5,104
0
petrpan-code/ProtonMail/WebClients/packages/atoms
petrpan-code/ProtonMail/WebClients/packages/atoms/Vr/Vr.test.tsx
import { render } from '@testing-library/react'; import Vr from './Vr'; describe('<Vr />', () => { it('should render with className vr', () => { const { container } = render(<Vr className="should-be-passed" />); expect(container.firstChild).toHaveClass('vr'); expect(container.firstChild).toHaveClass('should-be-passed'); }); });
5,113
0
petrpan-code/ProtonMail/WebClients/packages/atoms/create-atom
petrpan-code/ProtonMail/WebClients/packages/atoms/create-atom/templates/Atom.test.tsx.mustache
import { render } from '@testing-library/react'; import {{atomName}} from './{{atomName}}'; describe('<{{atomName}} />', () => { it('should do something', () => { const { container } = render(<{{atomName}} />); }); });
5,121
0
petrpan-code/ProtonMail/WebClients/packages
petrpan-code/ProtonMail/WebClients/packages/colors/gen-accent-shades.test.ts
import tinycolor, { Instance as Color } from 'tinycolor2'; import genAccentShades from './gen-accent-shades'; const getOriginal = (c: Color) => c.getOriginalInput(); describe('genAccentShades', () => { it('generates the necessary shades for an accent color', () => { const output = genAccentShades(tinycolor({ h: 240, s: 1, l: 0.75 })); expect(output.map(getOriginal)).toEqual([ { h: 240, s: 1, l: 0.75 }, { h: 240, s: 0.95, l: 0.7 }, { h: 240, s: 0.9, l: 0.65 }, ]); }); it("doesn't allow values to drop below 0", () => { const output = genAccentShades(tinycolor({ h: 100, s: 0.01, l: 0.01 })); expect(output.map(getOriginal)).toEqual([ { h: 100, s: 0.01, l: 0.01 }, { h: 100, s: 0, l: 0 }, { h: 100, s: 0, l: 0 }, ]); }); });
5,123
0
petrpan-code/ProtonMail/WebClients/packages
petrpan-code/ProtonMail/WebClients/packages/colors/gen-button-shades.test.ts
import tinycolor from 'tinycolor2'; import genButtonShades from './gen-button-shades'; describe('genButtonShades', () => { it('generates the necessary shades for a button', () => { const output = genButtonShades(tinycolor('#6d4aff'), true); expect(output.map((c) => c.toHexString())).toEqual([ '#f0edff', '#e2dbff', '#6d4aff', '#6243e6', '#573bcc', '#4c34b3', ]); }); it("generates the necessary button shades when the color's hue is between 30 & 60", () => { const output = genButtonShades(tinycolor('#ff9900'), true); expect(output.map((c) => c.toHexString())).toEqual([ '#fff5e6', '#ffebcc', '#ff9900', '#f27d00', '#e66300', '#d94c00', ]); }); it("generates the necessary button shades when the color's saturation is less than or equal to 30", () => { const output = genButtonShades(tinycolor('#eae7e4'), true); expect(output.map((c) => c.toHexString())).toEqual([ '#f9f8f7', '#f5f3f2', '#eae7e4', '#dedbd9', '#d3d0cd', '#c7c4c2', ]); }); });
5,126
0
petrpan-code/ProtonMail/WebClients/packages
petrpan-code/ProtonMail/WebClients/packages/colors/gen-themes.test.ts
import { describe, jest } from '@jest/globals'; import fs from 'fs'; import { main } from './gen-themes'; import config from './themes.config'; describe('genThemes', () => { it('generates the necessary shades for a button', async () => { jest.spyOn(fs, 'writeFileSync'); await main(config[0]); expect(fs.writeFileSync).toHaveBeenCalledTimes(1); expect(fs.writeFileSync).toHaveBeenCalledWith( './themes/dist/snow.theme.css', expect.stringContaining(':root,\n' + '.ui-standard {\n' + ' --primary: #6d4aff;') ); }); });
5,133
0
petrpan-code/ProtonMail/WebClients/packages
petrpan-code/ProtonMail/WebClients/packages/colors/shade.test.ts
import tinycolor from 'tinycolor2'; import shade from './shade'; describe('shade', () => { it('shades a color', () => { /* in steps of 10 from 0 to 100*/ const expectedByBase = { '#6d4aff': [ '#6d4aff', '#6243e6', '#573bcc', '#4c34b3', '#412c99', '#372580', '#2c1e66', '#21164d', '#160f33', '#0b071a', '#000000', ], '#DB3251': [ '#db3251', '#c52d49', '#af2841', '#992339', '#831e31', '#6e1929', '#581420', '#420f18', '#2c0a10', '#160508', '#000000', ], }; for (const [input, outputs] of Object.entries(expectedByBase)) { for (const [index, expected] of Object.entries(outputs)) { const output = shade(tinycolor(input), Number(index) * 10); expect(output.toHexString()).toBe(expected); } } }); });
5,136
0
petrpan-code/ProtonMail/WebClients/packages
petrpan-code/ProtonMail/WebClients/packages/colors/tint.test.ts
import tinycolor from 'tinycolor2'; import tint from './tint'; describe('tint', () => { it('tints a color', () => { /* in steps of 10 from 0 to 100*/ const expectedByBase = { '#6d4aff': [ '#6d4aff', '#7c5cff', '#8a6eff', '#9980ff', '#a792ff', '#b6a5ff', '#c5b7ff', '#d3c9ff', '#e2dbff', '#f0edff', '#ffffff', ], '#db3251': [ '#db3251', '#df4762', '#e25b74', '#e67085', '#e98497', '#ed99a8', '#f1adb9', '#f4c2cb', '#f8d6dc', '#fbebee', '#ffffff', ], }; for (const [input, outputs] of Object.entries(expectedByBase)) { for (const [index, expected] of Object.entries(outputs)) { const output = tint(tinycolor(input), Number(index) * 10); expect(output.toHexString()).toBe(expected); } } }); });
5,194
0
petrpan-code/ProtonMail/WebClients/packages/components/components
petrpan-code/ProtonMail/WebClients/packages/components/components/alert/Alert.test.tsx
import { render } from '@testing-library/react'; import Alert from './Alert'; describe('Alert component', () => { const text = 'Panda'; const { container } = render(<Alert className="mb-4">{text}</Alert>); const { firstChild } = container; it('renders children', () => { expect(firstChild?.textContent).toBe(text); }); it('has default class', () => { expect(firstChild).toHaveClass('mb-4 alert-block'); }); it('should have error class for warning type', () => { const { container } = render( <Alert className="mb-4" type="warning"> {text} </Alert> ); expect(container.firstChild).toHaveClass('mb-4 alert-block--warning'); }); });
5,227
0
petrpan-code/ProtonMail/WebClients/packages/components/components
petrpan-code/ProtonMail/WebClients/packages/components/components/calendarEventDateHeader/CalendarEventDateHeader.test.tsx
import { render, screen } from '@testing-library/react'; import { enUS, pt } from 'date-fns/locale'; import { CalendarEventDateHeader } from './index'; describe('CalendarEventDateHeader', () => { describe('should format properly all-day events', () => { it('for single-day events', () => { render( <CalendarEventDateHeader startDate={new Date(Date.UTC(2021, 10, 2))} endDate={new Date(Date.UTC(2021, 10, 3))} isAllDay hasFakeUtcDates formatOptions={{ locale: enUS }} /> ); expect(screen.getByText(/Nov/)).toHaveTextContent('Tue, Nov 2, 2021'); }); it('for multi-day events', () => { render( <CalendarEventDateHeader startDate={new Date(2021, 10, 2)} endDate={new Date(2021, 10, 3)} isAllDay hasModifiedAllDayEndDate formatOptions={{ locale: enUS }} /> ); expect(screen.getByText(/Nov/)).toHaveTextContent('Tue, Nov 2, 2021–Wed, Nov 3, 2021'); }); }); describe('should format properly part-day events', () => { it('for single-day events', () => { render( <CalendarEventDateHeader startDate={new Date(2021, 10, 2, 12, 0)} endDate={new Date(2021, 10, 2, 16, 30)} isAllDay={false} formatOptions={{ locale: enUS }} /> ); expect(screen.getByText(/Nov/)).toHaveTextContent('Tue, Nov 2, 2021, 12:00 PM–4:30 PM'); }); it('for multi-day events', () => { render( <CalendarEventDateHeader startDate={new Date(Date.UTC(2021, 10, 2, 12, 0))} endDate={new Date(Date.UTC(2021, 10, 3, 0, 30))} isAllDay={false} hasFakeUtcDates formatOptions={{ locale: enUS }} /> ); expect(screen.getByText(/Nov/)).toHaveTextContent('Tue, Nov 2, 2021 12:00 PM–Wed, Nov 3, 2021 12:30 AM'); }); }); describe('should format in other locales', () => { it('for all-day events', () => { render( <CalendarEventDateHeader startDate={new Date(Date.UTC(2021, 10, 2))} endDate={new Date(Date.UTC(2021, 10, 2))} isAllDay hasFakeUtcDates hasModifiedAllDayEndDate formatOptions={{ locale: pt }} /> ); expect(screen.getByText(/nov/)).toHaveTextContent('ter, 2 de nov de 2021'); }); it('for part-day events', () => { render( <CalendarEventDateHeader startDate={new Date(2021, 10, 2, 12, 0)} endDate={new Date(2021, 10, 2, 16, 30)} isAllDay={false} formatOptions={{ locale: pt }} /> ); expect(screen.getByText(/nov/)).toHaveTextContent('ter, 2 de nov de 2021, 12:00–16:30'); }); }); });
5,235
0
petrpan-code/ProtonMail/WebClients/packages/components/components
petrpan-code/ProtonMail/WebClients/packages/components/components/checklist/CheckListItem.test.tsx
import { fireEvent } from '@testing-library/react'; import { render } from '@proton/components/containers/contacts/tests/render'; import CheckListItem from './CheckListItem'; const checklistItemProps = { largeIcon: 'largeIcon', smallIcon: 'smallIcon', text: 'text', onClick: jest.fn(), smallVariant: false, done: false, }; describe('ChecklistItem', () => { it('Should trigger onclick when clicked', async () => { const onClick = jest.fn(); const { getByRole } = render(<CheckListItem {...checklistItemProps} onClick={onClick} />, false); const item = getByRole('button'); fireEvent.click(item); expect(onClick).toHaveBeenCalled(); }); it('Should not trigger onclick when disabled', async () => { const onClick = jest.fn(); const { getByRole } = render(<CheckListItem {...checklistItemProps} onClick={onClick} disabled />, false); const item = getByRole('button'); fireEvent.click(item); expect(onClick).not.toHaveBeenCalled(); }); it('Should trigger onclick when done', async () => { const onClick = jest.fn(); const { getByRole } = render(<CheckListItem {...checklistItemProps} onClick={onClick} done />, false); const item = getByRole('button'); fireEvent.click(item); expect(onClick).toHaveBeenCalled(); }); it('Should use the largeIcon when smallVariant is false', async () => { const { getByTestId } = render(<CheckListItem {...checklistItemProps} />, false); const icon = getByTestId('checklist-item-icon-large'); expect(icon).toBeTruthy(); }); it('Should use the smallIcon when smallVariant is true', async () => { const { getByTestId } = render(<CheckListItem {...checklistItemProps} smallVariant />, false); const icon = getByTestId('checklist-item-icon-small'); expect(icon).toBeTruthy(); }); });
5,238
0
petrpan-code/ProtonMail/WebClients/packages/components/components
petrpan-code/ProtonMail/WebClients/packages/components/components/collapsible/Collapsible.test.tsx
import { render } from '@testing-library/react'; import Collapsible from './Collapsible'; import CollapsibleContent from './CollapsibleContent'; import CollapsibleHeader from './CollapsibleHeader'; // test accessibility? describe('<Collapsible />', () => { it('renders only the header by default', () => { const { getByTestId } = render( <Collapsible> <CollapsibleHeader>Header</CollapsibleHeader> <CollapsibleContent>Content</CollapsibleContent> </Collapsible> ); const header = getByTestId('collapsible-header'); const content = getByTestId('collapsible-content'); expect(header.textContent).toBe('Header'); expect(content).not.toBeVisible(); }); it('renders content when expandByDefault is true', () => { const { getByTestId } = render( <Collapsible expandByDefault> <CollapsibleHeader>Header</CollapsibleHeader> <CollapsibleContent>Content</CollapsibleContent> </Collapsible> ); const content = getByTestId('collapsible-content'); expect(content.textContent).toBe('Content'); expect(content).toBeVisible(); }); it('toggles content when header is clicked', () => { const { getByTestId } = render( <Collapsible> <CollapsibleHeader>Header</CollapsibleHeader> <CollapsibleContent>Content</CollapsibleContent> </Collapsible> ); const header = getByTestId('collapsible-header'); const content = getByTestId('collapsible-content'); expect(content).not.toBeVisible(); header.click(); expect(content).toBeVisible(); header.click(); expect(content).not.toBeVisible(); }); });
5,274
0
petrpan-code/ProtonMail/WebClients/packages/components/components
petrpan-code/ProtonMail/WebClients/packages/components/components/country/CountrySelect.helpers.test.ts
import { CountryOption, PRESELECTED_COUNTRY_OPTION_SUFFIX, divideSortedCountries, getAllDropdownOptions, getCleanCountryCode, groupCountriesByStartingLetter, optionToPreselectedOption, } from '@proton/components/components/country/helpers'; const countryOptions: CountryOption[] = [ { countryName: 'France', countryCode: 'fr' }, { countryName: 'Switzerland', countryCode: 'ch' }, { countryName: 'Australia', countryCode: 'au' }, { countryName: 'Finland', countryCode: 'fi' }, ]; const groupedCountries = { A: [{ countryName: 'Australia', countryCode: 'au' }], F: [ { countryName: 'France', countryCode: 'fr' }, { countryName: 'Finland', countryCode: 'fi' }, ], S: [{ countryName: 'Switzerland', countryCode: 'ch' }], }; const dropdownOptions = [ { type: 'divider', text: 'A' }, { type: 'country', countryName: 'Australia', countryCode: 'au' }, { type: 'divider', text: 'F' }, { type: 'country', countryName: 'France', countryCode: 'fr' }, { type: 'country', countryName: 'Finland', countryCode: 'fi' }, { type: 'divider', text: 'S' }, { type: 'country', countryName: 'Switzerland', countryCode: 'ch' }, ]; describe('CountrySelect helpers', () => { describe('groupCountriesByStartingLetter', () => { it('should group countries options by their starting letters', () => { expect(groupCountriesByStartingLetter(countryOptions)).toEqual(groupedCountries); }); }); describe('divideSortedCountries', () => { it('should create dropdown options split by dividers', () => { expect(divideSortedCountries(groupedCountries)).toEqual(dropdownOptions); }); }); describe('getCountryDropdownOptions', () => { it('should return expected dropdown options', () => { expect(getAllDropdownOptions(countryOptions)).toEqual(dropdownOptions); }); it('should return dropdown options with pre-selected options', () => { const preSelectedOption: CountryOption = { countryName: 'France', countryCode: 'fr' }; const expected = [ { type: 'divider', text: 'Based on your time zone' }, { type: 'country', countryName: 'France', countryCode: 'fr-preselected' }, ...dropdownOptions, ]; expect(getAllDropdownOptions(countryOptions, preSelectedOption)).toEqual(expected); }); it('should return dropdown options with pre-selected options and divider text', () => { const dividerText = 'Whatever'; const preSelectedOption: CountryOption = { countryName: 'France', countryCode: 'fr' }; const expected = [ { type: 'divider', text: dividerText }, { type: 'country', countryName: 'France', countryCode: 'fr-preselected' }, ...dropdownOptions, ]; expect(getAllDropdownOptions(countryOptions, preSelectedOption, dividerText)).toEqual(expected); }); }); describe('getCleanCountryCode', () => { it('cleans the pre-selected suffix', () => { expect(getCleanCountryCode(`fr${PRESELECTED_COUNTRY_OPTION_SUFFIX}`)).toEqual('fr'); }); it('returns the country code if no suffix is present', () => { expect(getCleanCountryCode('ch')).toEqual('ch'); }); }); describe('optionToPreselectedOption', () => { it('should add `-preselected` suffix to option countryCode', () => { expect(optionToPreselectedOption({ countryName: 'France', countryCode: 'fr' })).toEqual({ countryName: 'France', countryCode: 'fr-preselected', }); }); it('should return option as it is if already suffixed', () => { expect(optionToPreselectedOption({ countryName: 'France', countryCode: 'fr-preselected' })).toEqual({ countryName: 'France', countryCode: 'fr-preselected', }); }); }); });
5,318
0
petrpan-code/ProtonMail/WebClients/packages/components/components
petrpan-code/ProtonMail/WebClients/packages/components/components/dropdown/Dropdown.test.tsx
import { ReactNode, useRef, useState } from 'react'; import { fireEvent, render } from '@testing-library/react'; import userEvent from '@testing-library/user-event'; import { DropdownProps, DropdownSizeUnit } from '@proton/components/components'; import Dropdown from './Dropdown'; import DropdownButton from './DropdownButton'; const Test = ({ children, dropdownProps, ...rest }: { children: ReactNode; dropdownProps?: any; [key: string]: any; }) => { const anchorRef = useRef<HTMLButtonElement>(null); const [open, setOpen] = useState(false); return ( <> <DropdownButton ref={anchorRef} isOpen={open} onClick={() => { setOpen(true); }} {...rest} > Open </DropdownButton> <Dropdown isOpen={open} anchorRef={anchorRef} onClose={() => { setOpen(false); }} {...dropdownProps} > {children} </Dropdown> </> ); }; describe('<Dropdown />', () => { it('should show a dropdown when opened', async () => { const { getByTestId, queryByTestId } = render( <Test data-testid="dropdown-open"> <div data-testid="dropdown-inner">Hello world</div> </Test> ); expect(queryByTestId('dropdown-inner')).toBeNull(); await userEvent.click(getByTestId('dropdown-open')); expect(getByTestId('dropdown-inner')).toBeVisible(); }); it('should auto close when open', async () => { const { getByTestId, queryByTestId } = render( <div> <div data-testid="outside">outside dropdown</div> <Test data-testid="dropdown-open" dropdownProps={{ 'data-testid': 'dropdown' }}> <div data-testid="dropdown-inner">Hello world</div> </Test> </div> ); await userEvent.click(getByTestId('dropdown-open')); expect(getByTestId('dropdown')).toBeVisible(); await userEvent.click(getByTestId('outside')); fireEvent.animationEnd(getByTestId('dropdown'), { animationName: 'anime-dropdown-out' }); expect(queryByTestId('dropdown-test')).toBeNull(); }); describe('dropdown size', () => { const Test = (props: { size: DropdownProps['size'] }) => { const ref = useRef<HTMLDivElement>(null); return ( <Dropdown anchorRef={ref} isOpen={true} data-testid="dropdown" {...props}> hello </Dropdown> ); }; it('should should set initial on viewport max size', async () => { const { getByTestId } = render( <Test size={{ maxWidth: DropdownSizeUnit.Viewport, maxHeight: DropdownSizeUnit.Viewport }} /> ); expect(getByTestId('dropdown')).toHaveStyle('--custom-max-width: initial; --custom-max-height: initial'); }); it('should should set custom max height', async () => { const { getByTestId } = render(<Test size={{ maxWidth: DropdownSizeUnit.Viewport, maxHeight: '13em' }} />); expect(getByTestId('dropdown')).toHaveStyle('--custom-max-width: initial; --custom-max-height: 13em'); }); it('should should set custom height', async () => { const { getByTestId } = render( <Test size={{ height: '15px', maxWidth: DropdownSizeUnit.Viewport, maxHeight: '13em' }} /> ); expect(getByTestId('dropdown')).toHaveStyle( '--height: 15px; --custom-max-width: initial; --custom-max-height: 13em' ); }); it('should should set custom width', async () => { const { getByTestId } = render( <Test size={{ width: '13px', height: '15px', maxWidth: '13em', maxHeight: DropdownSizeUnit.Viewport, }} /> ); expect(getByTestId('dropdown')).toHaveStyle( '--width: 13px; --height: 15px; --custom-max-width: 13em; --custom-max-height: initial' ); }); }); });
5,375
0
petrpan-code/ProtonMail/WebClients/packages/components/components/editor
petrpan-code/ProtonMail/WebClients/packages/components/components/editor/toolbar/ToolbarFontFaceDropdown.test.tsx
import { fireEvent, render } from '@testing-library/react'; import { DEFAULT_FONT_FACE, FONT_FACES } from '../constants'; import { getFontFaceIdFromValue } from '../helpers/fontFace'; import ToolbarFontFaceDropdown from './ToolbarFontFaceDropdown'; describe('Toolbar font face dropdown', () => { it('Should display default font value when no values', () => { const { getByTestId } = render( <ToolbarFontFaceDropdown defaultValue={null} setValue={() => {}} onClickDefault={() => {}} showDefaultFontSelector /> ); const selectedValue = getByTestId('editor-toolbar:font-face:selected-value'); const defaultFontFaceID = getFontFaceIdFromValue(DEFAULT_FONT_FACE); // To be "Arial" expect(selectedValue.innerHTML).toBe(defaultFontFaceID); }); it('Should display fonts dropdown on click', () => { const { getByTestId } = render( <ToolbarFontFaceDropdown defaultValue={null} setValue={() => {}} onClickDefault={() => {}} showDefaultFontSelector /> ); const input = getByTestId('editor-toolbar:font-face:selected-value'); fireEvent.click(input); Object.values(FONT_FACES).forEach(({ id }) => { expect(getByTestId(`editor-toolbar:font-face:dropdown-item:${id}`)).toBeInTheDocument(); }); }); it('Should display "default font" button in dropdown', () => { const { getByTestId } = render( <ToolbarFontFaceDropdown defaultValue={null} setValue={() => {}} onClickDefault={() => {}} showDefaultFontSelector /> ); const input = getByTestId('editor-toolbar:font-face:selected-value'); fireEvent.click(input); const defaultFontFaceID = getFontFaceIdFromValue(DEFAULT_FONT_FACE); expect(getByTestId(`editor-toolbar:font-face:dropdown-item:${defaultFontFaceID}`)).toBeInTheDocument(); expect(getByTestId(`editor-toolbar:font-face:dropdown-item:${defaultFontFaceID}:default`)).toBeInTheDocument(); }); });
5,389
0
petrpan-code/ProtonMail/WebClients/packages/components/components
petrpan-code/ProtonMail/WebClients/packages/components/components/focus/useFocusTrap.test.tsx
import { ReactNode, useRef, useState } from 'react'; import { fireEvent, render, waitFor } from '@testing-library/react'; import useFocusTrap from './useFocusTrap'; describe('FocusTrap', () => { let initialFocus: HTMLElement; beforeEach(() => { initialFocus = document.createElement('button'); document.body.appendChild(initialFocus); initialFocus.focus(); }); afterEach(() => { document.body.removeChild(initialFocus); }); it('should not focus the first focusable element', () => { const Component = () => { const rootRef = useRef<HTMLDivElement>(null); const props = useFocusTrap({ rootRef }); return ( <div ref={rootRef} {...props}> <input data-testid="auto-focus" /> </div> ); }; const { getByTestId } = render(<Component />); expect(getByTestId('auto-focus')).not.toHaveFocus(); }); it('should focus the root element if initial setting is off', () => { const Component = () => { const rootRef = useRef<HTMLDivElement>(null); const props = useFocusTrap({ rootRef, enableInitialFocus: false }); return ( <div ref={rootRef} {...props} data-testid="root-focus"> <input data-testid="auto-focus" /> </div> ); }; const { getByTestId } = render(<Component />); expect(getByTestId('root-focus')).toHaveFocus(); }); it('should respect autoFocus in children', () => { const Component = () => { const rootRef = useRef<HTMLDivElement>(null); const props = useFocusTrap({ rootRef }); return ( <div ref={rootRef} {...props}> <input /> <input autoFocus data-testid="auto-focus" /> </div> ); }; const { getByTestId } = render(<Component />); expect(getByTestId('auto-focus')).toHaveFocus(); }); it('should set tabIndex on root if there are focusable elements', () => { const Component = () => { const rootRef = useRef<HTMLDivElement>(null); const props = useFocusTrap({ rootRef }); return ( <div ref={rootRef} {...props} data-testid="root"> <button autoFocus /> </div> ); }; const { getByTestId } = render(<Component />); expect(getByTestId('root')).toHaveAttribute('tabIndex', '-1'); }); it('should focus first fallback if requested', () => { const Component = () => { const rootRef = useRef<HTMLDivElement>(null); const props = useFocusTrap({ rootRef }); return ( <div ref={rootRef} {...props} data-testid="root"> <div data-testid="div" data-focus-trap-fallback="0" tabIndex={-1} /> <button data-testid="button" /> </div> ); }; const { getByTestId } = render(<Component />); expect(getByTestId('div')).toHaveFocus(); }); it('should set tabIndex on root when active', () => { const Component = () => { const [active, setActive] = useState(false); const rootRef = useRef<HTMLDivElement>(null); const props = useFocusTrap({ active, rootRef }); return ( <div ref={rootRef} {...props} data-testid="root"> <button data-testid="button" autoFocus onClick={() => setActive(!active)} /> </div> ); }; const { getByTestId } = render(<Component />); expect(getByTestId('root')).not.toHaveAttribute('tabIndex', '-1'); const openerButton = getByTestId('button'); openerButton.click(); expect(getByTestId('root')).toHaveAttribute('tabIndex', '-1'); openerButton.click(); expect(getByTestId('root')).not.toHaveAttribute('tabIndex', '-1'); }); it('should set tabIndex on root if there are no focusable elements', () => { const Component = () => { const rootRef = useRef<HTMLDivElement>(null); const props = useFocusTrap({ rootRef }); return ( <div ref={rootRef} {...props} data-testid="root"> <div>No focusable element</div> </div> ); }; const { getByTestId } = render(<Component />); expect(getByTestId('root')).toHaveAttribute('tabIndex', '-1'); }); it('should not restore focus if closed by click', async () => { const Component = () => { const [open, setOpen] = useState(false); const rootRef = useRef<HTMLDivElement>(null); const props = useFocusTrap({ rootRef, active: open }); return ( <div> <button data-testid="button" onClick={() => setOpen(true)} /> {open && ( <div {...props} ref={rootRef}> <button data-testid="close" onClick={() => setOpen(false)} /> <input autoFocus data-testid="input" /> </div> )} </div> ); }; const { getByTestId } = render(<Component />); const openerButton = getByTestId('button'); openerButton.focus(); fireEvent.mouseUp(openerButton); fireEvent.click(openerButton); expect(getByTestId('input')).toHaveFocus(); const closeButton = getByTestId('close'); fireEvent.mouseUp(closeButton); fireEvent.click(closeButton); await waitFor(() => { expect(openerButton).not.toHaveFocus(); }); }); it('should restore focus if closed by keyboard', async () => { const Component = () => { const [open, setOpen] = useState(false); const rootRef = useRef<HTMLDivElement>(null); const props = useFocusTrap({ rootRef, active: open }); return ( <div> <button data-testid="button" onClick={() => setOpen(true)} /> {open && ( <div {...props} ref={rootRef}> <input autoFocus data-testid="input" onKeyDown={() => setOpen(false)} /> </div> )} </div> ); }; const { getByTestId } = render(<Component />); const openerButton = getByTestId('button'); openerButton.focus(); fireEvent.mouseUp(openerButton); fireEvent.click(openerButton); expect(getByTestId('input')).toHaveFocus(); fireEvent.keyDown(getByTestId('input'), { key: 'Esc' }); await waitFor(() => { expect(openerButton).toHaveFocus(); }); }); // TODO: Broken with latest jsdom it.skip('should not restore focus when another trap overrides it', async () => { const Dropdown = ({ open, children }: { open: boolean; children: ReactNode }) => { const rootRef = useRef<HTMLDivElement>(null); const props = useFocusTrap({ rootRef, active: open }); return ( <> {open && ( <div {...props} ref={rootRef}> {children} </div> )} </> ); }; const Component = () => { const [open, setOpen] = useState(false); const [open2nd, setOpen2nd] = useState(false); return ( <div> <button data-testid="button1" onClick={() => setOpen(!open)} /> <Dropdown open={open}> <input autoFocus data-testid="input1" /> </Dropdown> <button data-testid="button2" onClick={() => setOpen2nd(!open2nd)} /> <Dropdown open={open2nd}> <input autoFocus data-testid="input2" /> </Dropdown> </div> ); }; const { getByTestId } = render(<Component />); const openerButton = getByTestId('button1'); openerButton.focus(); openerButton.click(); await waitFor(() => { expect(getByTestId('input1')).toHaveFocus(); }); const openerButton2 = getByTestId('button2'); openerButton2.focus(); openerButton2.click(); await waitFor(() => { expect(getByTestId('input2')).toHaveFocus(); }); openerButton.click(); await waitFor(() => { expect(getByTestId('input2')).toHaveFocus(); }); openerButton2.click(); await waitFor(() => { expect(openerButton2).toHaveFocus(); }); }); it('should contain focus when tabbing', async () => { const Component = () => { const rootRef = useRef<HTMLDivElement>(null); const props = useFocusTrap({ rootRef }); return ( <div> <button data-testid="outside-1" /> <div {...props} ref={rootRef} data-testid="root"> <button data-testid="1" /> <button data-testid="2" autoFocus /> </div> <button data-testid="outside-2" /> </div> ); }; const { getByTestId } = render(<Component />); expect(getByTestId('2')).toHaveFocus(); fireEvent.keyDown(getByTestId('2'), { key: 'Tab', }); expect(getByTestId('1')).toHaveFocus(); fireEvent.keyDown(getByTestId('1'), { key: 'Tab', shiftKey: true, }); expect(getByTestId('2')).toHaveFocus(); }); it('should contain focus when elements are deleted', async () => { jest.useFakeTimers(); const Component = () => { const rootRef = useRef<HTMLDivElement>(null); const [hidden, setHidden] = useState(false); const props = useFocusTrap({ rootRef }); return ( <div {...props} ref={rootRef} data-testid="root"> {!hidden && <button data-testid="1" autoFocus onClick={() => setHidden(true)} />} </div> ); }; const { getByTestId } = render(<Component />); expect(getByTestId('1')).toHaveFocus(); fireEvent.click(getByTestId('1')); jest.runOnlyPendingTimers(); expect(getByTestId('root')).toHaveFocus(); jest.useRealTimers(); }); });
5,441
0
petrpan-code/ProtonMail/WebClients/packages/components/components
petrpan-code/ProtonMail/WebClients/packages/components/components/input/TimeInput.test.tsx
import { fireEvent, render, screen } from '@testing-library/react'; import noop from '@proton/utils/noop'; import TimeInput from './TimeInput'; describe('TimeInput component', () => { it('should display a time input of type text', () => { const date = new Date(2023, 0, 11, 12); const { container } = render(<TimeInput value={date} onChange={noop} />); const inputNode = container.querySelector('input'); expect(inputNode).not.toBe(null); expect(inputNode?.getAttribute('type')).toBe('text'); }); it('should display the time with duration', () => { const date = new Date(2023, 0, 1, 12); render(<TimeInput value={date} min={date} onChange={noop} displayDuration />); const input = screen.getByDisplayValue(/12/); expect(input).toHaveValue('12:00 PM'); fireEvent.click(input); // display duration options screen.getByText('0 min'); screen.getByText('30 min'); screen.getByText('30 min'); screen.getByText('1 h'); screen.getByText('1.5 h'); screen.getByText('2 h'); screen.getByText('2.5 h'); }); });
5,479
0
petrpan-code/ProtonMail/WebClients/packages/components/components
petrpan-code/ProtonMail/WebClients/packages/components/components/maintenanceLayout/SettingsMaintenanceLayoutWrapper.test.tsx
import { render } from '@testing-library/react'; import { SettingsAreaConfig, useFlag } from '../..'; import SettingsMaintenanceLayoutWrapper from './SettingsMaintenanceLayoutWrapper'; const config: SettingsAreaConfig = { text: 'text', subsections: [ { text: 'text', id: 'id', }, ], }; jest.mock('../..'); const mockUseFlag = useFlag as unknown as jest.MockedFunction<any>; jest.mock('@proton/components/hooks/useAppTitle'); jest.mock('react-router', () => ({ __esModule: true, useLocation: jest.fn().mockReturnValue({ location: { pathname: '/' } }), })); describe('SettingsMaintenanceLayoutWrapper', () => { it('should handle is in Maintenance', () => { mockUseFlag.mockReturnValue(true); const { getByText, queryByText } = render( <SettingsMaintenanceLayoutWrapper config={config} maintenanceFlag="MaintenanceImporter"> <div>children</div> </SettingsMaintenanceLayoutWrapper> ); expect(queryByText(config.text)).toBeTruthy(); expect(getByText('This feature is temporarily unavailable')).toBeInTheDocument(); }); it('should handle is not in maintenance', () => { mockUseFlag.mockReturnValue(false); const { getByText, queryByText } = render( <SettingsMaintenanceLayoutWrapper config={config} maintenanceFlag="MaintenanceImporter"> <div>children</div> </SettingsMaintenanceLayoutWrapper> ); expect(queryByText(config.text)).toBeNull(); expect(getByText('children')).toBeInTheDocument(); }); it('should handle is in maintenance and is subsection', () => { mockUseFlag.mockReturnValue(true); const { getByText, queryByText } = render( <SettingsMaintenanceLayoutWrapper config={config} maintenanceFlag="MaintenanceImporter" isSubsection> <div>children</div> </SettingsMaintenanceLayoutWrapper> ); expect(queryByText(config.text)).toBeNull(); expect(getByText('This feature is temporarily unavailable')).toBeInTheDocument(); }); it('should handle is not in maintenance and is subsection', () => { mockUseFlag.mockReturnValue(false); const { getByText, queryByText } = render( <SettingsMaintenanceLayoutWrapper config={config} maintenanceFlag="MaintenanceImporter" isSubsection> <div>children</div> </SettingsMaintenanceLayoutWrapper> ); expect(queryByText(config.text)).toBeNull(); expect(getByText('children')).toBeInTheDocument(); }); });
5,483
0
petrpan-code/ProtonMail/WebClients/packages/components/components
petrpan-code/ProtonMail/WebClients/packages/components/components/miniCalendar/MiniCalendar.test.tsx
import { fireEvent, render, screen } from '@testing-library/react'; import MiniCalendar from './MiniCalendar'; describe('MiniCalendar', () => { const getFakeNow = () => new Date(Date.UTC(2021, 0, 1, 0, 0, 0)); beforeAll(() => { jest.useFakeTimers().setSystemTime(getFakeNow().getTime()); }); it('disables today button when out of range', async () => { const { rerender } = render(<MiniCalendar date={getFakeNow()} hasToday min={getFakeNow()} />); const getTodayButton = () => screen.getByTestId(/minicalendar:today/); expect(getTodayButton()).not.toBeDisabled(); const fakeTomorrow = getFakeNow(); fakeTomorrow.setUTCDate(getFakeNow().getUTCDate() + 1); rerender(<MiniCalendar date={getFakeNow()} hasToday min={fakeTomorrow} />); expect(getTodayButton()).toBeDisabled(); const fakeYesterday = getFakeNow(); fakeYesterday.setUTCDate(getFakeNow().getUTCDate() - 1); rerender(<MiniCalendar date={getFakeNow()} hasToday max={fakeYesterday} />); expect(getTodayButton()).toBeDisabled(); }); it('disables month navigation when out of range', async () => { const { rerender } = render(<MiniCalendar date={getFakeNow()} min={getFakeNow()} max={getFakeNow()} />); const getPrevMonthButton = () => screen.getByTestId(/minicalendar:previous-month/); const getNextMonthButton = () => screen.getByTestId(/minicalendar:next-month/); expect(getPrevMonthButton()).toBeDisabled(); expect(getNextMonthButton()).toBeDisabled(); const fakeNextMonth = getFakeNow(); const fakePrevMonth = getFakeNow(); fakePrevMonth.setUTCMonth(getFakeNow().getUTCMonth() - 1); fakeNextMonth.setUTCMonth(getFakeNow().getUTCMonth() + 1); rerender(<MiniCalendar date={getFakeNow()} hasToday min={fakePrevMonth} max={fakeNextMonth} />); expect(getPrevMonthButton()).not.toBeDisabled(); expect(getNextMonthButton()).not.toBeDisabled(); fireEvent.click(getNextMonthButton()); expect(getNextMonthButton()).toBeDisabled(); fireEvent.click(getPrevMonthButton()); fireEvent.click(getPrevMonthButton()); expect(getPrevMonthButton()).toBeDisabled(); }); });
5,515
0
petrpan-code/ProtonMail/WebClients/packages/components/components
petrpan-code/ProtonMail/WebClients/packages/components/components/modalTwo/ModalTwo.test.tsx
import { ReactNode, useEffect, useState } from 'react'; import { fireEvent, render, screen } from '@testing-library/react'; import { Button } from '@proton/atoms'; import ModalTwo from './Modal'; // Mocked so that the modal renders in the same container jest.mock('react-dom', () => { const original = jest.requireActual('react-dom'); return { ...original, createPortal: (node: any) => node, }; }); const Inner = ({ onMount }: { onMount: () => void }) => { useEffect(() => { onMount(); }, []); return <div data-testid="inner">I'm only mounted once</div>; }; const MyModal = ({ open, onClose, children, disableCloseOnEscape, }: { open: boolean; onClose: () => void; children: ReactNode; disableCloseOnEscape?: boolean; }) => { return ( <ModalTwo open={open} onClose={onClose} disableCloseOnEscape={disableCloseOnEscape}> {children} <Button data-testid="close-button" onClick={onClose} /> </ModalTwo> ); }; const Container = ({ children, open: initialOpen = false, disableCloseOnEscape, }: { children: ReactNode; open?: boolean; disableCloseOnEscape?: boolean; }) => { const [open, setOpen] = useState(initialOpen); return ( <> <Button data-testid="open-button" onClick={() => setOpen(true)} /> <MyModal open={open} onClose={() => setOpen(false)} disableCloseOnEscape={disableCloseOnEscape}> {children} </MyModal> </> ); }; const getOutModal = (container: Element) => { return container.querySelector('.modal-two--out'); }; const maybeTriggerOutAnimation = (div?: Element | null) => { if (!div) { return; } fireEvent.animationEnd(div, { animationName: 'anime-modal-two-out' }); }; describe('ModalTwo rendering', () => { it('should not render children when closed', () => { const { queryByTestId } = render( <ModalTwo> <div data-testid="inner">Not rendered</div> </ModalTwo> ); expect(queryByTestId('inner')).toBeNull(); }); it('should render children when open', () => { const { queryByTestId } = render( <ModalTwo open> <div data-testid="inner">Rendered</div> </ModalTwo> ); expect(queryByTestId('inner')).toHaveTextContent('Rendered'); }); it('should render children when going from closed to open', () => { const { getByTestId, queryByTestId } = render( <Container> <div data-testid="inner">Rendered</div> </Container> ); expect(queryByTestId('inner')).toBeNull(); fireEvent.click(getByTestId('open-button')); expect(queryByTestId('inner')).toHaveTextContent('Rendered'); }); it('should not render children when going from open to closed', () => { const { container, getByTestId, queryByTestId } = render( <Container open> <div data-testid="inner">Rendered</div> </Container> ); expect(getOutModal(container)).toBeNull(); expect(queryByTestId('inner')).toHaveTextContent('Rendered'); fireEvent.click(getByTestId('close-button')); maybeTriggerOutAnimation(getOutModal(container)); expect(queryByTestId('inner')).toBeNull(); }); it('should only trigger mount once per render', async () => { const handleMount = jest.fn(); const { container, getByTestId, queryByTestId } = render( <Container> <Inner onMount={handleMount} /> </Container> ); const run = (n: number) => { expect(getOutModal(container)).toBeNull(); expect(handleMount).toHaveBeenCalledTimes(n); expect(queryByTestId('inner')).toBeNull(); fireEvent.click(getByTestId('open-button')); expect(getOutModal(container)).toBeNull(); expect(handleMount).toHaveBeenCalledTimes(n + 1); expect(queryByTestId('inner')).toHaveTextContent('mounted once'); fireEvent.click(getByTestId('close-button')); maybeTriggerOutAnimation(getOutModal(container)); expect(queryByTestId('inner')).toBeNull(); expect(handleMount).toHaveBeenCalledTimes(n + 1); }; run(0); run(1); run(2); }); it('should only trigger mount once per render if initially opened', async () => { const handleMount = jest.fn(); const { container, getByTestId, queryByTestId } = render( <Container open={true}> <Inner onMount={handleMount} /> </Container> ); const run = (n: number) => { expect(getOutModal(container)).toBeNull(); expect(handleMount).toHaveBeenCalledTimes(n); expect(queryByTestId('inner')).toHaveTextContent('mounted once'); fireEvent.click(getByTestId('close-button')); maybeTriggerOutAnimation(getOutModal(container)); expect(queryByTestId('inner')).toBeNull(); expect(handleMount).toHaveBeenCalledTimes(n); fireEvent.click(getByTestId('open-button')); expect(getOutModal(container)).toBeNull(); expect(handleMount).toHaveBeenCalledTimes(n + 1); expect(queryByTestId('inner')).toHaveTextContent('mounted once'); }; run(1); run(2); run(3); }); }); describe('ModalTwo Hotkeys', () => { it('should close on esc', () => { const { container, getByTestId, queryByTestId } = render( <Container open={true}> <div data-testid="inner">Rendered</div> </Container> ); expect(getOutModal(container)).toBeNull(); expect(queryByTestId('inner')).toHaveTextContent('Rendered'); fireEvent.keyDown(getByTestId('close-button'), { key: 'Escape' }); maybeTriggerOutAnimation(getOutModal(container)); expect(queryByTestId('inner')).toBeNull(); }); it('should not close on esc if disabled', () => { const { container, getByTestId, queryByTestId } = render( <Container open={true} disableCloseOnEscape> <div data-testid="inner">Rendered</div> </Container> ); expect(getOutModal(container)).toBeNull(); expect(queryByTestId('inner')).toHaveTextContent('Rendered'); fireEvent.keyDown(getByTestId('close-button'), { key: 'Escape' }); maybeTriggerOutAnimation(getOutModal(container)); expect(queryByTestId('inner')).toHaveTextContent('Rendered'); }); }); /** * Due to a JSDom issue `dialog` tag is not understood correctly * Delete this test when the Jest will implement the fix * - Issue: https://github.com/jsdom/jsdom/issues/3294 * - Fix pull request: https://github.com/jsdom/jsdom/pull/3403 */ describe('ModalTwo GetByRole issue', () => { it('Content should be selectable by role', () => { render( <ModalTwo open> <Button>Hello</Button> </ModalTwo> ); expect(screen.getByRole('button', { name: 'Hello' })).toBeVisible(); }); });
5,520
0
petrpan-code/ProtonMail/WebClients/packages/components/components
petrpan-code/ProtonMail/WebClients/packages/components/components/newFeatureTag/NewFeatureTag.test.tsx
import { render, screen } from '@testing-library/react'; import { IsActiveInEnvironmentContainer, SpotlightProps } from '@proton/components/components'; import { getItem, removeItem, setItem } from '@proton/shared/lib/helpers/storage'; import NewFeatureTag from './NewFeatureTag'; jest.mock('@proton/shared/lib/helpers/storage'); const mockedGetItem = jest.mocked(getItem); const mockedSetItem = jest.mocked(setItem); const mockedRemoveItem = jest.mocked(removeItem); const SPOTLIGHT_ID = 'this-is-a-mocked-spotlight'; const NEW_FEATURE_TAG_ID = 'this-is-a-test-instance-of-new-feature-tag'; jest.mock('@proton/components/components', () => ({ __esModule: true, Spotlight: () => <div data-testid={SPOTLIGHT_ID}></div>, })); describe('NewFeatureTag component', () => { const featureKey = 'feature-key'; const localStorageKey = `${featureKey}-new-tag`; const defaultValue = 'false'; beforeEach(() => { // Monday, April 24, 2023 9:00:00 AM jest.setSystemTime(new Date('2023-04-24T09:00:00')); jest.clearAllMocks(); }); it('NewFeatureTag should be always shown by default', () => { // Friday, December 1, 2023 9:00:00 AM const endDate = new Date('2023-12-1T09:00:00'); mockedGetItem.mockReturnValue(undefined); const { rerender } = render(<NewFeatureTag featureKey={featureKey} className="ml-10" endDate={endDate} />); expect(screen.getByText('New')).toBeInTheDocument(); rerender(<NewFeatureTag featureKey={featureKey} className="ml-10" />); expect(mockedGetItem).toHaveBeenCalledWith(localStorageKey, defaultValue); expect(mockedSetItem).not.toHaveBeenCalled(); expect(mockedRemoveItem).not.toHaveBeenCalled(); }); it('NewFeatureTag should be show once with showOnce', () => { const { rerender, unmount } = render(<NewFeatureTag featureKey={featureKey} showOnce className="ml-10" />); expect(screen.getByText('New')).toBeInTheDocument(); expect(mockedGetItem).toHaveBeenCalledWith(localStorageKey, defaultValue); unmount(); expect(mockedSetItem).toHaveBeenCalledWith(`${featureKey}-new-tag`, 'true'); mockedGetItem.mockReturnValue('true'); rerender(<NewFeatureTag featureKey={featureKey} showOnce className="ml-10" />); expect(mockedRemoveItem).not.toHaveBeenCalledWith(); expect(screen.queryByText('New')).not.toBeInTheDocument(); }); it('NewFeatureTag should not be shown if date end', () => { // Thursday, December 1, 2022 9:00:00 AM const endDate = new Date('2022-12-01T09:00:00'); const { unmount } = render(<NewFeatureTag featureKey={featureKey} endDate={endDate} className="ml-10" />); expect(screen.queryByText('New')).not.toBeInTheDocument(); expect(mockedSetItem).not.toHaveBeenCalled(); expect(mockedRemoveItem).toHaveBeenCalledWith(`${featureKey}-new-tag`); unmount(); expect(setItem).not.toHaveBeenCalled(); }); it('should add a Spotlight', () => { const spotlightProps: SpotlightProps = { show: true, content: <div></div>, }; const result = render( <NewFeatureTag featureKey={'doesntmatterhere'} spotlightProps={spotlightProps}></NewFeatureTag> ); expect(result.getByTestId(SPOTLIGHT_ID)).toBeTruthy(); }); it('should not render if it was not in the proper environment', () => { const environmentDontRender: IsActiveInEnvironmentContainer = { default: false, alpha: false, beta: false, }; const resultNotRendered = render( <NewFeatureTag data-testid="" featureKey={'doesntmatterhere'} isActiveInEnvironment={environmentDontRender} ></NewFeatureTag> ); expect(() => resultNotRendered.getByTestId(NEW_FEATURE_TAG_ID)).toThrowError( 'Unable to find an element by: [data-testid="this-is-a-test-instance-of-new-feature-tag"]' ); const environmentRender: IsActiveInEnvironmentContainer = { default: true, alpha: true, beta: true, }; const resultRendered = render( <NewFeatureTag data-testid="" featureKey={'doesntmatterhere'} isActiveInEnvironment={environmentRender} ></NewFeatureTag> ); expect(() => resultRendered.getByTestId(NEW_FEATURE_TAG_ID)).toBeTruthy(); }); });
5,549
0
petrpan-code/ProtonMail/WebClients/packages/components/components
petrpan-code/ProtonMail/WebClients/packages/components/components/popper/usePopper.test.tsx
import { useState } from 'react'; import { Middleware, shift as mockedShift } from '@floating-ui/dom'; import { act, render, screen } from '@testing-library/react'; import { PopperPlacement } from '@proton/components/components'; import { wait } from '@proton/shared/lib/helpers/promise'; import usePopper from './usePopper'; jest.mock('@floating-ui/dom', () => { const originalModule = jest.requireActual('@floating-ui/dom'); // Mock the default export and named export 'foo' return { __esModule: true, ...originalModule, shift: jest.fn(originalModule.shift), }; }); describe('usePopper', () => { Object.defineProperties(window.HTMLElement.prototype, { // @ts-ignore getBoundingClientRect: { value: function () { return { width: parseFloat(this.style.width) || 0, height: parseFloat(this.style.height) || 0, top: parseFloat(this.style.top) || 0, left: parseFloat(this.style.left) || 0, }; }, }, clientHeight: { get: function () { return 100; }, }, clientWidth: { get: function () { return 100; }, }, }); const Test = ({ isOpen, originalPlacement, anchor, }: { isOpen: boolean; originalPlacement: PopperPlacement; anchor?: { top: number; left: number }; }) => { const [ref, setRef] = useState<HTMLDivElement | null>(null); const { floating, position, arrow, placement } = usePopper({ isOpen, originalPlacement, offset: 0, reference: anchor ? { mode: 'position', value: anchor, anchor: ref, } : { mode: 'element', value: ref, }, }); return ( <div> <div ref={setRef} data-testid="reference" style={{ top: '10px', left: '10px', width: '10px', height: '10px' }} > hello world </div> <div ref={floating} data-testid="floating" data-placement={placement} style={{ ...position, ...arrow, width: '1px', height: '1px' }} > floating </div> </div> ); }; it('should return a hidden placement when not open', async () => { render(<Test isOpen={false} originalPlacement="top-start" />); await act(async () => {}); expect(screen.getByTestId('floating').dataset.placement).toBe('hidden'); }); it('should render a floating element when open', async () => { render(<Test isOpen={true} originalPlacement="top-start" />); await act(async () => {}); expect(screen.getByTestId('floating').dataset.placement).toBe('top-start'); // @ts-ignore expect(screen.getByTestId('floating').style._values).toEqual({ top: '10px', left: '10px', width: '1px', height: '1px', '--arrow-offset': '0', }); }); it('should render without race conditions', async () => { const { rerender } = render(<Test isOpen={true} originalPlacement="top-start" />); const shift = mockedShift as jest.Mock<Middleware>; const original = shift(); const mock: Middleware = { name: 'shift', fn: async (...args) => { await wait(1); return original.fn(...args); }, }; shift.mockReturnValue(mock); rerender(<Test isOpen={true} originalPlacement="top-start" />); shift.mockRestore(); rerender(<Test isOpen={true} originalPlacement="top-start" anchor={{ top: 2, left: 3 }} />); await act(async () => {}); // @ts-ignore expect(screen.getByTestId('floating').style._values).toEqual({ top: '2px', left: '3px', width: '1px', height: '1px', '--arrow-offset': '0', }); }); it('should render a floating element in an anchor element and in an anchor position', async () => { const { rerender } = render(<Test isOpen={true} originalPlacement="top-start" />); await act(async () => {}); // @ts-ignore expect(screen.getByTestId('floating').style._values).toEqual({ top: '10px', left: '10px', width: '1px', height: '1px', '--arrow-offset': '0', }); rerender(<Test isOpen={true} originalPlacement="top-start" anchor={{ top: 1, left: 2 }} />); await act(async () => {}); // @ts-ignore expect(screen.getByTestId('floating').style._values).toEqual({ top: '1px', left: '2px', width: '1px', height: '1px', '--arrow-offset': '0', }); }); });
5,553
0
petrpan-code/ProtonMail/WebClients/packages/components/components
petrpan-code/ProtonMail/WebClients/packages/components/components/popper/utils.test.ts
import { getFallbackPlacements, getInvertedRTLPlacement } from '@proton/components/components/popper/utils'; describe('popper utils', () => { describe('fallback placements', () => { test('should sort placements when given top-end', () => { expect(getFallbackPlacements('top-end')).toEqual([ 'top-start', 'top', 'bottom-end', 'bottom', 'bottom-start', 'right-start', 'right', 'right-end', 'left-end', 'left', 'left-start', ]); }); test('should sort placements when given top', () => { expect(getFallbackPlacements('top')).toEqual([ 'top-start', 'top-end', 'bottom', 'bottom-end', 'bottom-start', 'right-start', 'right', 'right-end', 'left-end', 'left', 'left-start', ]); }); test('should sort placements when given right', () => { expect(getFallbackPlacements('right')).toEqual([ 'right-start', 'right-end', 'left', 'left-end', 'left-start', 'top-start', 'top', 'top-end', 'bottom-end', 'bottom', 'bottom-start', ]); }); test('should sort placements when given left-start', () => { expect(getFallbackPlacements('left-start')).toEqual([ 'left-end', 'left', 'right-start', 'right', 'right-end', 'top-start', 'top', 'top-end', 'bottom-end', 'bottom', 'bottom-start', ]); }); test('should sort placements when given left-end', () => { expect(getFallbackPlacements('left-end')).toEqual([ 'left', 'left-start', 'right-end', 'right-start', 'right', 'top-start', 'top', 'top-end', 'bottom-end', 'bottom', 'bottom-start', ]); }); }); describe('rtl placement', () => { test('should get rtl placement', () => { expect(getInvertedRTLPlacement('top-start', true)).toEqual('top-end'); expect(getInvertedRTLPlacement('top-end', true)).toEqual('top-start'); expect(getInvertedRTLPlacement('right-start', true)).toEqual('right-start'); expect(getInvertedRTLPlacement('right-end', true)).toEqual('right-end'); expect(getInvertedRTLPlacement('bottom-end', true)).toEqual('bottom-start'); expect(getInvertedRTLPlacement('bottom-start', true)).toEqual('bottom-end'); expect(getInvertedRTLPlacement('left-start', true)).toEqual('left-start'); expect(getInvertedRTLPlacement('left-end', true)).toEqual('left-end'); expect(getInvertedRTLPlacement('top-start', false)).toEqual('top-start'); expect(getInvertedRTLPlacement('top-end', false)).toEqual('top-end'); expect(getInvertedRTLPlacement('bottom-start', false)).toEqual('bottom-start'); expect(getInvertedRTLPlacement('bottom-end', false)).toEqual('bottom-end'); }); }); });
5,559
0
petrpan-code/ProtonMail/WebClients/packages/components/components
petrpan-code/ProtonMail/WebClients/packages/components/components/price/Price.test.tsx
import { render } from '@testing-library/react'; import Price from './Price'; describe('Price component', () => { it('should render negative price with USD currency', () => { const { container } = render(<Price currency="USD">{-1500}</Price>); expect((container.firstChild as any).textContent).toBe('-$15'); }); it('should render price with EUR in suffix', () => { const { container } = render(<Price currency="EUR">{1500}</Price>); expect((container.firstChild as any).textContent).toBe('15 €'); }); it('should render price with CHF in prefix', () => { const { container } = render(<Price currency="CHF">{1500}</Price>); expect((container.firstChild as any).textContent).toBe('CHF 15'); }); it('should use the divisor defined', () => { const { container } = render(<Price divisor={1}>{1500}</Price>); expect((container.firstChild as any).textContent).toBe('1500'); }); it('should render string values as is', () => { const { container } = render(<Price>{'Let us talk'}</Price>); expect((container.firstChild as any).textContent).toBe('Let us talk'); }); });
5,573
0
petrpan-code/ProtonMail/WebClients/packages/components/components
petrpan-code/ProtonMail/WebClients/packages/components/components/protonBadge/ProtonBadgeType.test.tsx
import { render } from '@testing-library/react'; import { ProtonBadgeType } from '@proton/components/components'; import { Recipient } from '@proton/shared/lib/interfaces'; jest.mock('@proton/components/hooks/useFeature', () => jest.fn(() => ({ feature: { Value: true } }))); describe('ProtonBadgeType', () => { it('should show a verified badge', async () => { const verifiedRecipient: Recipient = { Name: 'Verified', Address: '[email protected]', IsProton: 1, }; const { getByTestId } = render(<ProtonBadgeType recipient={verifiedRecipient} />); getByTestId('proton-badge'); }); it('should not show a verified badge', async () => { const normalRecipient: Recipient = { Name: 'Normal', Address: '[email protected]', IsProton: 0, }; const { queryByTestId } = render(<ProtonBadgeType recipient={normalRecipient} />); const protonBadge = queryByTestId('proton-badge'); expect(protonBadge).toBeNull(); }); });
5,583
0
petrpan-code/ProtonMail/WebClients/packages/components/components
petrpan-code/ProtonMail/WebClients/packages/components/components/selectTwo/SelectTwo.test.tsx
import { RenderResult, fireEvent, render, within } from '@testing-library/react'; import { Option } from '../option'; import SelectTwo from './SelectTwo'; function renderBasicSelect() { return render( <SelectTwo data-testid="dropdown-button"> <Option title="one" value="one" /> <Option title="two" value="two" /> <Option title="three" value="three" /> </SelectTwo> ); } function renderSelectWithSelectedOption() { return render( <SelectTwo value="two" data-testid="dropdown-button"> <Option title="one" value="one" /> <Option title="two" value="two" /> <Option title="three" value="three" /> </SelectTwo> ); } function getAnchor({ getByTestId }: RenderResult) { return getByTestId('dropdown-button'); } function getList({ getByTestId }: RenderResult) { return getByTestId('select-list'); } function openByClick(renderResult: RenderResult) { fireEvent.click(getAnchor(renderResult)); } describe('SelectTwo component', () => { it('should open on click', () => { const output = renderBasicSelect(); openByClick(output); expect(getList(output)).toBeInTheDocument(); }); it('should select a value on click', () => { const spy = jest.fn(); const output = render( <SelectTwo onChange={spy} data-testid="dropdown-button"> <Option title="one" value="one" /> <Option title="two" value="two" /> </SelectTwo> ); openByClick(output); const { getByText } = output; fireEvent.click(getByText('one')); const [[{ value }]] = spy.mock.calls; expect(value).toBe('one'); }); it('should render a placeholer if no value is selected', () => { const { getByText } = render( <SelectTwo placeholder="Placeholder" data-testid="dropdown-button"> <Option title="one" value="one" /> <Option title="two" value="two" /> </SelectTwo> ); expect(getByText('Placeholder')).toBeTruthy(); }); it(`should open on " " (Space) keydown`, () => { const output = renderBasicSelect(); fireEvent.keyDown(getAnchor(output), { key: ' ' }); expect(getList(output)).toBeInTheDocument(); }); it(`should select "two" when typing "t"`, () => { const spy = jest.fn(); const output = render( <SelectTwo onChange={spy} data-testid="dropdown-button"> <Option title="one" value="one" /> <Option title="two" value="two" /> </SelectTwo> ); fireEvent.keyDown(getAnchor(output), { key: 't' }); const [[{ value }]] = spy.mock.calls; expect(value).toBe('two'); }); it('should focus the first element when opened and no option is selected', () => { const output = renderBasicSelect(); openByClick(output); const { getByText } = output; expect(getByText('one')).toHaveFocus(); }); it('should focus the selected element when opened and an option is selected', () => { const output = renderSelectWithSelectedOption(); openByClick(output); const { getByText } = within(getList(output)); expect(getByText('two')).toHaveFocus(); }); /* * https://spectrum.chat/testing-library/general/ontransitionend~7b84288b-716e-42c3-853c-78295a92fd63 */ // it('should close on "Escape" keydown and give focus back to anchor', () => { // const output = renderBasicSelect(); // openByClick(output); // fireEvent.keyDown(getList(output), { key: 'Escape' }); // expect(getList(output)).not.toBeInTheDocument(); // expect(getAnchor(output)).toHaveFocus(); // }); it(`should focus the next option on "ArrowDown" keydown`, () => { const output = renderBasicSelect(); openByClick(output); fireEvent.keyDown(getList(output), { key: 'ArrowDown' }); const { getByText } = within(getList(output)); expect(getByText('two')).toHaveFocus(); }); it(`should focus the previous option on "ArrowUp" keydown`, () => { const output = renderSelectWithSelectedOption(); openByClick(output); fireEvent.keyDown(getList(output), { key: 'ArrowUp' }); const { getByText } = within(getList(output)); expect(getByText('one')).toHaveFocus(); }); /* * https://spectrum.chat/testing-library/general/ontransitionend~7b84288b-716e-42c3-853c-78295a92fd63 */ // it('should close the select and focus the anchor when pressing "Shift+Tab" given that the first element is selected', () => { // const output = renderBasicSelect(); // openByClick(output); // fireEvent.keyDown(getList(output), { key: 'Tab', shiftKey: true }); // expect(getList(output)).not.toBeInTheDocument(); // expect(getAnchor(output)).toHaveFocus(); // }); // it('should close the select and focus the anchor when pressing "Shift" given that the last element is selected', async () => { // const output = renderBasicSelect(); // openByClick(output); // fireEvent.keyDown(getList(output), { key: 'Tab' }); // fireEvent.keyDown(getList(output), { key: 'Tab' }); // fireEvent.keyDown(getList(output), { key: 'Tab' }); // expect(getList(output)).not.toBeInTheDocument(); // expect(getAnchor(output)).toHaveFocus(); // }); it('should focus the element most closely matching typed keyboard input', () => { const output = renderBasicSelect(); openByClick(output); const list = getList(output); fireEvent.keyDown(list, { key: 't' }); const { getByText } = within(list); expect(getByText('two')).toHaveFocus(); }); it('should clear the current typed input after a given amount of ms and match the new input after the delay', async () => { const output = render( <SelectTwo clearSearchAfter={800} data-testid="dropdown-button"> <Option title="one" value="one" /> <Option title="two" value="two" /> <Option title="three" value="three" /> </SelectTwo> ); openByClick(output); const list = getList(output); fireEvent.keyDown(list, { key: 't' }); const { getByText } = within(list); expect(getByText('two')).toHaveFocus(); await new Promise((resolve) => setTimeout(resolve, 1000)); fireEvent.keyDown(list, { key: 'o' }); expect(getByText('one')).toHaveFocus(); }); it('continues the typed input from the last keystroke if the delay is small enough', () => { const output = renderBasicSelect(); openByClick(output); const list = getList(output); fireEvent.keyDown(list, { key: 't' }); const { getByText } = within(list); expect(getByText('two')).toHaveFocus(); fireEvent.keyDown(list, { key: 'h' }); expect(getByText('three')).toHaveFocus(); }); it('supports the search feature even with complex values given that "getSearchableValue" is supplied', () => { type V = { label: string; amount: number }; const getSearchableValue = ({ label }: V) => label; const output = render( <SelectTwo getSearchableValue={getSearchableValue} data-testid="dropdown-button"> <Option title="one" value={{ label: 'one' }} /> <Option title="two" value={{ label: 'two' }} /> <Option title="three" value={{ label: 'three' }} /> </SelectTwo> ); openByClick(output); const list = getList(output); fireEvent.keyDown(list, { key: 't' }); fireEvent.keyDown(list, { key: 'w' }); const { getByText } = output; expect(getByText('two')).toHaveFocus(); }); it('supports multiple selection mode', () => { const onChangeSpy = jest.fn(); const output = render( <SelectTwo data-testid="dropdown-button" multiple value={['one', 'two']} onChange={onChangeSpy}> <Option title="one" value="one" /> <Option title="two" value="two" /> <Option title="three" value="three" /> </SelectTwo> ); openByClick(output); expect(output.getByText('one')).toHaveClass('dropdown-item--is-selected'); expect(output.getByText('two')).toHaveClass('dropdown-item--is-selected'); expect(output.getByText('three')).not.toHaveClass('dropdown-item--is-selected'); fireEvent.click(output.getByText('three')); expect(onChangeSpy).toBeCalledWith({ selectedIndex: 2, value: ['one', 'two', 'three'] }); }); it('supports multiple selection mode with complex values', () => { const onChangeSpy = jest.fn(); const options = [ { label: 'one', key: 1 }, { label: 'two', key: 2 }, { label: 'three', key: 3 }, ]; const output = render( <SelectTwo data-testid="dropdown-button" multiple value={[options[0]]} onChange={onChangeSpy}> {options.map((option) => ( <Option title={option.label} value={option} key={option.key} /> ))} </SelectTwo> ); openByClick(output); expect(output.getByText('one', { selector: 'button' })).toHaveClass('dropdown-item--is-selected'); expect(output.getByText('two', { selector: 'button' })).not.toHaveClass('dropdown-item--is-selected'); expect(output.getByText('three', { selector: 'button' })).not.toHaveClass('dropdown-item--is-selected'); fireEvent.click(output.getByText('three')); expect(onChangeSpy).toBeCalledWith({ selectedIndex: 2, value: [options[0], options[2]] }); }); });
5,650
0
petrpan-code/ProtonMail/WebClients/packages/components/components
petrpan-code/ProtonMail/WebClients/packages/components/components/text/Mark.test.tsx
import { render } from '@testing-library/react'; import Mark from './Mark'; describe('Mark component', () => { const input = `Eh, toi, l'ours mal léché`; it('should highlight several matches', () => { const result = render(<Mark value="e">{input}</Mark>); const container = result.container; const nodes = container.querySelectorAll('mark'); expect(nodes.length).toBe(3); }); it('should highlight accent and capitalized matches', () => { const result = render(<Mark value="e">{input}</Mark>); const container = result.container; const nodes = container.querySelectorAll('mark'); expect(nodes[0].textContent).toBe('E'); expect(nodes[1].textContent).toBe('é'); expect(nodes[2].textContent).toBe('é'); }); it('should highlight print result properly', () => { const result = render(<Mark value="e">{input}</Mark>); const container = result.container; expect(container.innerHTML).toBe( `<mark class="is-light">E</mark><span>h, toi, l'ours mal l</span><mark class="is-light">é</mark><span>ch</span><mark class="is-light">é</mark>` ); }); it('should return original children if no match', () => { const { container } = render(<Mark value="orage">{input}</Mark>); expect(container.innerHTML).toBe(input); }); it('should return original children if value empty', () => { const { container } = render(<Mark value="">{input}</Mark>); expect(container.innerHTML).toBe(input); }); it('should return original children if children not a string', () => { const { container } = render( <Mark value="orage"> <input /> </Mark> ); expect(container.innerHTML).toBe('<input>'); }); it('should preserve spacing between highlighted matches', () => { const text = 'Créer un nouveau dossier'; const { container } = render(<Mark value="n">{text}</Mark>); expect(container.innerHTML).toBe( `<span>Créer u</span><mark class="is-light">n</mark><span> </span><mark class="is-light">n</mark><span>ouveau dossier</span>` ); }); });