level_0
int64
0
10k
index
int64
0
0
repo_id
stringlengths
22
152
file_path
stringlengths
41
203
content
stringlengths
11
11.5M
4,484
0
petrpan-code/mattermost/mattermost/webapp/channels/src
petrpan-code/mattermost/mattermost/webapp/channels/src/utils/limits_test.tsx
// Copyright (c) 2015-present Mattermost, Inc. All Rights Reserved. // See LICENSE.txt for license information. import type {Limits, CloudUsage} from '@mattermost/types/cloud'; interface LimitsRedux { limitsLoaded: boolean; limits: Limits; } export function makeEmptyLimits(): LimitsRedux { return { limitsLoaded: true, limits: {}, }; } export function makeEmptyUsage(): CloudUsage { return { files: { totalStorage: 0, totalStorageLoaded: true, }, messages: { history: 0, historyLoaded: true, }, teams: { active: 0, cloudArchived: 0, teamsLoaded: true, }, }; }
4,485
0
petrpan-code/mattermost/mattermost/webapp/channels/src
petrpan-code/mattermost/mattermost/webapp/channels/src/utils/message_html_to_component.test.tsx
// Copyright (c) 2015-present Mattermost, Inc. All Rights Reserved. // See LICENSE.txt for license information. import {shallow} from 'enzyme'; import AtMention from 'components/at_mention'; import MarkdownImage from 'components/markdown_image'; import Constants from 'utils/constants'; import EmojiMap from 'utils/emoji_map'; import messageHtmlToComponent from 'utils/message_html_to_component'; import * as TextFormatting from 'utils/text_formatting'; const emptyEmojiMap = new EmojiMap(new Map()); describe('messageHtmlToComponent', () => { test('plain text', () => { const input = 'Hello, world!'; const html = TextFormatting.formatText(input, {}, emptyEmojiMap); expect(messageHtmlToComponent(html)).toMatchSnapshot(); }); test('latex', () => { const input = `This is some latex! \`\`\`latex x^2 + y^2 = z^2 \`\`\` \`\`\`latex F_m - 2 = F_0 F_1 \\dots F_{m-1} \`\`\` That was some latex!`; const html = TextFormatting.formatText(input, {}, emptyEmojiMap); expect(messageHtmlToComponent(html)).toMatchSnapshot(); }); test('typescript', () => { const input = `\`\`\`typescript const myFunction = () => { console.log('This is a meaningful function'); }; \`\`\` `; const html = TextFormatting.formatText(input, {}, emptyEmojiMap); expect(messageHtmlToComponent(html, {postId: 'randompostid'})).toMatchSnapshot(); }); test('html', () => { const input = `\`\`\`html <div>This is a html div</div> \`\`\` `; const html = TextFormatting.formatText(input, {}, emptyEmojiMap); expect(messageHtmlToComponent(html, {postId: 'randompostid'})).toMatchSnapshot(); }); test('link without enabled tooltip plugins', () => { const input = 'lorem ipsum www.dolor.com sit amet'; const html = TextFormatting.formatText(input, {}, emptyEmojiMap); expect(messageHtmlToComponent(html)).toMatchSnapshot(); }); test('link with enabled a tooltip plugin', () => { const input = 'lorem ipsum www.dolor.com sit amet'; const html = TextFormatting.formatText(input, {}, emptyEmojiMap); expect(messageHtmlToComponent(html, {hasPluginTooltips: true})).toMatchSnapshot(); }); test('Inline markdown image', () => { const options = {markdown: true}; const html = TextFormatting.formatText('![Mattermost](/images/icon.png) and a [link](link)', options, emptyEmojiMap); const component = messageHtmlToComponent(html, { hasPluginTooltips: false, postId: 'post_id', postType: Constants.PostTypes.HEADER_CHANGE, }); expect(component).toMatchSnapshot(); expect(shallow(component).find(MarkdownImage).prop('imageIsLink')).toBe(false); }); test('Inline markdown image where image is link', () => { const options = {markdown: true}; const html = TextFormatting.formatText('[![Mattermost](images/icon.png)](images/icon.png)', options, emptyEmojiMap); const component = messageHtmlToComponent(html, { hasPluginTooltips: false, postId: 'post_id', postType: Constants.PostTypes.HEADER_CHANGE, }); expect(component).toMatchSnapshot(); expect(shallow(component).find(MarkdownImage).prop('imageIsLink')).toBe(true); }); test('At mention', () => { const options = {mentionHighlight: true, atMentions: true, mentionKeys: [{key: '@joram'}]}; let html = TextFormatting.formatText('@joram', options, emptyEmojiMap); let component = messageHtmlToComponent(html, {mentionHighlight: true}); expect(component).toMatchSnapshot(); expect(shallow(component).find(AtMention).prop('disableHighlight')).toBe(false); options.mentionHighlight = false; html = TextFormatting.formatText('@joram', options, emptyEmojiMap); component = messageHtmlToComponent(html, {mentionHighlight: false}); expect(component).toMatchSnapshot(); expect(shallow(component).find(AtMention).prop('disableHighlight')).toBe(true); }); test('At mention with group highlight disabled', () => { const options: TextFormatting.TextFormattingOptions = {mentionHighlight: true, atMentions: true, mentionKeys: [{key: '@joram'}]}; let html = TextFormatting.formatText('@developers', options, emptyEmojiMap); let component = messageHtmlToComponent(html, {disableGroupHighlight: false}); expect(component).toMatchSnapshot(); expect(shallow(component).find(AtMention).prop('disableGroupHighlight')).toBe(false); options.disableGroupHighlight = true; html = TextFormatting.formatText('@developers', options, emptyEmojiMap); component = messageHtmlToComponent(html, {disableGroupHighlight: true}); expect(component).toMatchSnapshot(); expect(shallow(component).find(AtMention).prop('disableGroupHighlight')).toBe(true); }); test('typescript', () => { const input = `Text before typescript codeblock \`\`\`typescript const myFunction = () => { console.log('This is a test function'); }; \`\`\` text after typescript block`; const html = TextFormatting.formatText(input, {}, emptyEmojiMap); expect(messageHtmlToComponent(html)).toMatchSnapshot(); }); });
4,488
0
petrpan-code/mattermost/mattermost/webapp/channels/src
petrpan-code/mattermost/mattermost/webapp/channels/src/utils/notifications.test.ts
// Copyright (c) 2015-present Mattermost, Inc. All Rights Reserved. // See LICENSE.txt for license information. /* eslint-disable global-require */ // to enable being a typescript file export const a = ''; import type {showNotification} from './notifications'; declare global { interface Window { Notification: any; } } describe('Notifications.showNotification', () => { let Notifications: {showNotification: typeof showNotification}; beforeEach(() => { jest.resetModules(); Notifications = require('utils/notifications'); }); it('should throw an exception if Notification is not defined on window', async () => { await expect(Notifications.showNotification()).rejects.toThrow('Notification not supported'); }); it('should throw an exception if Notification.requestPermission is not defined', async () => { window.Notification = {}; await expect(Notifications.showNotification()).rejects.toThrow('Notification.requestPermission not supported'); }); it('should throw an exception if Notification.requestPermission is not a function', async () => { window.Notification = { requestPermission: true, }; await expect(Notifications.showNotification()).rejects.toThrow('Notification.requestPermission not supported'); }); it('should request permissions, promise style, if not previously requested, do nothing', async () => { window.Notification = { requestPermission: () => Promise.resolve('denied'), permission: 'denied', }; await expect(Notifications.showNotification()).resolves.toBeTruthy(); }); it('should request permissions, callback style, if not previously requested, do nothing', async () => { window.Notification = { requestPermission: (callback: NotificationPermissionCallback) => { if (callback) { callback('denied'); } }, permission: 'denied', }; await expect(Notifications.showNotification()).resolves.toBeTruthy(); }); it('should request permissions, promise style, if not previously requested, handling success', async () => { window.Notification = jest.fn(); window.Notification.requestPermission = () => Promise.resolve('granted'); window.Notification.permission = 'denied'; const n = {}; window.Notification.mockReturnValueOnce(n); await expect(Notifications.showNotification({ body: 'body', requireInteraction: true, silent: false, title: '', })).resolves.toBeTruthy(); await expect(window.Notification.mock.calls.length).toBe(1); const call = window.Notification.mock.calls[0]; expect(call[1]).toEqual({ body: 'body', tag: 'body', icon: {}, requireInteraction: true, silent: false, }); }); it('should request permissions, callback style, if not previously requested, handling success', async () => { window.Notification = jest.fn(); window.Notification.requestPermission = (callback: NotificationPermissionCallback) => { if (callback) { callback('granted'); } }; window.Notification.permission = 'denied'; const n = {}; window.Notification.mockReturnValueOnce(n); await expect(Notifications.showNotification({ body: 'body', requireInteraction: true, silent: false, title: '', })).resolves.toBeTruthy(); await expect(window.Notification.mock.calls.length).toBe(1); const call = window.Notification.mock.calls[0]; expect(call[1]).toEqual({ body: 'body', tag: 'body', icon: {}, requireInteraction: true, silent: false, }); }); it('should do nothing if permissions previously requested but not granted', async () => { window.Notification = { requestPermission: () => Promise.resolve('denied'), permission: 'denied', }; // Call one to deny and mark as already requested, do nothing, throw nothing await expect(Notifications.showNotification()).resolves.toBeTruthy(); // Try again await expect(Notifications.showNotification()).resolves.toBeTruthy(); }); });
4,492
0
petrpan-code/mattermost/mattermost/webapp/channels/src
petrpan-code/mattermost/mattermost/webapp/channels/src/utils/paste.test.tsx
// Copyright (c) 2015-present Mattermost, Inc. All Rights Reserved. // See LICENSE.txt for license information. import {Locations} from './constants'; import {execCommandInsertText} from './exec_commands'; import { parseHtmlTable, getHtmlTable, formatMarkdownMessage, formatGithubCodePaste, formatMarkdownLinkMessage, isTextUrl, hasPlainText, createFileFromClipboardDataItem, pasteHandler, } from './paste'; const validClipboardData: any = { items: [1], types: ['text/html'], getData: () => { return '<table><tr><td>test</td><td>test</td></tr><tr><td>test</td><td>test</td></tr></table>'; }, }; const validTable: any = parseHtmlTable(validClipboardData.getData()); describe('getHtmlTable', () => { test('returns false without html in the clipboard', () => { const badClipboardData: any = { items: [1], types: ['text/plain'], }; expect(getHtmlTable(badClipboardData)).toBe(null); }); test('returns false without table in the clipboard', () => { const badClipboardData: any = { items: [1], types: ['text/html'], getData: () => '<p>There is no table here</p>', }; expect(getHtmlTable(badClipboardData)).toBe(null); }); test('returns table from valid clipboard data', () => { expect(getHtmlTable(validClipboardData)).toEqual(validTable); }); }); describe('formatMarkdownMessage', () => { const markdownTable = '| test | test |\n| --- | --- |\n| test | test |'; test('returns a markdown table when valid html table provided', () => { expect(formatMarkdownMessage(validClipboardData).formattedMessage).toBe(`${markdownTable}\n`); }); test('returns a markdown table when valid html table with headers provided', () => { const tableHeadersClipboardData: any = { items: [1], types: ['text/html'], getData: () => { return '<table><tr><th>test</th><th>test</th></tr><tr><td>test</td><td>test</td></tr></table>'; }, }; expect(formatMarkdownMessage(tableHeadersClipboardData).formattedMessage).toBe(markdownTable); }); test('removes style contents and additional whitespace around tables', () => { const styleClipboardData: any = { items: [1], types: ['text/html'], getData: () => { return '<style><!--td {border: 1px solid #cccccc;}--></style>\n<table><tr><th>test</th><th>test</th></tr><tr><td>test</td><td>test</td></tr></table>\n'; }, }; expect(formatMarkdownMessage(styleClipboardData).formattedMessage).toBe(markdownTable); }); test('returns a markdown table under a message when one is provided', () => { const testMessage = 'test message'; expect(formatMarkdownMessage(validClipboardData, testMessage).formattedMessage).toBe(`${testMessage}\n\n${markdownTable}\n`); }); test('returns a markdown formatted link when valid hyperlink provided', () => { const linkClipboardData: any = { items: [1], types: ['text/html'], getData: () => { return '<a href="https://test.domain">link text</a>'; }, }; const markdownLink = '[link text](https://test.domain)'; expect(formatMarkdownMessage(linkClipboardData).formattedMessage).toBe(markdownLink); }); }); describe('formatGithubCodePaste', () => { const clipboardData: any = { items: [], types: ['text/plain', 'text/html'], getData: (type: any) => { if (type === 'text/plain') { return '// a javascript codeblock example\nif (1 > 0) {\n return \'condition is true\';\n}'; } return '<table class="highlight tab-size js-file-line-container" data-tab-size="8"><tbody><tr><td id="LC1" class="blob-code blob-code-inner js-file-line"><span class="pl-c"><span class="pl-c">//</span> a javascript codeblock example</span></td></tr><tr><td id="L2" class="blob-num js-line-number" data-line-number="2">&nbsp;</td><td id="LC2" class="blob-code blob-code-inner js-file-line"><span class="pl-k">if</span> (<span class="pl-c1">1</span> <span class="pl-k">&gt;</span> <span class="pl-c1">0</span>) {</td></tr><tr><td id="L3" class="blob-num js-line-number" data-line-number="3">&nbsp;</td><td id="LC3" class="blob-code blob-code-inner js-file-line"><span class="pl-en">console</span>.<span class="pl-c1">log</span>(<span class="pl-s"><span class="pl-pds">\'</span>condition is true<span class="pl-pds">\'</span></span>);</td></tr><tr><td id="L4" class="blob-num js-line-number" data-line-number="4">&nbsp;</td><td id="LC4" class="blob-code blob-code-inner js-file-line">}</td></tr></tbody></table>'; }, }; test('Formatted message for empty message', () => { const message = "```\n// a javascript codeblock example\nif (1 > 0) {\n return 'condition is true';\n}\n```"; const codeBlock = "```\n// a javascript codeblock example\nif (1 > 0) {\n return 'condition is true';\n}\n```"; const {formattedMessage, formattedCodeBlock} = formatGithubCodePaste({selectionStart: 0, selectionEnd: 0, message: '', clipboardData}); expect(message).toBe(formattedMessage); expect(codeBlock).toBe(formattedCodeBlock); }); test('Formatted message with a draft and cursor at end', () => { const message = "test\n```\n// a javascript codeblock example\nif (1 > 0) {\n return 'condition is true';\n}\n```"; const codeBlock = "\n```\n// a javascript codeblock example\nif (1 > 0) {\n return 'condition is true';\n}\n```"; const {formattedMessage, formattedCodeBlock} = formatGithubCodePaste({selectionStart: 4, selectionEnd: 4, message: 'test', clipboardData}); expect(message).toBe(formattedMessage); expect(codeBlock).toBe(formattedCodeBlock); }); test('Formatted message with a draft and cursor at start', () => { const message = "```\n// a javascript codeblock example\nif (1 > 0) {\n return 'condition is true';\n}\n```\ntest"; const codeBlock = "```\n// a javascript codeblock example\nif (1 > 0) {\n return 'condition is true';\n}\n```\n"; const {formattedMessage, formattedCodeBlock} = formatGithubCodePaste({selectionStart: 0, selectionEnd: 0, message: 'test', clipboardData}); expect(message).toBe(formattedMessage); expect(codeBlock).toBe(formattedCodeBlock); }); test('Formatted message with a draft and cursor at middle', () => { const message = "te\n```\n// a javascript codeblock example\nif (1 > 0) {\n return 'condition is true';\n}\n```\nst"; const codeBlock = "\n```\n// a javascript codeblock example\nif (1 > 0) {\n return 'condition is true';\n}\n```\n"; const {formattedMessage, formattedCodeBlock} = formatGithubCodePaste({selectionStart: 2, selectionEnd: 2, message: 'test', clipboardData}); expect(message).toBe(formattedMessage); expect(codeBlock).toBe(formattedCodeBlock); }); test('Selected message in the middle is replaced with code', () => { const originalMessage = 'test replace message'; const codeBlock = "\n```\n// a javascript codeblock example\nif (1 > 0) {\n return 'condition is true';\n}\n```\n"; const updatedMessage = "test \n```\n// a javascript codeblock example\nif (1 > 0) {\n return 'condition is true';\n}\n```\n message"; const {formattedMessage, formattedCodeBlock} = formatGithubCodePaste({selectionStart: 5, selectionEnd: 12, message: originalMessage, clipboardData}); expect(updatedMessage).toBe(formattedMessage); expect(codeBlock).toBe(formattedCodeBlock); }); }); describe('formatMarkdownLinkMessage', () => { const clipboardData: any = { items: [], types: ['text/plain'], getData: () => { return 'https://example.com/'; }, }; test('Should return empty selection when no selection is made', () => { const message = ''; const formatttedMarkdownLinkMessage = formatMarkdownLinkMessage({selectionStart: 0, selectionEnd: 0, message, clipboardData}); expect(formatttedMarkdownLinkMessage).toEqual('[](https://example.com/)'); }); test('Should return correct selection when selection is made', () => { const message = 'test'; const formatttedMarkdownLinkMessage = formatMarkdownLinkMessage({selectionStart: 0, selectionEnd: 4, message, clipboardData}); expect(formatttedMarkdownLinkMessage).toEqual('[test](https://example.com/)'); }); test('Should not add link when pasting inside of a formatted markdown link', () => { const message = '[test](url)'; const formatttedMarkdownLinkMessage = formatMarkdownLinkMessage({selectionStart: 7, selectionEnd: 10, message, clipboardData}); expect(formatttedMarkdownLinkMessage).toEqual('https://example.com/'); }); test('Should add link when pasting inside of an improper formatted markdown link', () => { const improperFormattedLinkMessages = [ {message: '[test](url)', selection: 'ur', expected: '[ur](https://example.com/)'}, {message: '[test](url)', selection: '(url', expected: '[(url](https://example.com/)'}, {message: '[test](url)', selection: 'url)', expected: '[url)](https://example.com/)'}, {message: '[test](url)', selection: '(url)', expected: '[(url)](https://example.com/)'}, {message: '[test](url)', selection: '[test](url', expected: '[[test](url](https://example.com/)'}, {message: '[test](url)', selection: 'test](url', expected: '[test](url](https://example.com/)'}, {message: '[test](url)', selection: 'test](url)', expected: '[test](url)](https://example.com/)'}, {message: '[test](url)', selection: '[test](url)', expected: '[[test](url)](https://example.com/)'}, ]; for (const {message, selection, expected} of improperFormattedLinkMessages) { const selectionStart = message.indexOf(selection); const selectionEnd = selectionStart + selection.length; const formatttedMarkdownLinkMessage = formatMarkdownLinkMessage({selectionStart, selectionEnd, message, clipboardData}); expect(formatttedMarkdownLinkMessage).toEqual(expected); } }); }); describe('isTextUrl', () => { test('Should return true when url is valid', () => { const clipboardData: any = { ...validClipboardData, getData: () => { return 'https://example.com/'; }, }; expect(isTextUrl(clipboardData)).toBe(true); }); test('Should return false when url is invalid', () => { const clipboardData: any = { ...validClipboardData, getData: () => { return 'not a url'; }, }; expect(isTextUrl(clipboardData)).toBe(false); }); }); jest.mock('utils/exec_commands', () => ({ execCommandInsertText: jest.fn(), })); describe('pasteHandler', () => { const testCases = [ { testName: 'should be able to format a pasted markdown table', clipboardData: { items: [1], types: ['text/html'], getData: () => { return '<table><tr><th>test</th><th>test</th></tr><tr><td>test</td><td>test</td></tr></table>'; }, }, expectedMarkdown: '| test | test |\n| --- | --- |\n| test | test |', }, { testName: 'should be able to format a pasted markdown table without headers', clipboardData: { items: [1], types: ['text/html'], getData: () => { return '<table><tr><td>test</td><td>test</td></tr><tr><td>test</td><td>test</td></tr></table>'; }, }, expectedMarkdown: '| test | test |\n| --- | --- |\n| test | test |\n', }, { testName: 'should be able to format a pasted hyperlink', clipboardData: { items: [1], types: ['text/html'], getData: () => { return '<a href="https://test.domain">link text</a>'; }, }, expectedMarkdown: '[link text](https://test.domain)', }, { testName: 'should be able to format a github codeblock (pasted as a table)', clipboardData: { items: [1], types: ['text/plain', 'text/html'], getData: (type: string) => { if (type === 'text/plain') { return '// a javascript codeblock example\nif (1 > 0) {\n return \'condition is true\';\n}'; } return '<table class="highlight tab-size js-file-line-container" data-tab-size="8"><tbody><tr><td id="LC1" class="blob-code blob-code-inner js-file-line"><span class="pl-c"><span class="pl-c">//</span> a javascript codeblock example</span></td></tr><tr><td id="L2" class="blob-num js-line-number" data-line-number="2">&nbsp;</td><td id="LC2" class="blob-code blob-code-inner js-file-line"><span class="pl-k">if</span> (<span class="pl-c1">1</span> <span class="pl-k">&gt;</span> <span class="pl-c1">0</span>) {</td></tr><tr><td id="L3" class="blob-num js-line-number" data-line-number="3">&nbsp;</td><td id="LC3" class="blob-code blob-code-inner js-file-line"><span class="pl-en">console</span>.<span class="pl-c1">log</span>(<span class="pl-s"><span class="pl-pds">\'</span>condition is true<span class="pl-pds">\'</span></span>);</td></tr><tr><td id="L4" class="blob-num js-line-number" data-line-number="4">&nbsp;</td><td id="LC4" class="blob-code blob-code-inner js-file-line">}</td></tr></tbody></table>'; }, }, expectedMarkdown: "```\n// a javascript codeblock example\nif (1 > 0) {\n return 'condition is true';\n}\n```", }, ]; for (const tc of testCases) { it(tc.testName, () => { const location = Locations.RHS_COMMENT; const event: any = { target: { id: 'reply_textbox', }, preventDefault: jest.fn(), clipboardData: tc.clipboardData, }; pasteHandler(event, location, '', false, 0); expect(execCommandInsertText).toHaveBeenCalledWith(tc.expectedMarkdown); }); } }); describe('hasPlainText', () => { test('Should return true when clipboard data has plain text', () => { const clipboardData = { ...validClipboardData, types: ['text/plain'], getData: () => { return 'plain text'; }, }; expect(hasPlainText(clipboardData)).toBe(true); }); test('Should return true when clipboard data has plain text along with other types', () => { const clipboardData = { ...validClipboardData, types: ['text/html', 'text/plain'], getData: () => { return 'plain text'; }, }; expect(hasPlainText(clipboardData)).toBe(true); }); test('Should return false when clipboard data has empty text', () => { const clipboardData = { ...validClipboardData, types: ['text/html', 'text/plain'], getData: () => { return ''; }, }; expect(hasPlainText(clipboardData)).toBe(false); }); test('Should return false when clipboard data doesnt not have plain text type', () => { const clipboardData = { ...validClipboardData, types: ['text/html'], getData: () => { return 'plain text without type'; }, }; expect(hasPlainText(clipboardData)).toBe(false); }); }); describe('createFileFromClipboardDataItem', () => { test('should return a file from a clipboard item', () => { const item = { getAsFile: jest.fn(() => ({ name: 'test1.png', type: 'image/png', })), type: 'image/png', } as unknown as DataTransferItem; const file = createFileFromClipboardDataItem(item, '') as File; expect(file).toBeInstanceOf(File); expect(file.name).toEqual('test1.png'); expect(file.type).toEqual('image/png'); }); test('should return null if getAsFile is not a file', () => { const item = { getAsFile: jest.fn(() => null), } as unknown as DataTransferItem; const file = createFileFromClipboardDataItem(item, ''); expect(file).toBeNull(); }); test('Should return correct file name when file name is not available', () => { const item = { getAsFile: jest.fn(() => ({ type: 'image/jpeg', })), type: 'image/jpeg', } as unknown as DataTransferItem; const now = new Date(); const file = createFileFromClipboardDataItem(item, 'pasted') as File; expect(file).toBeInstanceOf(File); expect(file.name).toBe(`pasted${now.getFullYear()}-${now.getMonth() + 1}-${now.getDate()} ${now.getHours().toString().padStart(2, '0')}-${now.getMinutes().toString().padStart(2, '0')}.jpeg`); expect(file.type).toBe('image/jpeg'); }); test('Should return correct file extension when file name contains extension', () => { const item = { getAsFile: jest.fn(() => ({ name: 'test.jpeg', })), type: 'image/jpeg', } as unknown as DataTransferItem; const file = createFileFromClipboardDataItem(item, 'pasted') as File; expect(file.name).toContain('.jpeg'); }); test('Should return correct file extension when file name doesnt contains extension', () => { const item = { getAsFile: jest.fn(() => ({ type: 'image/JPEG', })), type: 'image/jpeg', } as unknown as DataTransferItem; const file = createFileFromClipboardDataItem(item, 'pasted') as File; expect(file.name).toContain('.jpeg'); }); });
4,495
0
petrpan-code/mattermost/mattermost/webapp/channels/src
petrpan-code/mattermost/mattermost/webapp/channels/src/utils/policy_roles_adapter.test.ts
// Copyright (c) 2015-present Mattermost, Inc. All Rights Reserved. // See LICENSE.txt for license information. import type {Role} from '@mattermost/types/roles'; import {Permissions} from 'mattermost-redux/constants/index'; import {rolesFromMapping, mappingValueFromRoles} from 'utils/policy_roles_adapter'; describe('PolicyRolesAdapter', () => { let roles: Record<string, any> = {}; let policies: Record<string, any> = {}; beforeEach(() => { roles = { channel_user: { name: 'channel_user', permissions: [ Permissions.EDIT_POST, Permissions.DELETE_POST, Permissions.MANAGE_PRIVATE_CHANNEL_MEMBERS, ], }, team_user: { name: 'team_user', permissions: [ Permissions.INVITE_USER, Permissions.ADD_USER_TO_TEAM, Permissions.CREATE_PUBLIC_CHANNEL, Permissions.CREATE_PRIVATE_CHANNEL, Permissions.MANAGE_PUBLIC_CHANNEL_PROPERTIES, Permissions.DELETE_PUBLIC_CHANNEL, Permissions.MANAGE_PRIVATE_CHANNEL_PROPERTIES, Permissions.DELETE_PRIVATE_CHANNEL, ], }, channel_admin: { name: 'channel_admin', permissions: [ Permissions.MANAGE_CHANNEL_ROLES, ], }, team_admin: { name: 'team_admin', permissions: [ Permissions.DELETE_POST, Permissions.DELETE_OTHERS_POSTS, ], }, system_admin: { name: 'system_admin', permissions: [ Permissions.DELETE_PUBLIC_CHANNEL, Permissions.INVITE_USER, Permissions.ADD_USER_TO_TEAM, Permissions.DELETE_POST, Permissions.DELETE_OTHERS_POSTS, Permissions.EDIT_POST, ], }, system_user: { name: 'system_user', permissions: [ Permissions.CREATE_TEAM, ], }, }; const teamPolicies = { restrictTeamInvite: 'all', }; policies = { ...teamPolicies, }; }); afterEach(() => { roles = {}; }); describe('PolicyRolesAdapter.rolesFromMapping', () => { test('unknown value throws an exception', () => { policies.enableTeamCreation = 'sometimesmaybe'; expect(() => { rolesFromMapping(policies, roles); }).toThrowError(/not present in mapping/i); }); // // That way you can pass in the whole state if you want. test('ignores unknown keys', () => { policies.blah = 'all'; expect(() => { rolesFromMapping(policies, roles); }).not.toThrowError(); }); test('mock data setup', () => { const updatedRoles = rolesFromMapping(policies, roles); expect(Object.values(updatedRoles).length).toEqual(0); }); describe('enableTeamCreation', () => { test('true', () => { roles.system_user.permissions = []; const updatedRoles = rolesFromMapping({enableTeamCreation: 'true'}, roles); expect(Object.values(updatedRoles).length).toEqual(1); expect(updatedRoles.system_user.permissions).toEqual(expect.arrayContaining([Permissions.CREATE_TEAM])); }); test('false', () => { roles.system_user.permissions = [Permissions.CREATE_TEAM]; const updatedRoles = rolesFromMapping({enableTeamCreation: 'false'}, roles); expect(Object.values(updatedRoles).length).toEqual(1); expect(updatedRoles.system_user.permissions).not.toEqual(expect.arrayContaining([Permissions.CREATE_TEAM])); }); }); test('it only returns the updated roles', () => { const updatedRoles = rolesFromMapping(policies, roles); expect(Object.keys(updatedRoles).length).toEqual(0); }); }); describe('PolicyRolesAdapter.mappingValueFromRoles', () => { describe('enableTeamCreation', () => { test('returns the expected policy value for a enableTeamCreation policy', () => { addPermissionToRole(Permissions.CREATE_TEAM, roles.system_user); let value = mappingValueFromRoles('enableTeamCreation', roles); expect(value).toEqual('true'); removePermissionFromRole(Permissions.CREATE_TEAM, roles.system_user); value = mappingValueFromRoles('enableTeamCreation', roles); expect(value).toEqual('false'); }); }); }); }); function addPermissionToRole(permission: string, role: Role) { if (!role.permissions.includes(permission)) { role.permissions.push(permission); } } function removePermissionFromRole(permission: string, role: Role) { const permissionIndex = role.permissions.indexOf(permission); if (permissionIndex !== -1) { role.permissions.splice(permissionIndex, 1); } }
4,497
0
petrpan-code/mattermost/mattermost/webapp/channels/src
petrpan-code/mattermost/mattermost/webapp/channels/src/utils/position_utils.test.tsx
// Copyright (c) 2015-present Mattermost, Inc. All Rights Reserved. // See LICENSE.txt for license information. import {popOverOverlayPosition, approxGroupPopOverHeight} from 'utils/position_utils'; test('Should return placement position for overlay based on bounds, space required and innerHeight', () => { const targetBounds = { top: 400, bottom: 500, }; expect(popOverOverlayPosition(targetBounds as DOMRect, 1000, 300)).toEqual('top'); expect(popOverOverlayPosition(targetBounds as DOMRect, 1000, 500, 300)).toEqual('bottom'); expect(popOverOverlayPosition(targetBounds as DOMRect, 1000, 450)).toEqual('bottom'); expect(popOverOverlayPosition(targetBounds as DOMRect, 1000, 600)).toEqual('left'); }); test('Should return the correct height for the group list overlay bounded by viewport height or max list height', () => { // constants. should not need to change const viewportScaleFactor = 0.4; const headerHeight = 130; const maxListHeight = 800; // array of [listHeight, viewPortHeight, expected] // tests for cases when // group list fits // group list is too tall for viewport // group list reaches max list height const testCases = [[100, 1000, 230], [500, 500, 330], [800, 2000, maxListHeight]]; for (const [listHeight, viewPortHeight, expected] of testCases) { expect( approxGroupPopOverHeight( listHeight, viewPortHeight, viewportScaleFactor, headerHeight, maxListHeight, )).toBe(expected); } });
4,499
0
petrpan-code/mattermost/mattermost/webapp/channels/src
petrpan-code/mattermost/mattermost/webapp/channels/src/utils/post_utils.test.tsx
// Copyright (c) 2015-present Mattermost, Inc. All Rights Reserved. // See LICENSE.txt for license information. import {createIntl} from 'react-intl'; import {Preferences} from 'mattermost-redux/constants'; import enMessages from 'i18n/en.json'; import {PostListRowListIds, Constants} from 'utils/constants'; import EmojiMap from 'utils/emoji_map'; import * as PostUtils from 'utils/post_utils'; import {TestHelper} from 'utils/test_helper'; import type {GlobalState} from 'types/store'; describe('PostUtils.containsAtChannel', () => { test('should return correct @all (same for @channel)', () => { for (const data of [ { text: '', result: false, }, { text: 'all', result: false, }, { text: '@allison', result: false, }, { text: '@ALLISON', result: false, }, { text: '@all123', result: false, }, { text: '123@all', result: false, }, { text: 'hey@all', result: false, }, { text: '[email protected]', result: false, }, { text: '@all', result: true, }, { text: '@ALL', result: true, }, { text: '@all hey', result: true, }, { text: 'hey @all', result: true, }, { text: 'HEY @ALL', result: true, }, { text: 'hey @all!', result: true, }, { text: 'hey @all:+1:', result: true, }, { text: 'hey @ALL:+1:', result: true, }, { text: '`@all`', result: false, }, { text: '@someone `@all`', result: false, }, { text: '``@all``', result: false, }, { text: '```@all```', result: false, }, { text: '```\n@all\n```', result: false, }, { text: '```````\n@all\n```````', result: false, }, { text: '```code\n@all\n```', result: false, }, { text: '~~~@all~~~', result: true, }, { text: '~~~\n@all\n~~~', result: false, }, { text: ' /not_cmd @all', result: true, }, { text: '/cmd @all', result: false, }, { text: '/cmd @all test', result: false, }, { text: '/cmd test @all', result: false, }, { text: '@channel', result: true, }, { text: '@channel.', result: true, }, { text: '@channel/test', result: true, }, { text: 'test/@channel', result: true, }, { text: '@all/@channel', result: true, }, { text: '@cha*nnel*', result: false, }, { text: '@cha**nnel**', result: false, }, { text: '*@cha*nnel', result: false, }, { text: '[@chan](https://google.com)nel', result: false, }, { text: '@cha![](https://myimage)nnel', result: false, }, { text: '@here![](https://myimage)nnel', result: true, options: { checkAllMentions: true, }, }, { text: '@heree', result: false, options: { checkAllMentions: true, }, }, { text: '=@here=', result: true, options: { checkAllMentions: true, }, }, { text: '@HERE', result: true, options: { checkAllMentions: true, }, }, { text: '@here', result: false, options: { checkAllMentions: false, }, }, ]) { const containsAtChannel = PostUtils.containsAtChannel(data.text, data.options); expect(containsAtChannel).toEqual(data.result); } }); }); describe('PostUtils.specialMentionsInText', () => { test('should return correct mentions', () => { for (const data of [ { text: '', result: {all: false, channel: false, here: false}, }, { text: 'all', result: {all: false, channel: false, here: false}, }, { text: '@allison', result: {all: false, channel: false, here: false}, }, { text: '@ALLISON', result: {all: false, channel: false, here: false}, }, { text: '@all123', result: {all: false, channel: false, here: false}, }, { text: '123@all', result: {all: false, channel: false, here: false}, }, { text: 'hey@all', result: {all: false, channel: false, here: false}, }, { text: '[email protected]', result: {all: false, channel: false, here: false}, }, { text: '@all', result: {all: true, channel: false, here: false}, }, { text: '@ALL', result: {all: true, channel: false, here: false}, }, { text: '@all hey', result: {all: true, channel: false, here: false}, }, { text: 'hey @all', result: {all: true, channel: false, here: false}, }, { text: 'HEY @ALL', result: {all: true, channel: false, here: false}, }, { text: 'hey @all!', result: {all: true, channel: false, here: false}, }, { text: 'hey @all:+1:', result: {all: true, channel: false, here: false}, }, { text: 'hey @ALL:+1:', result: {all: true, channel: false, here: false}, }, { text: '`@all`', result: {all: false, channel: false, here: false}, }, { text: '@someone `@all`', result: {all: false, channel: false, here: false}, }, { text: '``@all``', result: {all: false, channel: false, here: false}, }, { text: '```@all```', result: {all: false, channel: false, here: false}, }, { text: '```\n@all\n```', result: {all: false, channel: false, here: false}, }, { text: '```````\n@all\n```````', result: {all: false, channel: false, here: false}, }, { text: '```code\n@all\n```', result: {all: false, channel: false, here: false}, }, { text: '~~~@all~~~', result: {all: true, channel: false, here: false}, }, { text: '~~~\n@all\n~~~', result: {all: false, channel: false, here: false}, }, { text: ' /not_cmd @all', result: {all: true, channel: false, here: false}, }, { text: '/cmd @all', result: {all: false, channel: false, here: false}, }, { text: '/cmd @all test', result: {all: false, channel: false, here: false}, }, { text: '/cmd test @all', result: {all: false, channel: false, here: false}, }, { text: '@channel', result: {all: false, channel: true, here: false}, }, { text: '@channel.', result: {all: false, channel: true, here: false}, }, { text: '@channel/test', result: {all: false, channel: true, here: false}, }, { text: 'test/@channel', result: {all: false, channel: true, here: false}, }, { text: '@all/@channel', result: {all: true, channel: true, here: false}, }, { text: '@cha*nnel*', result: {all: false, channel: false, here: false}, }, { text: '@cha**nnel**', result: {all: false, channel: false, here: false}, }, { text: '*@cha*nnel', result: {all: false, channel: false, here: false}, }, { text: '[@chan](https://google.com)nel', result: {all: false, channel: false, here: false}, }, { text: '@cha![](https://myimage)nnel', result: {all: false, channel: false, here: false}, }, { text: '@here![](https://myimage)nnel', result: {all: false, channel: false, here: true}, }, { text: '@heree', result: {all: false, channel: false, here: false}, }, { text: '=@here=', result: {all: false, channel: false, here: true}, }, { text: '@HERE', result: {all: false, channel: false, here: true}, }, { text: '@all @here', result: {all: true, channel: false, here: true}, }, { text: 'message @all message @here message @channel', result: {all: true, here: true, channel: true}, }, ]) { const mentions = PostUtils.specialMentionsInText(data.text); expect(mentions).toEqual(data.result); } }); }); describe('PostUtils.shouldFocusMainTextbox', () => { test('basic cases', () => { for (const data of [ { event: null, expected: false, }, { event: {}, expected: false, }, { event: {ctrlKey: true}, activeElement: {tagName: 'BODY'}, expected: false, }, { event: {metaKey: true}, activeElement: {tagName: 'BODY'}, expected: false, }, { event: {altKey: true}, activeElement: {tagName: 'BODY'}, expected: false, }, { event: {}, activeElement: {tagName: 'BODY'}, expected: false, }, { event: {key: 'a'}, activeElement: {tagName: 'BODY'}, expected: true, }, { event: {key: 'a'}, activeElement: {tagName: 'INPUT'}, expected: false, }, { event: {key: 'a'}, activeElement: {tagName: 'TEXTAREA'}, expected: false, }, { event: {key: '0'}, activeElement: {tagName: 'BODY'}, expected: true, }, { event: {key: '!'}, activeElement: {tagName: 'BODY'}, expected: true, }, { event: {key: ' '}, activeElement: {tagName: 'BODY'}, expected: true, }, { event: {key: 'BACKSPACE'}, activeElement: {tagName: 'BODY'}, expected: false, }, ]) { const shouldFocus = PostUtils.shouldFocusMainTextbox(data.event as unknown as KeyboardEvent, data.activeElement as unknown as Element); expect(shouldFocus).toEqual(data.expected); } }); }); describe('PostUtils.postMessageOnKeyPress', () => { // null/empty cases const emptyCases = [{ name: 'null/empty: Test for null event', input: {event: null, message: 'message', sendMessageOnCtrlEnter: false, sendCodeBlockOnCtrlEnter: false}, expected: {allowSending: false}, }, { name: 'null/empty: Test for empty message', input: {event: {}, message: '', sendMessageOnCtrlEnter: false, sendCodeBlockOnCtrlEnter: false}, expected: {allowSending: false}, }, { name: 'null/empty: Test for shiftKey event', input: {event: {shiftKey: true}, message: 'message', sendMessageOnCtrlEnter: false, sendCodeBlockOnCtrlEnter: false}, expected: {allowSending: false}, }, { name: 'null/empty: Test for altKey event', input: {event: {altKey: true}, message: 'message', sendMessageOnCtrlEnter: false, sendCodeBlockOnCtrlEnter: false}, expected: {allowSending: false}, }]; for (const testCase of emptyCases) { it(testCase.name, () => { const output = PostUtils.postMessageOnKeyPress( testCase.input.event as any, testCase.input.message, testCase.input.sendMessageOnCtrlEnter, testCase.input.sendCodeBlockOnCtrlEnter, 0, 0, testCase.input.message.length, ); expect(output).toEqual(testCase.expected); }); } // no override case const noOverrideCases = [{ name: 'no override: Test no override setting', input: {event: {keyCode: 13}, message: 'message', sendMessageOnCtrlEnter: false, sendCodeBlockOnCtrlEnter: false}, expected: {allowSending: true}, }, { name: 'no override: empty message', input: {event: {keyCode: 13}, message: '', sendMessageOnCtrlEnter: false, sendCodeBlockOnCtrlEnter: false}, expected: {allowSending: true}, }, { name: 'no override: empty message on ctrl + enter', input: {event: {keyCode: 13}, message: '', sendMessageOnCtrlEnter: true, sendCodeBlockOnCtrlEnter: false}, expected: {allowSending: true}, }]; for (const testCase of noOverrideCases) { it(testCase.name, () => { const output = PostUtils.postMessageOnKeyPress( testCase.input.event as any, testCase.input.message, testCase.input.sendMessageOnCtrlEnter, testCase.input.sendCodeBlockOnCtrlEnter, 0, 0, testCase.input.message.length, ); expect(output).toEqual(testCase.expected); }); } // on sending of message on Ctrl + Enter const sendMessageOnCtrlEnterCases = [{ name: 'sendMessageOnCtrlEnter: Test for overriding sending of message on CTRL+ENTER, no ctrlKey|metaKey', input: {event: {keyCode: 13}, message: 'message', sendMessageOnCtrlEnter: true, sendCodeBlockOnCtrlEnter: false}, expected: {allowSending: false}, }, { name: 'sendMessageOnCtrlEnter: Test for overriding sending of message on CTRL+ENTER, no ctrlKey|metaKey, with opening backticks', input: {event: {keyCode: 13}, message: '```', sendMessageOnCtrlEnter: true, sendCodeBlockOnCtrlEnter: false}, expected: {allowSending: false}, }, { name: 'sendMessageOnCtrlEnter: Test for overriding sending of message on CTRL+ENTER, no ctrlKey|metaKey, with opening backticks', input: {event: {keyCode: 13}, message: '```\nfunc(){}', sendMessageOnCtrlEnter: true, sendCodeBlockOnCtrlEnter: false}, expected: {allowSending: false}, }, { name: 'sendMessageOnCtrlEnter: Test for overriding sending of message on CTRL+ENTER, no ctrlKey|metaKey, with opening backticks', input: {event: {keyCode: 13}, message: '```\nfunc(){}\n', sendMessageOnCtrlEnter: true, sendCodeBlockOnCtrlEnter: false}, expected: {allowSending: false}, }, { name: 'sendMessageOnCtrlEnter: Test for overriding sending of message on CTRL+ENTER, no ctrlKey|metaKey, with opening and closing backticks', input: {event: {keyCode: 13}, message: '```\nfunc(){}\n```', sendMessageOnCtrlEnter: true, sendCodeBlockOnCtrlEnter: false}, expected: {allowSending: false}, }, { name: 'sendMessageOnCtrlEnter: Test for overriding sending of message on CTRL+ENTER, with ctrlKey', input: {event: {keyCode: 13, ctrlKey: true}, message: 'message', sendMessageOnCtrlEnter: true, sendCodeBlockOnCtrlEnter: false}, expected: {allowSending: true}, }, { name: 'sendMessageOnCtrlEnter: Test for overriding sending of message on CTRL+ENTER, with metaKey', input: {event: {keyCode: 13, metaKey: true}, message: 'message', sendMessageOnCtrlEnter: true, sendCodeBlockOnCtrlEnter: false}, expected: {allowSending: true}, }, { name: 'sendMessageOnCtrlEnter: Test for overriding sending of message on CTRL+ENTER, with ctrlKey, with opening backticks', input: {event: {keyCode: 13, ctrlKey: true}, message: '```', sendMessageOnCtrlEnter: true, sendCodeBlockOnCtrlEnter: false}, expected: {allowSending: true}, }, { name: 'sendMessageOnCtrlEnter: Test for overriding sending of message on CTRL+ENTER, with ctrlKey, with opening backticks, with language set', input: {event: {keyCode: 13, ctrlKey: true}, message: '```javascript', sendMessageOnCtrlEnter: true, sendCodeBlockOnCtrlEnter: false}, expected: {allowSending: true}, }, { name: 'sendMessageOnCtrlEnter: Test for overriding sending of message on CTRL+ENTER, with ctrlKey, with opening backticks', input: {event: {keyCode: 13, ctrlKey: true}, message: '```\n', sendMessageOnCtrlEnter: true, sendCodeBlockOnCtrlEnter: false}, expected: {allowSending: true}, }, { name: 'sendMessageOnCtrlEnter: Test for overriding sending of message on CTRL+ENTER, with ctrlKey, with opening backticks', input: {event: {keyCode: 13, ctrlKey: true}, message: '```\nfunction(){}', sendMessageOnCtrlEnter: true, sendCodeBlockOnCtrlEnter: false}, expected: {allowSending: true, message: '```\nfunction(){}\n```', withClosedCodeBlock: true}, }, { name: 'sendMessageOnCtrlEnter: Test for overriding sending of message on CTRL+ENTER, with ctrlKey, with opening backticks, with line break on last line', input: {event: {keyCode: 13, ctrlKey: true}, message: '```\nfunction(){}\n', sendMessageOnCtrlEnter: true, sendCodeBlockOnCtrlEnter: false}, expected: {allowSending: true, message: '```\nfunction(){}\n```', withClosedCodeBlock: true}, }, { name: 'sendMessageOnCtrlEnter: Test for overriding sending of message on CTRL+ENTER, with ctrlKey, with opening backticks, with multiple line breaks on last lines', input: {event: {keyCode: 13, ctrlKey: true}, message: '```\nfunction(){}\n\n\n', sendMessageOnCtrlEnter: true, sendCodeBlockOnCtrlEnter: false}, expected: {allowSending: true, message: '```\nfunction(){}\n\n\n```', withClosedCodeBlock: true}, }, { name: 'sendMessageOnCtrlEnter: Test for overriding sending of message on CTRL+ENTER, with ctrlKey, with opening and closing backticks', input: {event: {keyCode: 13, ctrlKey: true}, message: '```\nfunction(){}\n```', sendMessageOnCtrlEnter: true, sendCodeBlockOnCtrlEnter: false}, expected: {allowSending: true}, }, { name: 'sendMessageOnCtrlEnter: Test for overriding sending of message on CTRL+ENTER, with ctrlKey, with opening and closing backticks, with language set', input: {event: {keyCode: 13, ctrlKey: true}, message: '```javascript\nfunction(){}\n```', sendMessageOnCtrlEnter: true, sendCodeBlockOnCtrlEnter: false}, expected: {allowSending: true}, }, { name: 'sendMessageOnCtrlEnter: Test for overriding sending of message on CTRL+ENTER, with ctrlKey, with inline opening backticks', input: {event: {keyCode: 13, ctrlKey: true}, message: '``` message', sendMessageOnCtrlEnter: true, sendCodeBlockOnCtrlEnter: false}, expected: {allowSending: true}, }]; for (const testCase of sendMessageOnCtrlEnterCases) { it(testCase.name, () => { const output = PostUtils.postMessageOnKeyPress( testCase.input.event as any, testCase.input.message, testCase.input.sendMessageOnCtrlEnter, testCase.input.sendCodeBlockOnCtrlEnter, 0, 0, testCase.input.message.length, ); expect(output).toEqual(testCase.expected); }); } // on sending and/or closing of code block on Ctrl + Enter const sendCodeBlockOnCtrlEnterCases = [{ name: 'sendCodeBlockOnCtrlEnter: Test for overriding sending of code block on CTRL+ENTER, no ctrlKey|metaKey, without opening backticks', input: {event: {keyCode: 13}, message: 'message', sendMessageOnCtrlEnter: false, sendCodeBlockOnCtrlEnter: true}, expected: {allowSending: true}, }, { name: 'sendCodeBlockOnCtrlEnter: Test for overriding sending of code block on CTRL+ENTER, no ctrlKey|metaKey, with opening backticks', input: {event: {keyCode: 13}, message: '```', sendMessageOnCtrlEnter: false, sendCodeBlockOnCtrlEnter: true}, expected: {allowSending: false}, }, { name: 'sendCodeBlockOnCtrlEnter: Test for overriding sending of code block on CTRL+ENTER, no ctrlKey|metaKey, with opening backticks', input: {event: {keyCode: 13}, message: '```javascript', sendMessageOnCtrlEnter: false, sendCodeBlockOnCtrlEnter: true}, expected: {allowSending: false}, }, { name: 'sendCodeBlockOnCtrlEnter: Test for overriding sending of code block on CTRL+ENTER, no ctrlKey|metaKey, with opening backticks', input: {event: {keyCode: 13}, message: '```javascript\n', sendMessageOnCtrlEnter: false, sendCodeBlockOnCtrlEnter: true}, expected: {allowSending: false}, }, { name: 'sendCodeBlockOnCtrlEnter: Test for overriding sending of code block on CTRL+ENTER, no ctrlKey|metaKey, with opening backticks', input: {event: {keyCode: 13}, message: '```javascript\n function(){}', sendMessageOnCtrlEnter: false, sendCodeBlockOnCtrlEnter: true}, expected: {allowSending: false}, }, { name: 'sendCodeBlockOnCtrlEnter: Test for overriding sending of code block on CTRL+ENTER, with ctrlKey, without opening backticks', input: {event: {keyCode: 13, ctrlKey: true}, message: 'message', sendMessageOnCtrlEnter: false, sendCodeBlockOnCtrlEnter: true}, expected: {allowSending: true}, }, { name: 'sendCodeBlockOnCtrlEnter: Test for overriding sending of code block on CTRL+ENTER, with metaKey, without opening backticks', input: {event: {keyCode: 13, metaKey: true}, message: 'message', sendMessageOnCtrlEnter: false, sendCodeBlockOnCtrlEnter: true}, expected: {allowSending: true}, }, { name: 'sendCodeBlockOnCtrlEnter: Test for overriding sending of code block on CTRL+ENTER, with ctrlKey, with line break', input: {event: {keyCode: 13, ctrlKey: true}, message: '\n', sendMessageOnCtrlEnter: false, sendCodeBlockOnCtrlEnter: true}, expected: {allowSending: true}, }, { name: 'sendCodeBlockOnCtrlEnter: Test for overriding sending of code block on CTRL+ENTER, with ctrlKey, with multiple line breaks', input: {event: {keyCode: 13, ctrlKey: true}, message: '\n\n\n', sendMessageOnCtrlEnter: false, sendCodeBlockOnCtrlEnter: true}, expected: {allowSending: true}, }, { name: 'sendCodeBlockOnCtrlEnter: Test for overriding sending of code block on CTRL+ENTER, with ctrlKey, with opening backticks', input: {event: {keyCode: 13, ctrlKey: true}, message: '```', sendMessageOnCtrlEnter: false, sendCodeBlockOnCtrlEnter: true}, expected: {allowSending: true}, }, { name: 'sendCodeBlockOnCtrlEnter: Test for overriding sending of code block on CTRL+ENTER, with ctrlKey, with opening backticks, with language set', input: {event: {keyCode: 13, ctrlKey: true}, message: '```javascript', sendMessageOnCtrlEnter: false, sendCodeBlockOnCtrlEnter: true}, expected: {allowSending: true}, }, { name: 'sendCodeBlockOnCtrlEnter: Test for overriding sending of code block on CTRL+ENTER, with ctrlKey, with opening and closing backticks, with language set', input: {event: {keyCode: 13, ctrlKey: true}, message: '```javascript\n function(){}\n```', sendMessageOnCtrlEnter: false, sendCodeBlockOnCtrlEnter: true}, expected: {allowSending: true}, }, { name: 'sendCodeBlockOnCtrlEnter: Test for overriding sending of code block on CTRL+ENTER, with ctrlKey, with opening and closing backticks', input: {event: {keyCode: 13, ctrlKey: true}, message: '```\n function(){}\n```', sendMessageOnCtrlEnter: false, sendCodeBlockOnCtrlEnter: true}, expected: {allowSending: true}, }, { name: 'sendCodeBlockOnCtrlEnter: Test for overriding sending of code block on CTRL+ENTER, with ctrlKey, with opening backticks, with last line of empty spaces', input: {event: {keyCode: 13, ctrlKey: true}, message: '```javascript\n function(){}\n ', sendMessageOnCtrlEnter: false, sendCodeBlockOnCtrlEnter: true}, expected: {allowSending: true, message: '```javascript\n function(){}\n \n```', withClosedCodeBlock: true}, }, { name: 'sendCodeBlockOnCtrlEnter: Test for overriding sending of code block on CTRL+ENTER, with ctrlKey, with opening backticks, with empty line break on last line', input: {event: {keyCode: 13, ctrlKey: true}, message: '```javascript\n function(){}\n', sendMessageOnCtrlEnter: false, sendCodeBlockOnCtrlEnter: true}, expected: {allowSending: true, message: '```javascript\n function(){}\n```', withClosedCodeBlock: true}, }, { name: 'sendCodeBlockOnCtrlEnter: Test for overriding sending of code block on CTRL+ENTER, with ctrlKey, with opening backticks, with multiple empty line breaks on last lines', input: {event: {keyCode: 13, ctrlKey: true}, message: '```javascript\n function(){}\n\n\n', sendMessageOnCtrlEnter: false, sendCodeBlockOnCtrlEnter: true}, expected: {allowSending: true, message: '```javascript\n function(){}\n\n\n```', withClosedCodeBlock: true}, }, { name: 'sendCodeBlockOnCtrlEnter: Test for overriding sending of code block on CTRL+ENTER, with ctrlKey, with opening backticks, with multiple empty line breaks and spaces on last lines', input: {event: {keyCode: 13, ctrlKey: true}, message: '```javascript\n function(){}\n \n\n ', sendMessageOnCtrlEnter: false, sendCodeBlockOnCtrlEnter: true}, expected: {allowSending: true, message: '```javascript\n function(){}\n \n\n \n```', withClosedCodeBlock: true}, }, { name: 'sendCodeBlockOnCtrlEnter: Test for overriding sending of code block on CTRL+ENTER, with ctrlKey, with opening backticks, without line break on last line', input: {event: {keyCode: 13, ctrlKey: true}, message: '```javascript\n function(){}', sendMessageOnCtrlEnter: false, sendCodeBlockOnCtrlEnter: true}, expected: {allowSending: true, message: '```javascript\n function(){}\n```', withClosedCodeBlock: true}, }, { name: 'sendCodeBlockOnCtrlEnter: Test for overriding sending of code block on CTRL+ENTER, with ctrlKey, with inline opening backticks', input: {event: {keyCode: 13, ctrlKey: true}, message: '``` message', sendMessageOnCtrlEnter: true, sendCodeBlockOnCtrlEnter: false}, expected: {allowSending: true}, }, { name: 'sendCodeBlockOnCtrlEnter: Test for overriding sending of code block on CTRL+ENTER, no ctrlKey|metaKey, with cursor between backticks', input: {event: {keyCode: 13, ctrlKey: false}, message: '``` message ```', sendMessageOnCtrlEnter: true, sendCodeBlockOnCtrlEnter: true, cursorPosition: 5}, expected: {allowSending: false}, }, { name: 'sendCodeBlockOnCtrlEnter: Test for overriding sending of code block on CTRL+ENTER, with ctrlKey, with cursor between backticks', input: {event: {keyCode: 13, ctrlKey: true}, message: '``` message ```', sendMessageOnCtrlEnter: true, sendCodeBlockOnCtrlEnter: true, cursorPosition: 5}, expected: {allowSending: true}, }]; for (const testCase of sendCodeBlockOnCtrlEnterCases) { it(testCase.name, () => { const output = PostUtils.postMessageOnKeyPress( testCase.input.event as any, testCase.input.message, testCase.input.sendMessageOnCtrlEnter, testCase.input.sendCodeBlockOnCtrlEnter, 0, 0, testCase.input.cursorPosition ? testCase.input.cursorPosition : testCase.input.message.length, ); expect(output).toEqual(testCase.expected); }); } // on sending within channel threshold const channelThresholdCases = [{ name: 'now unspecified, last channel switch unspecified', input: {event: {keyCode: 13}, message: 'message', sendMessageOnCtrlEnter: false, sendCodeBlockOnCtrlEnter: true, now: 0, lastChannelSwitch: 0}, expected: {allowSending: true}, }, { name: 'now specified, last channel switch unspecified', input: {event: {keyCode: 13}, message: 'message', sendMessageOnCtrlEnter: false, sendCodeBlockOnCtrlEnter: true, now: 1541658920334, lastChannelSwitch: 0}, expected: {allowSending: true}, }, { name: 'now specified, last channel switch unspecified', input: {event: {keyCode: 13}, message: 'message', sendMessageOnCtrlEnter: false, sendCodeBlockOnCtrlEnter: true, now: 0, lastChannelSwitch: 1541658920334}, expected: {allowSending: true}, }, { name: 'last channel switch within threshold', input: {event: {keyCode: 13}, message: 'message', sendMessageOnCtrlEnter: false, sendCodeBlockOnCtrlEnter: true, now: 1541658920334, lastChannelSwitch: 1541658920334 - 250}, expected: {allowSending: false, ignoreKeyPress: true}, }, { name: 'last channel switch at threshold', input: {event: {keyCode: 13}, message: 'message', sendMessageOnCtrlEnter: false, sendCodeBlockOnCtrlEnter: true, now: 1541658920334, lastChannelSwitch: 1541658920334 - 500}, expected: {allowSending: false, ignoreKeyPress: true}, }, { name: 'last channel switch outside threshold', input: {event: {keyCode: 13}, message: 'message', sendMessageOnCtrlEnter: false, sendCodeBlockOnCtrlEnter: true, now: 1541658920334, lastChannelSwitch: 1541658920334 - 501}, expected: {allowSending: true}, }, { name: 'last channel switch well outside threshold', input: {event: {keyCode: 13}, message: 'message', sendMessageOnCtrlEnter: false, sendCodeBlockOnCtrlEnter: true, now: 1541658920334, lastChannelSwitch: 1541658920334 - 1500}, expected: {allowSending: true}, }]; for (const testCase of channelThresholdCases) { it(testCase.name, () => { const output = PostUtils.postMessageOnKeyPress( testCase.input.event as any, testCase.input.message, testCase.input.sendMessageOnCtrlEnter, testCase.input.sendCodeBlockOnCtrlEnter, testCase.input.now, testCase.input.lastChannelSwitch, testCase.input.message.length, ); expect(output).toEqual(testCase.expected); }); } }); describe('PostUtils.getOldestPostId', () => { test('Should not return LOAD_OLDER_MESSAGES_TRIGGER', () => { const postId = PostUtils.getOldestPostId(['postId1', 'postId2', PostListRowListIds.LOAD_OLDER_MESSAGES_TRIGGER]); expect(postId).toEqual('postId2'); }); test('Should not return OLDER_MESSAGES_LOADER', () => { const postId = PostUtils.getOldestPostId(['postId1', 'postId2', PostListRowListIds.OLDER_MESSAGES_LOADER]); expect(postId).toEqual('postId2'); }); test('Should not return CHANNEL_INTRO_MESSAGE', () => { const postId = PostUtils.getOldestPostId(['postId1', 'postId2', PostListRowListIds.CHANNEL_INTRO_MESSAGE]); expect(postId).toEqual('postId2'); }); test('Should not return dateline', () => { const postId = PostUtils.getOldestPostId(['postId1', 'postId2', 'date-1558290600000']); expect(postId).toEqual('postId2'); }); test('Should not return START_OF_NEW_MESSAGES', () => { const postId = PostUtils.getOldestPostId(['postId1', 'postId2', PostListRowListIds.START_OF_NEW_MESSAGES]); expect(postId).toEqual('postId2'); }); }); describe('PostUtils.getPreviousPostId', () => { test('Should skip dateline', () => { const postId = PostUtils.getPreviousPostId(['postId1', 'postId2', 'date-1558290600000', 'postId3'], 1); expect(postId).toEqual('postId3'); }); test('Should skip START_OF_NEW_MESSAGES', () => { const postId = PostUtils.getPreviousPostId(['postId1', 'postId2', PostListRowListIds.START_OF_NEW_MESSAGES, 'postId3'], 1); expect(postId).toEqual('postId3'); }); test('Should return first postId from combined system messages', () => { const postId = PostUtils.getPreviousPostId(['postId1', 'postId2', 'user-activity-post1_post2_post3', 'postId3'], 1); expect(postId).toEqual('post1'); }); }); describe('PostUtils.getLatestPostId', () => { test('Should not return LOAD_OLDER_MESSAGES_TRIGGER', () => { const postId = PostUtils.getLatestPostId([PostListRowListIds.LOAD_OLDER_MESSAGES_TRIGGER, 'postId1', 'postId2']); expect(postId).toEqual('postId1'); }); test('Should not return OLDER_MESSAGES_LOADER', () => { const postId = PostUtils.getLatestPostId([PostListRowListIds.OLDER_MESSAGES_LOADER, 'postId1', 'postId2']); expect(postId).toEqual('postId1'); }); test('Should not return CHANNEL_INTRO_MESSAGE', () => { const postId = PostUtils.getLatestPostId([PostListRowListIds.CHANNEL_INTRO_MESSAGE, 'postId1', 'postId2']); expect(postId).toEqual('postId1'); }); test('Should not return dateline', () => { const postId = PostUtils.getLatestPostId(['date-1558290600000', 'postId1', 'postId2']); expect(postId).toEqual('postId1'); }); test('Should not return START_OF_NEW_MESSAGES', () => { const postId = PostUtils.getLatestPostId([PostListRowListIds.START_OF_NEW_MESSAGES, 'postId1', 'postId2']); expect(postId).toEqual('postId1'); }); test('Should return first postId from combined system messages', () => { const postId = PostUtils.getLatestPostId(['user-activity-post1_post2_post3', 'postId1', 'postId2']); expect(postId).toEqual('post1'); }); }); describe('PostUtils.createAriaLabelForPost', () => { const emojiMap = new EmojiMap(new Map()); const users = { 'benjamin.cooke': TestHelper.getUserMock({ username: 'benjamin.cooke', nickname: 'sysadmin', first_name: 'Benjamin', last_name: 'Cooke', }), }; const teammateNameDisplaySetting = 'username'; test('Should show username, timestamp, message, attachments, reactions, flagged and pinned', () => { const intl = createIntl({locale: 'en', messages: enMessages, defaultLocale: 'en'}); const testPost = TestHelper.getPostMock({ message: 'test_message', create_at: (new Date().getTime() / 1000) || 0, props: { attachments: [ {i: 'am attachment 1'}, {and: 'i am attachment 2'}, ], }, file_ids: ['test_file_id_1'], is_pinned: true, }); const author = 'test_author'; const reactions = { reaction1: TestHelper.getReactionMock({emoji_name: 'reaction 1'}), reaction2: TestHelper.getReactionMock({emoji_name: 'reaction 2'}), }; const isFlagged = true; const ariaLabel = PostUtils.createAriaLabelForPost(testPost, author, isFlagged, reactions, intl, emojiMap, users, teammateNameDisplaySetting); expect(ariaLabel.indexOf(author)).not.toBe(-1); expect(ariaLabel.indexOf(testPost.message)).not.toBe(-1); expect(ariaLabel.indexOf('3 attachments')).not.toBe(-1); expect(ariaLabel.indexOf('2 reactions')).not.toBe(-1); expect(ariaLabel.indexOf('message is saved and pinned')).not.toBe(-1); }); test('Should show that message is a reply', () => { const intl = createIntl({locale: 'en', messages: enMessages, defaultLocale: 'en'}); const testPost = TestHelper.getPostMock({ message: 'test_message', root_id: 'test_id', create_at: (new Date().getTime() / 1000) || 0, }); const author = 'test_author'; const reactions = {}; const isFlagged = true; const ariaLabel = PostUtils.createAriaLabelForPost(testPost, author, isFlagged, reactions, intl, emojiMap, users, teammateNameDisplaySetting); expect(ariaLabel.indexOf('replied')).not.toBe(-1); }); test('Should translate emoji into {emoji-name} emoji', () => { const intl = createIntl({locale: 'en', messages: enMessages, defaultLocale: 'en'}); const testPost = TestHelper.getPostMock({ message: 'emoji_test :smile: :+1: :non-potable_water: :space emoji: :not_an_emoji:', create_at: (new Date().getTime() / 1000) || 0, }); const author = 'test_author'; const reactions = {}; const isFlagged = true; const ariaLabel = PostUtils.createAriaLabelForPost(testPost, author, isFlagged, reactions, intl, emojiMap, users, teammateNameDisplaySetting); expect(ariaLabel.indexOf('smile emoji')).not.toBe(-1); expect(ariaLabel.indexOf('+1 emoji')).not.toBe(-1); expect(ariaLabel.indexOf('non-potable water emoji')).not.toBe(-1); expect(ariaLabel.indexOf(':space emoji:')).not.toBe(-1); expect(ariaLabel.indexOf(':not_an_emoji:')).not.toBe(-1); }); test('Generating aria label should not break if message is undefined', () => { const intl = createIntl({locale: 'en', messages: enMessages, defaultLocale: 'en'}); const testPost = TestHelper.getPostMock({ id: '32', message: undefined, create_at: (new Date().getTime() / 1000) || 0, }); const author = 'test_author'; const reactions = {}; const isFlagged = true; expect(() => PostUtils.createAriaLabelForPost(testPost, author, isFlagged, reactions, intl, emojiMap, users, teammateNameDisplaySetting)).not.toThrow(); }); test('Should not mention reactions if passed an empty object', () => { const intl = createIntl({locale: 'en', messages: enMessages, defaultLocale: 'en'}); const testPost = TestHelper.getPostMock({ message: 'test_message', root_id: 'test_id', create_at: (new Date().getTime() / 1000) || 0, }); const author = 'test_author'; const reactions = {}; const isFlagged = true; const ariaLabel = PostUtils.createAriaLabelForPost(testPost, author, isFlagged, reactions, intl, emojiMap, users, teammateNameDisplaySetting); expect(ariaLabel.indexOf('reaction')).toBe(-1); }); test('Should show the username as mention name in the message', () => { const intl = createIntl({locale: 'en', messages: enMessages, defaultLocale: 'en'}); const testPost = TestHelper.getPostMock({ message: 'test_message @benjamin.cooke', root_id: 'test_id', create_at: (new Date().getTime() / 1000) || 0, }); const author = 'test_author'; const reactions = {}; const isFlagged = true; const ariaLabel = PostUtils.createAriaLabelForPost(testPost, author, isFlagged, reactions, intl, emojiMap, users, teammateNameDisplaySetting); expect(ariaLabel.indexOf('@benjamin.cooke')).not.toBe(-1); }); test('Should show the nickname as mention name in the message', () => { const intl = createIntl({locale: 'en', messages: enMessages, defaultLocale: 'en'}); const testPost = TestHelper.getPostMock({ message: 'test_message @benjamin.cooke', root_id: 'test_id', create_at: (new Date().getTime() / 1000) || 0, }); const author = 'test_author'; const reactions = {}; const isFlagged = true; const ariaLabel = PostUtils.createAriaLabelForPost(testPost, author, isFlagged, reactions, intl, emojiMap, users, 'nickname_full_name'); expect(ariaLabel.indexOf('@sysadmin')).not.toBe(-1); }); }); describe('PostUtils.splitMessageBasedOnCaretPosition', () => { const state = { caretPosition: 2, }; const message = 'Test Message'; it('should return an object with two strings when given context and message', () => { const stringPieces = PostUtils.splitMessageBasedOnCaretPosition(state.caretPosition, message); expect('Te').toEqual(stringPieces.firstPiece); expect('st Message').toEqual(stringPieces.lastPiece); }); }); describe('PostUtils.splitMessageBasedOnTextSelection', () => { const cases: Array<[number, number, string, {firstPiece: string; lastPiece: string}]> = [ [0, 0, 'Test Replace Message', {firstPiece: '', lastPiece: 'Test Replace Message'}], [20, 20, 'Test Replace Message', {firstPiece: 'Test Replace Message', lastPiece: ''}], [0, 20, 'Test Replace Message', {firstPiece: '', lastPiece: ''}], [0, 10, 'Test Replace Message', {firstPiece: '', lastPiece: 'ce Message'}], [5, 12, 'Test Replace Message', {firstPiece: 'Test ', lastPiece: ' Message'}], [7, 20, 'Test Replace Message', {firstPiece: 'Test Re', lastPiece: ''}], ]; test.each(cases)('should return an object with two strings when given context and message', (start, end, message, expected) => { expect(PostUtils.splitMessageBasedOnTextSelection(start, end, message)).toEqual(expected); }); }); describe('PostUtils.getPostURL', () => { const currentTeam = TestHelper.getTeamMock({id: 'current_team_id', name: 'current_team_name'}); const team = TestHelper.getTeamMock({id: 'team_id_1', name: 'team_1'}); const dmChannel = TestHelper.getChannelMock({id: 'dm_channel_id', name: 'current_user_id__user_id_1', type: Constants.DM_CHANNEL as 'D', team_id: ''}); const gmChannel = TestHelper.getChannelMock({id: 'gm_channel_id', name: 'gm_channel_name', type: Constants.GM_CHANNEL as 'G', team_id: ''}); const channel = TestHelper.getChannelMock({id: 'channel_id', name: 'channel_name', team_id: team.id}); const dmPost = TestHelper.getPostMock({id: 'dm_post_id', channel_id: dmChannel.id}); const gmPost = TestHelper.getPostMock({id: 'gm_post_id', channel_id: gmChannel.id}); const post = TestHelper.getPostMock({id: 'post_id', channel_id: channel.id}); const dmReply = TestHelper.getPostMock({id: 'dm_reply_id', root_id: 'root_post_id_1', channel_id: dmChannel.id}); const gmReply = TestHelper.getPostMock({id: 'gm_reply_id', root_id: 'root_post_id_1', channel_id: gmChannel.id}); const reply = TestHelper.getPostMock({id: 'reply_id', root_id: 'root_post_id_1', channel_id: channel.id}); const getState = (collapsedThreads: boolean) => ({ entities: { general: { config: { CollapsedThreads: 'default_off', }, }, preferences: { myPreferences: { [`${Preferences.CATEGORY_DISPLAY_SETTINGS}--${Preferences.COLLAPSED_REPLY_THREADS}`]: { value: collapsedThreads ? 'on' : 'off', }, }, }, users: { currentUserId: 'current_user_id', profiles: { user_id_1: { id: 'user_id_1', username: 'jessicahyde', }, current_user_id: { id: 'current_user_id', username: 'currentuser', }, }, }, channels: { channels: { gm_channel_id: gmChannel, dm_channel_id: dmChannel, channel_id: channel, }, myMembers: {channelid1: {channel_id: 'channelid1', user_id: 'current_user_id'}}, }, teams: { currentTeamId: currentTeam.id, teams: { current_team_id: currentTeam, team_id_1: team, }, }, posts: { dm_post_id: dmPost, gm_post_id: gmPost, post_id: post, dm_reply_id: dmReply, gm_reply_id: gmReply, reply_id: reply, }, }, } as unknown as GlobalState); test.each([ ['/current_team_name/messages/@jessicahyde/dm_post_id', dmPost, true], ['/current_team_name/messages/gm_channel_name/gm_post_id', gmPost, true], ['/team_1/channels/channel_name/post_id', post, true], ['/current_team_name/messages/@jessicahyde/dm_post_id', dmPost, false], ['/current_team_name/messages/gm_channel_name/gm_post_id', gmPost, false], ['/team_1/channels/channel_name/post_id', post, false], ])('root posts should return %s', (expected, postCase, collapsedThreads) => { const state = getState(collapsedThreads); expect(PostUtils.getPostURL(state, postCase)).toBe(expected); }); test.each([ ['/current_team_name/messages/@jessicahyde', dmReply, true], ['/current_team_name/messages/gm_channel_name', gmReply, true], ['/team_1/channels/channel_name', reply, true], ['/current_team_name/messages/@jessicahyde/dm_reply_id', dmReply, false], ['/current_team_name/messages/gm_channel_name/gm_reply_id', gmReply, false], ['/team_1/channels/channel_name/reply_id', reply, false], ])('replies should return %s', (expected, postCase, collapsedThreads) => { const state = getState(collapsedThreads); expect(PostUtils.getPostURL(state, postCase)).toBe(expected); }); }); describe('PostUtils.isWithinCodeBlock', () => { const CARET_MARKER = '•'; const TRIPLE_BACKTICKS = '```'; const getCaretAndMsg = (textWithCaret: string): [number, string] => { const normalizedText = textWithCaret.split('\n').map((line) => line.replace(/^\s*\|/, '')).join('\n'); return [normalizedText.indexOf(CARET_MARKER), normalizedText]; }; it('should return true if caret is within a code block', () => { const [caretPosition, message] = getCaretAndMsg(` |This is a line of text |${TRIPLE_BACKTICKS} | fun main() { | println("Hello Wo${CARET_MARKER}") | } |${TRIPLE_BACKTICKS} |This is a line of text `); expect(PostUtils.isWithinCodeBlock(message, caretPosition)).toBe(true); }); it('should return false if caret is not within a code block', () => { const [caretPosition, message] = getCaretAndMsg(` |This is a line of text |${TRIPLE_BACKTICKS} | fun main() { | println("Hello World") | } |${TRIPLE_BACKTICKS} |This is a line of t${CARET_MARKER} `); expect(PostUtils.isWithinCodeBlock(message, caretPosition)).toBe(false); }); it('should handle code blocks with language tags', () => { const [caretPosition, message] = getCaretAndMsg(` |This is a line of text |${TRIPLE_BACKTICKS}kotlin | fun main() { | println("Hello Wo${CARET_MARKER}") | } |${TRIPLE_BACKTICKS} |This is a line of text `); expect(PostUtils.isWithinCodeBlock(message, caretPosition)).toBe(true); }); it('should handle caret in front of code block', () => { const [caretPosition, message] = getCaretAndMsg(` |${CARET_MARKER}${TRIPLE_BACKTICKS}kotlin | fun main() { | println("Test") | } |${TRIPLE_BACKTICKS} |This is text `); expect(PostUtils.isWithinCodeBlock(message, caretPosition)).toBe(false); }); it('should handle caret behind code block', () => { const [caretPosition, message] = getCaretAndMsg(` |${TRIPLE_BACKTICKS}kotlin | fun main() { | println("Test") | } |${TRIPLE_BACKTICKS}${CARET_MARKER} |This is text `); expect(PostUtils.isWithinCodeBlock(message, caretPosition)).toBe(false); }); it('should handle multiple code blocks', () => { const [caretPosition, message] = getCaretAndMsg(` |${TRIPLE_BACKTICKS} | Code Block 1 |${TRIPLE_BACKTICKS} |This is text |${TRIPLE_BACKTICKS} | Code Block 2 ${CARET_MARKER} |${TRIPLE_BACKTICKS} `); expect(PostUtils.isWithinCodeBlock(message, caretPosition)).toBe(true); }); it('should handle empty code blocks', () => { const [caretPosition, message] = getCaretAndMsg(` |${TRIPLE_BACKTICKS} |${TRIPLE_BACKTICKS} |${CARET_MARKER} `); expect(PostUtils.isWithinCodeBlock(message, caretPosition)).toBe(false); }); it('should handle consecutive code blocks', () => { const [caretPosition, message] = getCaretAndMsg(` |${TRIPLE_BACKTICKS} | Code Block 1 |${TRIPLE_BACKTICKS} |This is text |${TRIPLE_BACKTICKS} | Code Block 2 ${CARET_MARKER} |${TRIPLE_BACKTICKS} |${TRIPLE_BACKTICKS} | Code Block 3 |${TRIPLE_BACKTICKS} |This is text `); expect(PostUtils.isWithinCodeBlock(message, caretPosition)).toBe(true); }); it('should handle caret position at 0', () => { const [caretPosition, message] = getCaretAndMsg(`${CARET_MARKER} |This is text `); expect(PostUtils.isWithinCodeBlock(message, caretPosition)).toBe(false); }); it('should handle whitespace within and around code blocks', () => { const [caretPosition, message] = getCaretAndMsg(` |${TRIPLE_BACKTICKS} | Test text asd 1 | ${CARET_MARKER} |${TRIPLE_BACKTICKS} `); expect(PostUtils.isWithinCodeBlock(message, caretPosition)).toBe(true); }); it('should produce consistent results when called multiple times', () => { const [caretPosition, message] = getCaretAndMsg(` |${TRIPLE_BACKTICKS} | Test text asd 1 | ${CARET_MARKER} |${TRIPLE_BACKTICKS} `); const results = Array.from({length: 10}, () => PostUtils.isWithinCodeBlock(message, caretPosition)); expect(results.every(Boolean)).toBe(true); }); }); describe('PostUtils.getMentionDetails', () => { const user1 = TestHelper.getUserMock({username: 'user1'}); const user2 = TestHelper.getUserMock({username: 'user2'}); const users = {user1, user2}; test.each([ ['user1 data from mention', 'user1', user1], ['user2 data from mention', 'user2', user2], ['user1 data from mention with punctution', 'user1.', user1], ['blank string when no matching user', 'user3', undefined], ])('should return %s', (description, mention, expected) => { expect(PostUtils.getMentionDetails(users, mention)).toEqual(expected); }); const group1 = TestHelper.getGroupMock({name: 'group1'}); const group2 = TestHelper.getGroupMock({name: 'group2'}); const groups = {group1, group2}; test.each([ ['group1 data from mention', 'group1', group1], ['group2 data from mention', 'group2', group2], ['group1 data from mention with punctuation', 'group2.', group2], ['blank string when no matching group', 'group3', undefined], ])('shoud return %s', (description, mention, expected) => { expect(PostUtils.getMentionDetails(groups, mention)).toEqual(expected); }); }); describe('PostUtils.getUserOrGroupFromMentionName', () => { const userMention = 'user1'; const groupMention = 'group1'; const userAndGroupMention = 'user2'; const user1 = TestHelper.getUserMock({username: 'user1'}); const user2 = TestHelper.getUserMock({username: 'user2'}); const users = {user1, user2}; const group1 = TestHelper.getGroupMock({name: 'group1'}); const group2 = TestHelper.getGroupMock({name: 'user2'}); const groups = {group1, user2: group2}; test.each([ ['the found user', userMention, false, [user1, undefined]], ['nothing when not matching user or group', 'user3', false, [undefined, undefined]], ['the found group', groupMention, false, [undefined, group1]], ['no group when groups highlights are disabled', groupMention, true, [undefined, undefined]], ['user when there is a matching user and group mention', userAndGroupMention, false, [user2, undefined]], ])('should return %s', (description, mention, disabledGroups, expected) => { const result = PostUtils.getUserOrGroupFromMentionName( mention, users, groups, disabledGroups, (usersOrGroups, mention) => usersOrGroups[mention], ); expect(result).toEqual(expected); }); }); describe('makeGetIsReactionAlreadyAddedToPost', () => { const currentUserId = 'current_user_id'; const baseState = { entities: { users: { currentUserId, }, posts: { reactions: { post_id_1: { 'current_user_id-smile': { emoji_name: 'smile', user_id: currentUserId, post_id: 'post_id_1', }, }, }, }, general: { config: {}, }, emojis: {}, }} as unknown as GlobalState; test('should return true if the post has an emoji that the user has reacted to.', () => { const getIsReactionAlreadyAddedToPost = PostUtils.makeGetIsReactionAlreadyAddedToPost(); expect(getIsReactionAlreadyAddedToPost(baseState, 'post_id_1', 'sad')).toBeFalsy(); expect(getIsReactionAlreadyAddedToPost(baseState, 'post_id_1', 'smile')).toBeTruthy(); }); });
4,504
0
petrpan-code/mattermost/mattermost/webapp/channels/src
petrpan-code/mattermost/mattermost/webapp/channels/src/utils/route.test.ts
// Copyright (c) 2015-present Mattermost, Inc. All Rights Reserved. // See LICENSE.txt for license information. import type {ClientLicense} from '@mattermost/types/config'; import type {UserProfile} from '@mattermost/types/users'; import {checkIfMFARequired} from './route'; import type {ConfigOption} from './route'; describe('Utils.Route', () => { describe('checkIfMFARequired', () => { test('mfa is enforced', () => { const user: UserProfile = {mfa_active: false, auth_service: '', id: '', create_at: 0, update_at: 0, delete_at: 0, username: '', password: '', email: '', nickname: '', first_name: '', last_name: '', position: '', roles: '', props: {userid: '121'}, notify_props: {desktop: 'default', desktop_sound: 'false', calls_desktop_sound: 'true', email: 'true', mark_unread: 'all', push: 'default', push_status: 'ooo', comments: 'never', first_name: 'true', channel: 'true', mention_keys: '', highlight_keys: '', }, last_password_update: 0, last_picture_update: 0, locale: '', timezone: {useAutomaticTimezone: '', automaticTimezone: '', manualTimezone: ''}, last_activity_at: 0, is_bot: false, bot_description: '', terms_of_service_id: '', terms_of_service_create_at: 0, remote_id: ''}; const config: ConfigOption = {EnableMultifactorAuthentication: 'true', EnforceMultifactorAuthentication: 'true'}; const license: ClientLicense = {MFA: 'true'}; expect(checkIfMFARequired(user, license, config, '')).toBeTruthy(); expect(!checkIfMFARequired(user, license, config, '/mfa/setup')).toBeTruthy(); expect(!checkIfMFARequired(user, license, config, '/mfa/confirm')).toBeTruthy(); user.auth_service = 'email'; expect(checkIfMFARequired(user, license, config, '')).toBeTruthy(); user.auth_service = 'ldap'; expect(checkIfMFARequired(user, license, config, '')).toBeTruthy(); user.auth_service = 'saml'; expect(!checkIfMFARequired(user, license, config, '')).toBeTruthy(); user.auth_service = ''; user.mfa_active = true; expect(!checkIfMFARequired(user, license, config, '')).toBeTruthy(); }); test('mfa is not enforced or enabled', () => { const user: UserProfile = {mfa_active: true, auth_service: '', id: '', create_at: 0, update_at: 0, delete_at: 0, username: '', password: '', email: '', nickname: '', first_name: '', last_name: '', position: '', roles: '', props: {userid: '121'}, notify_props: { desktop: 'default', desktop_sound: 'false', calls_desktop_sound: 'true', email: 'true', mark_unread: 'all', push: 'default', push_status: 'ooo', comments: 'never', first_name: 'true', channel: 'true', mention_keys: '', highlight_keys: '', }, last_password_update: 0, last_picture_update: 0, locale: '', timezone: {useAutomaticTimezone: '', automaticTimezone: '', manualTimezone: ''}, last_activity_at: 0, is_bot: false, bot_description: '', terms_of_service_id: '', terms_of_service_create_at: 0, remote_id: ''}; const config: ConfigOption = {EnableMultifactorAuthentication: 'true', EnforceMultifactorAuthentication: 'true'}; const license: ClientLicense = {MFA: 'true'}; expect(!checkIfMFARequired(user, license, config, '')).toBeTruthy(); config.EnforceMultifactorAuthentication = 'true'; config.EnableMultifactorAuthentication = 'false'; expect(!checkIfMFARequired(user, license, config, '')).toBeTruthy(); license.MFA = 'false'; config.EnableMultifactorAuthentication = 'true'; expect(!checkIfMFARequired(user, license, config, '')).toBeTruthy(); }); }); });
4,506
0
petrpan-code/mattermost/mattermost/webapp/channels/src
petrpan-code/mattermost/mattermost/webapp/channels/src/utils/server_version.test.tsx
// Copyright (c) 2015-present Mattermost, Inc. All Rights Reserved. // See LICENSE.txt for license information. import {isServerVersionGreaterThanOrEqualTo} from 'utils/server_version'; describe('utils/server_version/isServerVersionGreaterThanOrEqualTo', () => { test('should consider two empty versions as equal', () => { const a = ''; const b = ''; expect(isServerVersionGreaterThanOrEqualTo(a, b)).toEqual(true); }); test('should consider different strings without components as equal', () => { const a = 'not a server version'; const b = 'also not a server version'; expect(isServerVersionGreaterThanOrEqualTo(a, b)).toEqual(true); }); test('should consider different malformed versions normally (not greater than case)', () => { const a = '1.2.3'; const b = '1.2.4'; expect(isServerVersionGreaterThanOrEqualTo(a, b)).toEqual(false); }); test('should consider different malformed versions normally (greater than case)', () => { const a = '1.2.4'; const b = '1.2.3'; expect(isServerVersionGreaterThanOrEqualTo(a, b)).toEqual(true); }); test('should work correctly for different numbers of digits', () => { const a = '10.0.1'; const b = '4.8.0'; expect(isServerVersionGreaterThanOrEqualTo(a, b)).toEqual(true); }); test('should consider an empty version as not greater than or equal', () => { const a = ''; const b = '4.7.1.dev.c51676437bc02ada78f3a0a0a2203c60.true'; expect(isServerVersionGreaterThanOrEqualTo(a, b)).toEqual(false); }); test('should consider the same versions equal', () => { const a = '4.7.1.dev.c51676437bc02ada78f3a0a0a2203c60.true'; const b = '4.7.1.dev.c51676437bc02ada78f3a0a0a2203c60.true'; expect(isServerVersionGreaterThanOrEqualTo(a, b)).toEqual(true); }); test('should consider different release versions (not greater than case)', () => { const a = '4.7.0.12.c51676437bc02ada78f3a0a0a2203c60.true'; const b = '4.7.1.12.c51676437bc02ada78f3a0a0a2203c60.true'; expect(isServerVersionGreaterThanOrEqualTo(a, b)).toEqual(false); }); test('should consider different release versions (greater than case)', () => { const a = '4.7.1.12.c51676437bc02ada78f3a0a0a2203c60.true'; const b = '4.7.0.12.c51676437bc02ada78f3a0a0a2203c60.true'; expect(isServerVersionGreaterThanOrEqualTo(a, b)).toEqual(true); }); test('should consider different build numbers unequal', () => { const a = '4.7.1.12.c51676437bc02ada78f3a0a0a2203c60.true'; const b = '4.7.1.13.c51676437bc02ada78f3a0a0a2203c60.true'; expect(isServerVersionGreaterThanOrEqualTo(a, b)).toEqual(false); }); test('should ignore different config hashes', () => { const a = '4.7.1.12.c51676437bc02ada78f3a0a0a2203c60.true'; const b = '4.7.1.12.c51676437bc02ada78f3a0a0a2203c61.true'; expect(isServerVersionGreaterThanOrEqualTo(a, b)).toEqual(true); }); test('should ignore different licensed statuses', () => { const a = '4.7.1.13.c51676437bc02ada78f3a0a0a2203c60.false'; const b = '4.7.1.12.c51676437bc02ada78f3a0a0a2203c60.true'; expect(isServerVersionGreaterThanOrEqualTo(a, b)).toEqual(true); }); });
4,511
0
petrpan-code/mattermost/mattermost/webapp/channels/src
petrpan-code/mattermost/mattermost/webapp/channels/src/utils/syntax_highlighting.test.ts
// Copyright (c) 2015-present Mattermost, Inc. All Rights Reserved. // See LICENSE.txt for license information. import hlJS from 'highlight.js/lib/core'; import javascript from 'highlight.js/lib/languages/javascript'; import plaintext from 'highlight.js/lib/languages/plaintext'; import swift from 'highlight.js/lib/languages/swift'; import {highlight} from './syntax_highlighting'; jest.mock('highlight.js/lib/core'); describe('utils/syntax_highlighting.tsx', () => { it('should register full name language', async () => { expect.assertions(1); await highlight('swift', ''); expect(hlJS.registerLanguage).toHaveBeenCalledWith('swift', swift); }); it('should register alias language', async () => { expect.assertions(1); await highlight('js', ''); expect(hlJS.registerLanguage).toHaveBeenCalledWith('javascript', javascript); }); it('should register WebVTT format as plaintext', async () => { expect.assertions(1); await highlight('vtt', ''); expect(hlJS.registerLanguage).toHaveBeenCalledWith('vtt', plaintext); }); });
4,513
0
petrpan-code/mattermost/mattermost/webapp/channels/src
petrpan-code/mattermost/mattermost/webapp/channels/src/utils/team_utils.test.ts
// Copyright (c) 2015-present Mattermost, Inc. All Rights Reserved. // See LICENSE.txt for license information. import type {Team} from '@mattermost/types/teams'; import {General} from 'mattermost-redux/constants'; import * as TeamUtils from 'utils/team_utils'; import {TestHelper as TH} from 'utils/test_helper'; describe('TeamUtils.filterAndSortTeamsByDisplayName', () => { const teamA = TH.getTeamMock({id: 'team_id_a', name: 'team-a', display_name: 'Team A', delete_at: 0}); const teamB = TH.getTeamMock({id: 'team_id_b', name: 'team-b', display_name: 'Team A', delete_at: 0}); const teamC = TH.getTeamMock({id: 'team_id_c', name: 'team-c', display_name: 'Team C', delete_at: null as unknown as number}); const teamD = TH.getTeamMock({id: 'team_id_d', name: 'team-d', display_name: 'Team D'}); const teamE = TH.getTeamMock({id: 'team_id_e', name: 'team-e', display_name: 'Team E', delete_at: 1}); const teamF = TH.getTeamMock({id: 'team_id_i', name: 'team-f', display_name: null as unknown as string}); const teamG = null as unknown as Team; test('should return correct sorted teams', () => { for (const data of [ {teams: [teamG], result: []}, {teams: [teamF, teamG], result: []}, {teams: [teamA, teamB, teamC, teamD, teamE], result: [teamA, teamB, teamC, teamD]}, {teams: [teamE, teamD, teamC, teamB, teamA], result: [teamA, teamB, teamC, teamD]}, {teams: [teamA, teamB, teamC, teamD, teamE, teamF, teamG], result: [teamA, teamB, teamC, teamD]}, {teams: [teamG, teamF, teamE, teamD, teamC, teamB, teamA], result: [teamA, teamB, teamC, teamD]}, ]) { expect(TeamUtils.filterAndSortTeamsByDisplayName(data.teams, General.DEFAULT_LOCALE)).toEqual(data.result); } }); test('should return correct sorted teams when teamsOrder is provided', () => { const teamsOrder = 'team_id_d,team_id_b,team_id_a,team_id_c'; for (const data of [ {teams: [teamG], result: []}, {teams: [teamF, teamG], result: []}, {teams: [teamA, teamB, teamC, teamD, teamE], result: [teamD, teamB, teamA, teamC]}, {teams: [teamE, teamD, teamC, teamB, teamA], result: [teamD, teamB, teamA, teamC]}, {teams: [teamA, teamB, teamC, teamD, teamE, teamF, teamG], result: [teamD, teamB, teamA, teamC]}, {teams: [teamG, teamF, teamE, teamD, teamC, teamB, teamA], result: [teamD, teamB, teamA, teamC]}, ]) { expect(TeamUtils.filterAndSortTeamsByDisplayName(data.teams, General.DEFAULT_LOCALE, teamsOrder)).toEqual(data.result); } }); });
4,516
0
petrpan-code/mattermost/mattermost/webapp/channels/src
petrpan-code/mattermost/mattermost/webapp/channels/src/utils/text_formatting.test.ts
// Copyright (c) 2015-present Mattermost, Inc. All Rights Reserved. // See LICENSE.txt for license information. import emojiRegex from 'emoji-regex'; import {getEmojiMap} from 'selectors/emojis'; import store from 'stores/redux_store'; import EmojiMap from 'utils/emoji_map'; import LinkOnlyRenderer from 'utils/markdown/link_only_renderer'; import { formatText, autolinkAtMentions, highlightSearchTerms, handleUnicodeEmoji, highlightCurrentMentions, highlightWithoutNotificationKeywords, parseSearchTerms, autolinkChannelMentions, } from 'utils/text_formatting'; import type {ChannelNamesMap} from 'utils/text_formatting'; const emptyEmojiMap = new EmojiMap(new Map()); describe('formatText', () => { test('jumbo emoji should be able to handle up to 3 spaces before the emoji character', () => { const emoji = ':)'; let spaces = ''; for (let i = 0; i < 3; i++) { spaces += ' '; const output = formatText(`${spaces}${emoji}`, {}, emptyEmojiMap); expect(output).toBe(`<span class="all-emoji"><p>${spaces}<span data-emoticon="slightly_smiling_face">${emoji}</span></p></span>`); } }); test('code blocks newlines are not converted into <br/> with inline markdown image in the post', () => { const output = formatText('```\nsome text\nsecond line\n```\n ![](https://example.com/image.png)', {}, emptyEmojiMap); expect(output).not.toContain('<br/>'); }); test('newlines in post text are converted into <br/> with inline markdown image in the post', () => { const output = formatText('some text\nand some more ![](https://example.com/image.png)', {}, emptyEmojiMap); expect(output).toContain('<br/>'); }); }); describe('autolinkAtMentions', () => { // testing to make sure @channel, @all & @here are setup properly to get highlighted correctly const mentionTestCases = [ 'channel', 'all', 'here', ]; function runSuccessfulAtMentionTests(leadingText = '', trailingText = '') { mentionTestCases.forEach((testCase) => { const mention = `@${testCase}`; const text = `${leadingText}${mention}${trailingText}`; const tokens = new Map(); const output = autolinkAtMentions(text, tokens); let expected = `${leadingText}$MM_ATMENTION0$${trailingText}`; // Deliberately remove all leading underscores since regex replaces underscore by treating it as non word boundary while (expected[0] === '_') { expected = expected.substring(1); } expect(output).toBe(expected); expect(tokens.get('$MM_ATMENTION0$').value).toBe(`<span data-mention="${testCase}">${mention}</span>`); }); } function runUnsuccessfulAtMentionTests(leadingText = '', trailingText = '') { mentionTestCases.forEach((testCase) => { const mention = `@${testCase}`; const text = `${leadingText}${mention}${trailingText}`; const tokens = new Map(); const output = autolinkAtMentions(text, tokens); expect(output).toBe(text); expect(tokens.get('$MM_ATMENTION0$')).toBeUndefined(); }); } function runUnsuccessfulAtMentionTestsMatchingNonSpecialMentions(leadingText = '', trailingText = '') { mentionTestCases.forEach((testCase) => { const mention = `@${testCase}`; const text = `${leadingText}${mention}${trailingText}`; const tokens = new Map(); const output = autolinkAtMentions(text, tokens); expect(output).toBe(`${leadingText}$MM_ATMENTION0$`); expect(tokens.get('$MM_ATMENTION0$').value).toBe(`<span data-mention="${testCase}${trailingText}">${mention}${trailingText}</span>`); }); } // cases where highlights should be successful test('@channel, @all, @here should highlight properly with no leading or trailing content', () => { runSuccessfulAtMentionTests(); }); test('@channel, @all, @here should highlight properly with a leading space', () => { runSuccessfulAtMentionTests(' ', ''); }); test('@channel, @all, @here should highlight properly with a trailing space', () => { runSuccessfulAtMentionTests('', ' '); }); test('@channel, @all, @here should highlight properly with a leading period', () => { runSuccessfulAtMentionTests('.', ''); }); test('@channel, @all, @here should highlight properly with a trailing period', () => { runSuccessfulAtMentionTests('', '.'); }); test('@channel, @all, @here should highlight properly with multiple leading and trailing periods', () => { runSuccessfulAtMentionTests('...', '...'); }); test('@channel, @all, @here should highlight properly with a leading dash', () => { runSuccessfulAtMentionTests('-', ''); }); test('@channel, @all, @here should highlight properly with a trailing dash', () => { runSuccessfulAtMentionTests('', '-'); }); test('@channel, @all, @here should highlight properly with multiple leading and trailing dashes', () => { runSuccessfulAtMentionTests('---', '---'); }); test('@channel, @all, @here should highlight properly with a trailing underscore', () => { runSuccessfulAtMentionTests('', '____'); }); test('@channel, @all, @here should highlight properly with multiple trailing underscores', () => { runSuccessfulAtMentionTests('', '____'); }); test('@channel, @all, @here should highlight properly within a typical sentance', () => { runSuccessfulAtMentionTests('This is a typical sentance, ', ' check out this sentance!'); }); test('@channel, @all, @here should highlight with a leading underscore', () => { runSuccessfulAtMentionTests('_'); }); // cases where highlights should be unsuccessful test('@channel, @all, @here should not highlight when the last part of a word', () => { runUnsuccessfulAtMentionTests('testing'); }); test('@channel, @all, @here should not highlight when in the middle of a word', () => { runUnsuccessfulAtMentionTests('test', 'ing'); }); // cases where highlights should be unsucessful but a non special mention should be created test('@channel, @all, @here should be treated as non special mentions with trailing period followed by a word', () => { runUnsuccessfulAtMentionTestsMatchingNonSpecialMentions('Hello ', '.developers'); }); test('@channel, @all, @here should be treated as non special mentions with multiple trailing periods followed by a word', () => { runUnsuccessfulAtMentionTestsMatchingNonSpecialMentions('Hello ', '...developers'); }); test('@channel, @all, @here should be treated as non special mentions with trailing dash followed by a word', () => { runUnsuccessfulAtMentionTestsMatchingNonSpecialMentions('Hello ', '-developers'); }); test('@channel, @all, @here should be treated as non special mentions with multiple trailing dashes followed by a word', () => { runUnsuccessfulAtMentionTestsMatchingNonSpecialMentions('Hello ', '---developers'); }); test('@channel, @all, @here should be treated as non special mentions with trailing underscore followed by a word', () => { runUnsuccessfulAtMentionTestsMatchingNonSpecialMentions('Hello ', '_developers'); }); test('@channel, @all, @here should be treated as non special mentions with multiple trailing underscores followed by a word', () => { runUnsuccessfulAtMentionTestsMatchingNonSpecialMentions('Hello ', '___developers'); }); }); describe('highlightSearchTerms', () => { test('hashtags should highlight case-insensitively', () => { const text = '$MM_HASHTAG0$'; const tokens = new Map( [['$MM_HASHTAG0$', { hashtag: 'Test', originalText: '#Test', value: '<a class="mention-link" href="#" data-hashtag="#Test">#Test</a>', }]], ); const searchPatterns = [ { pattern: /(\W|^)(#test)\b/gi, term: '#test', }, ]; const output = highlightSearchTerms(text, tokens, searchPatterns); expect(output).toBe('$MM_SEARCHTERM1$'); expect(tokens.get('$MM_SEARCHTERM1$')!.value).toBe('<span class="search-highlight">$MM_HASHTAG0$</span>'); }); }); describe('autolink channel mentions', () => { test('link a channel mention', () => { const mention = '~test-channel'; const leadingText = 'pre blah blah '; const trailingText = ' post blah blah'; const text = `${leadingText}${mention}${trailingText}`; const tokens = new Map(); const channelNamesMap: ChannelNamesMap = { 'test-channel': { team_name: 'ad-1', display_name: 'Test Channel', }, }; const output = autolinkChannelMentions(text, tokens, channelNamesMap); expect(output).toBe(`${leadingText}$MM_CHANNELMENTION0$${trailingText}`); expect(tokens.get('$MM_CHANNELMENTION0$').value).toBe('<a class="mention-link" href="/ad-1/channels/test-channel" data-channel-mention-team="ad-1" data-channel-mention="test-channel">~Test Channel</a>'); }); }); describe('handleUnicodeEmoji', () => { const emojiMap = getEmojiMap(store.getState()); const UNICODE_EMOJI_REGEX = emojiRegex(); const tests = [ { description: 'should replace supported emojis with an image', text: '👍', output: '<span data-emoticon="+1">👍</span>', }, { description: 'should not replace unsupported emojis with an image', text: '😮‍💨', // Note, this test will fail as soon as this emoji gets a corresponding image output: '<span class="emoticon emoticon--unicode">😮‍💨</span>', }, { description: 'should correctly match gendered emojis', text: '🙅‍♀️🙅‍♂️', output: '<span data-emoticon="woman-gesturing-no">🙅‍♀️</span><span data-emoticon="man-gesturing-no">🙅‍♂️</span>', }, { description: 'should correctly match flags', text: '🏳️🇨🇦🇫🇮', output: '<span data-emoticon="waving_white_flag">🏳️</span><span data-emoticon="flag-ca">🇨🇦</span><span data-emoticon="flag-fi">🇫🇮</span>', }, { description: 'should correctly match emojis with skin tones', text: '👍🏿👍🏻', output: '<span data-emoticon="+1_dark_skin_tone">👍🏿</span><span data-emoticon="+1_light_skin_tone">👍🏻</span>', }, { description: 'should correctly match more emojis with skin tones', text: '✊🏻✊🏿', output: '<span data-emoticon="fist_light_skin_tone">✊🏻</span><span data-emoticon="fist_dark_skin_tone">✊🏿</span>', }, { description: 'should correctly match combined emojis', text: '👨‍👩‍👧‍👦👨‍❤️‍👨', output: '<span data-emoticon="man-woman-girl-boy">👨‍👩‍👧‍👦</span><span data-emoticon="man-heart-man">👨‍❤️‍👨</span>', }, ]; for (const t of tests) { test(t.description, () => { const output = handleUnicodeEmoji(t.text, emojiMap, UNICODE_EMOJI_REGEX); expect(output).toBe(t.output); }); } test('without emojiMap, should work as unsupported emoji', () => { const output = handleUnicodeEmoji('👍', undefined as unknown as EmojiMap, UNICODE_EMOJI_REGEX); expect(output).toBe('<span class="emoticon emoticon--unicode">👍</span>'); }); }); describe('linkOnlyMarkdown', () => { const options = {markdown: false, renderer: new LinkOnlyRenderer()}; test('link without a title', () => { const text = 'Do you like https://www.mattermost.com?'; const output = formatText(text, options, emptyEmojiMap); expect(output).toBe( 'Do you like <a class="theme markdown__link" href="https://www.mattermost.com" target="_blank">' + 'https://www.mattermost.com</a>?'); }); test('link with a title', () => { const text = 'Do you like [Mattermost](https://www.mattermost.com)?'; const output = formatText(text, options, emptyEmojiMap); expect(output).toBe( 'Do you like <a class="theme markdown__link" href="https://www.mattermost.com" target="_blank">' + 'Mattermost</a>?'); }); test('link with header signs to skip', () => { const text = '#### Do you like [Mattermost](https://www.mattermost.com)?'; const output = formatText(text, options, emptyEmojiMap); expect(output).toBe( 'Do you like <a class="theme markdown__link" href="https://www.mattermost.com" target="_blank">' + 'Mattermost</a>?'); }); }); describe('highlightCurrentMentions', () => { const tokens = new Map(); const mentionKeys = [ {key: '메터모스트'}, // Korean word {key: 'マッターモスト'}, // Japanese word {key: 'маттермост'}, // Russian word {key: 'Mattermost'}, // Latin word ]; it('should find and match Korean, Japanese, latin and Russian words', () => { const text = '메터모스트, notinkeys, マッターモスト, маттермост!, Mattermost, notinkeys'; const highlightedText = highlightCurrentMentions(text, tokens, mentionKeys); const expectedOutput = '$MM_SELFMENTION0$, notinkeys, $MM_SELFMENTION1$, $MM_SELFMENTION2$!, $MM_SELFMENTION3$, notinkeys'; // note that the string output $MM_SELFMENTION{idx} will be used by doFormatText to add the highlight later in the format process expect(highlightedText).toContain(expectedOutput); }); }); describe('highlightWithoutNotificationKeywords', () => { test('should replace highlight keywords with tokens', () => { const text = 'This is a test message with some keywords'; const tokens = new Map(); const highlightKeys = [ {key: 'test message'}, {key: 'keywords'}, ]; const expectedOutput = 'This is a $MM_HIGHLIGHTKEYWORD0$ with some $MM_HIGHLIGHTKEYWORD1$'; const expectedTokens = new Map([ ['$MM_HIGHLIGHTKEYWORD0$', { value: '<span class="non-notification-highlight">test message</span>', originalText: 'test message', }], ['$MM_HIGHLIGHTKEYWORD1$', { value: '<span class="non-notification-highlight">keywords</span>', originalText: 'keywords', }], ]); const output = highlightWithoutNotificationKeywords(text, tokens, highlightKeys); expect(output).toBe(expectedOutput); expect(tokens).toEqual(expectedTokens); }); test('should handle empty highlightKeys array', () => { const text = 'This is a test message'; const tokens = new Map(); const highlightKeys = [] as Array<{key: string}>; const expectedOutput = 'This is a test message'; const expectedTokens = new Map(); const output = highlightWithoutNotificationKeywords(text, tokens, highlightKeys); expect(output).toBe(expectedOutput); expect(tokens).toEqual(expectedTokens); }); test('should handle empty text', () => { const text = ''; const tokens = new Map(); const highlightKeys = [ {key: 'test'}, {key: 'keywords'}, ]; const expectedOutput = ''; const expectedTokens = new Map(); const output = highlightWithoutNotificationKeywords(text, tokens, highlightKeys); expect(output).toBe(expectedOutput); expect(tokens).toEqual(expectedTokens); }); test('should handle Chinese, Korean, Russian, and Japanese words', () => { const text = 'This is a test message with some keywords: привет, こんにちは, 안녕하세요, 你好'; const tokens = new Map(); const highlightKeys = [ {key: 'こんにちは'}, // Japanese hello {key: '안녕하세요'}, // Korean hello {key: 'привет'}, // Russian hello {key: '你好'}, // Chinese hello ]; const expectedOutput = 'This is a test message with some keywords: $MM_HIGHLIGHTKEYWORD0$, $MM_HIGHLIGHTKEYWORD1$, $MM_HIGHLIGHTKEYWORD2$, $MM_HIGHLIGHTKEYWORD3$'; const expectedTokens = new Map([ ['$MM_HIGHLIGHTKEYWORD0$', { value: '<span class="non-notification-highlight">привет</span>', originalText: 'привет', }], ['$MM_HIGHLIGHTKEYWORD1$', { value: '<span class="non-notification-highlight">こんにちは</span>', originalText: 'こんにちは', }], ['$MM_HIGHLIGHTKEYWORD2$', { value: '<span class="non-notification-highlight">안녕하세요</span>', originalText: '안녕하세요', }], ['$MM_HIGHLIGHTKEYWORD3$', { value: '<span class="non-notification-highlight">你好</span>', originalText: '你好', }], ]); const output = highlightWithoutNotificationKeywords(text, tokens, highlightKeys); expect(output).toBe(expectedOutput); expect(tokens).toEqual(expectedTokens); }); }); describe('parseSearchTerms', () => { const tests = [ { description: 'no input', input: undefined as unknown as string, expected: [], }, { description: 'empty input', input: '', expected: [], }, { description: 'simple word', input: 'someword', expected: ['someword'], }, { description: 'simple phrase', input: '"some phrase"', expected: ['some phrase'], }, { description: 'empty phrase', input: '""', expected: [], }, { description: 'phrase before word', input: '"some phrase" someword', expected: ['some phrase', 'someword'], }, { description: 'word before phrase', input: 'someword "some phrase"', expected: ['someword', 'some phrase'], }, { description: 'words and phrases', input: 'someword "some phrase" otherword "other phrase"', expected: ['someword', 'some phrase', 'otherword', 'other phrase'], }, { description: 'with search flags after', input: 'someword "some phrase" from:someone in:somechannel', expected: ['someword', 'some phrase'], }, { description: 'with search flags before', input: 'from:someone in: channel someword "some phrase"', expected: ['someword', 'some phrase'], }, { description: 'with search flags before and after', input: 'from:someone someword "some phrase" in:somechannel', expected: ['someword', 'some phrase'], }, { description: 'with date search flags before and after', input: 'on:1970-01-01 someword "some phrase" after:1970-01-01 before: 1970-01-01', expected: ['someword', 'some phrase'], }, { description: 'with negative search flags after', input: 'someword "some phrase" -from:someone -in:somechannel', expected: ['someword', 'some phrase'], }, { description: 'with negative search flags before', input: '-from:someone -in: channel someword "some phrase"', expected: ['someword', 'some phrase'], }, { description: 'with negative search flags before and after', input: '-from:someone someword "some phrase" -in:somechannel', expected: ['someword', 'some phrase'], }, { description: 'with negative date search flags before and after', input: '-on:1970-01-01 someword "some phrase" -after:1970-01-01 -before: 1970-01-01', expected: ['someword', 'some phrase'], }, ]; for (const t of tests) { test(t.description, () => { const output = parseSearchTerms(t.input); expect(output).toStrictEqual(t.expected); }); } });
4,518
0
petrpan-code/mattermost/mattermost/webapp/channels/src
petrpan-code/mattermost/mattermost/webapp/channels/src/utils/text_formatting_at_mentions.test.ts
// Copyright (c) 2015-present Mattermost, Inc. All Rights Reserved. // See LICENSE.txt for license information. import EmojiMap from 'utils/emoji_map'; import * as TextFormatting from 'utils/text_formatting'; interface StringsTest { actual: string; expected: string; label: string; } const emptyEmojiMap = new EmojiMap(new Map()); describe('TextFormatting.AtMentions', () => { describe('At mentions', () => { const tests: StringsTest[] = [ { actual: TextFormatting.autolinkAtMentions('@user', new Map()), expected: '$MM_ATMENTION0$', label: 'should replace mention with token', }, { actual: TextFormatting.autolinkAtMentions('abc"@user"def', new Map()), expected: 'abc"$MM_ATMENTION0$"def', label: 'should replace mention surrounded by punctuation with token', }, { actual: TextFormatting.autolinkAtMentions('@user1 @user2', new Map()), expected: '$MM_ATMENTION0$ $MM_ATMENTION1$', label: 'should replace multiple mentions with tokens', }, { actual: TextFormatting.autolinkAtMentions('@user1/@user2/@user3', new Map()), expected: '$MM_ATMENTION0$/$MM_ATMENTION1$/$MM_ATMENTION2$', label: 'should replace multiple mentions with tokens', }, { actual: TextFormatting.autolinkAtMentions('@us_-e.r', new Map()), expected: '$MM_ATMENTION0$', label: 'should replace multiple mentions containing punctuation with token', }, { actual: TextFormatting.autolinkAtMentions('@user.', new Map()), expected: '$MM_ATMENTION0$', label: 'should capture trailing punctuation as part of mention', }, { actual: TextFormatting.autolinkAtMentions('@foo.com @bar.com', new Map()), expected: '$MM_ATMENTION0$ $MM_ATMENTION1$', label: 'should capture two at mentions with space in between', }, { actual: TextFormatting.autolinkAtMentions('@[email protected]', new Map()), expected: '$MM_ATMENTION0$$MM_ATMENTION1$', label: 'should capture two at mentions without space in between', }, { actual: TextFormatting.autolinkAtMentions('@[email protected]@baz.com', new Map()), expected: '$MM_ATMENTION0$$MM_ATMENTION1$$MM_ATMENTION2$', label: 'should capture multiple at mentions without space in between', }, ]; tests.forEach((test: StringsTest) => { it(test.label, () => expect(test.actual).toBe(test.expected)); }); }); it('Not at mentions', () => { expect(TextFormatting.autolinkAtMentions('user@host', new Map())).toEqual('user@host'); expect(TextFormatting.autolinkAtMentions('[email protected]', new Map())).toEqual('[email protected]'); expect(TextFormatting.autolinkAtMentions('@', new Map())).toEqual('@'); expect(TextFormatting.autolinkAtMentions('@ ', new Map())).toEqual('@ '); expect(TextFormatting.autolinkAtMentions(':@', new Map())).toEqual(':@'); }); it('Highlighted at mentions', () => { expect( TextFormatting.formatText('@user', {atMentions: true, mentionKeys: [{key: '@user'}]}, emptyEmojiMap).trim(), ).toEqual( '<p><span class="mention--highlight"><span data-mention="user">@user</span></span></p>', ); expect( TextFormatting.formatText('@channel', {atMentions: true, mentionKeys: [{key: '@channel'}]}, emptyEmojiMap).trim(), ).toEqual( '<p><span class="mention--highlight"><span data-mention="channel">@channel</span></span></p>', ); expect(TextFormatting.formatText('@all', {atMentions: true, mentionKeys: [{key: '@all'}]}, emptyEmojiMap).trim(), ).toEqual( '<p><span class="mention--highlight"><span data-mention="all">@all</span></span></p>', ); expect(TextFormatting.formatText('@USER', {atMentions: true, mentionKeys: [{key: '@user'}]}, emptyEmojiMap).trim(), ).toEqual( '<p><span class="mention--highlight"><span data-mention="USER">@USER</span></span></p>', ); expect(TextFormatting.formatText('@CHanNEL', {atMentions: true, mentionKeys: [{key: '@channel'}]}, emptyEmojiMap).trim(), ).toEqual('<p><span class="mention--highlight"><span data-mention="CHanNEL">@CHanNEL</span></span></p>', ); expect(TextFormatting.formatText('@ALL', {atMentions: true, mentionKeys: [{key: '@all'}]}, emptyEmojiMap).trim(), ).toEqual('<p><span class="mention--highlight"><span data-mention="ALL">@ALL</span></span></p>', ); expect(TextFormatting.formatText('@foo.com', {atMentions: true, mentionKeys: [{key: '@foo.com'}]}, emptyEmojiMap).trim(), ).toEqual( '<p><span class="mention--highlight"><span data-mention="foo.com">@foo.com</span></span></p>', ); expect(TextFormatting.formatText('@foo.com @bar.com', {atMentions: true, mentionKeys: [{key: '@foo.com'}, {key: '@bar.com'}]}, emptyEmojiMap).trim(), ).toEqual('<p><span class="mention--highlight"><span data-mention="foo.com">@foo.com</span></span> <span class="mention--highlight"><span data-mention="bar.com">@bar.com</span></span></p>', ); expect(TextFormatting.formatText('@[email protected]', {atMentions: true, mentionKeys: [{key: '@foo.com'}, {key: '@bar.com'}]}, emptyEmojiMap).trim(), ).toEqual('<p><span class="mention--highlight"><span data-mention="foo.com">@foo.com</span></span><span class="mention--highlight"><span data-mention="bar.com">@bar.com</span></span></p>', ); }); describe('Mix highlight at mentions', () => { const tests: StringsTest[] = [ { actual: TextFormatting.formatText('@foo.com @bar.com', {atMentions: true, mentionKeys: [{key: '@foo.com'}]}, emptyEmojiMap).trim(), expected: '<p><span class="mention--highlight"><span data-mention="foo.com">@foo.com</span></span> <span data-mention="bar.com">@bar.com</span></p>', label: 'should highlight first at mention, with space in between', }, { actual: TextFormatting.formatText('@foo.com @bar.com', {atMentions: true, mentionKeys: [{key: '@bar.com'}]}, emptyEmojiMap).trim(), expected: '<p><span data-mention="foo.com">@foo.com</span> <span class="mention--highlight"><span data-mention="bar.com">@bar.com</span></span></p>', label: 'should highlight second at mention, with space in between', }, { actual: TextFormatting.formatText('@[email protected]', {atMentions: true, mentionKeys: [{key: '@foo.com'}]}, emptyEmojiMap).trim(), expected: '<p><span class="mention--highlight"><span data-mention="foo.com">@foo.com</span></span><span data-mention="bar.com">@bar.com</span></p>', label: 'should highlight first at mention, without space in between', }, { actual: TextFormatting.formatText('@[email protected]', {atMentions: true, mentionKeys: [{key: '@bar.com'}]}, emptyEmojiMap).trim(), expected: '<p><span data-mention="foo.com">@foo.com</span><span class="mention--highlight"><span data-mention="bar.com">@bar.com</span></span></p>', label: 'should highlight second at mention, without space in between', }, { actual: TextFormatting.formatText('@[email protected]', {atMentions: true, mentionKeys: [{key: '@user'}]}, emptyEmojiMap).trim(), expected: '<p><span data-mention="foo.com">@foo.com</span><span data-mention="bar.com">@bar.com</span></p>', label: 'should not highlight any at mention', }, ]; tests.forEach((test: StringsTest) => { it(test.label, () => expect(test.actual).toBe(test.expected)); }); }); });
4,519
0
petrpan-code/mattermost/mattermost/webapp/channels/src
petrpan-code/mattermost/mattermost/webapp/channels/src/utils/text_formatting_channel_links.test.ts
// Copyright (c) 2015-present Mattermost, Inc. All Rights Reserved. // See LICENSE.txt for license information. import EmojiMap from 'utils/emoji_map'; import {TestHelper as TH} from 'utils/test_helper'; import * as TextFormatting from 'utils/text_formatting'; const emojiMap = new EmojiMap(new Map()); describe('TextFormatting.ChannelLinks', () => { test('Not channel links', () => { expect( TextFormatting.formatText('~123', {}, emojiMap).trim(), ).toBe( '<p>~123</p>', ); expect( TextFormatting.formatText('~town-square', {}, emojiMap).trim(), ).toBe( '<p>~town-square</p>', ); }); describe('Channel links', () => { afterEach(() => { delete (window as any).basename; }); test('should link ~town-square', () => { expect( TextFormatting.formatText('~town-square', { channelNamesMap: {'town-square': 'Town Square'}, team: TH.getTeamMock({name: 'myteam'}), }, emojiMap).trim(), ).toBe( '<p><a class="mention-link" href="/myteam/channels/town-square" data-channel-mention="town-square">~Town Square</a></p>', ); }); test('should link ~town-square followed by a period', () => { expect( TextFormatting.formatText('~town-square.', { channelNamesMap: {'town-square': 'Town Square'}, team: TH.getTeamMock({name: 'myteam'}), }, emojiMap).trim(), ).toBe( '<p><a class="mention-link" href="/myteam/channels/town-square" data-channel-mention="town-square">~Town Square</a>.</p>', ); }); test('should link ~town-square, with display_name an HTML string', () => { expect( TextFormatting.formatText('~town-square', { channelNamesMap: {'town-square': '<b>Reception</b>'}, team: TH.getTeamMock({name: 'myteam'}), }, emojiMap).trim(), ).toBe( '<p><a class="mention-link" href="/myteam/channels/town-square" data-channel-mention="town-square">~&lt;b&gt;Reception&lt;/b&gt;</a></p>', ); }); test('should link ~town-square, with a basename defined', () => { window.basename = '/subpath'; expect( TextFormatting.formatText('~town-square', { channelNamesMap: {'town-square': '<b>Reception</b>'}, team: TH.getTeamMock({name: 'myteam'}), }, emojiMap).trim(), ).toBe( '<p><a class="mention-link" href="/subpath/myteam/channels/town-square" data-channel-mention="town-square">~&lt;b&gt;Reception&lt;/b&gt;</a></p>', ); }); test('should link in brackets', () => { expect( TextFormatting.formatText('(~town-square)', { channelNamesMap: {'town-square': 'Town Square'}, team: TH.getTeamMock({name: 'myteam'}), }, emojiMap).trim(), ).toBe( '<p>(<a class="mention-link" href="/myteam/channels/town-square" data-channel-mention="town-square">~Town Square</a>)</p>', ); }); }); describe('invalid channel links', () => { test('should not link when a ~ is in the middle of a word', () => { expect( TextFormatting.formatText('aa~town-square', { channelNamesMap: {'town-square': 'Town Square'}, team: TH.getTeamMock({name: 'myteam'}), }, emojiMap).trim(), ).toBe( '<p>aa~town-square</p>', ); }); }); });
4,520
0
petrpan-code/mattermost/mattermost/webapp/channels/src
petrpan-code/mattermost/mattermost/webapp/channels/src/utils/text_formatting_email.test.ts
// Copyright (c) 2015-present Mattermost, Inc. All Rights Reserved. // See LICENSE.txt for license information. import EmojiMap from 'utils/emoji_map'; import * as TextFormatting from 'utils/text_formatting'; const emojiMap = new EmojiMap(new Map()); describe('TextFormatting.Emails', () => { it('Valid email addresses', () => { expect(TextFormatting.formatText('[email protected]', {}, emojiMap).trim()).toBe( '<p><a class="theme" href="mailto:[email protected]" rel="noreferrer" target="_blank">[email protected]</a></p>', ); expect(TextFormatting.formatText('[email protected]', {}, emojiMap).trim()).toBe( '<p><a class="theme" href="mailto:[email protected]" rel="noreferrer" target="_blank">[email protected]</a></p>', ); expect(TextFormatting.formatText('[email protected]', {}, emojiMap).trim()).toBe( '<p><a class="theme" href="mailto:[email protected]" rel="noreferrer" target="_blank">[email protected]</a></p>', ); expect(TextFormatting.formatText('[email protected]', {}, emojiMap).trim()).toBe( '<p><a class="theme" href="mailto:[email protected]" rel="noreferrer" target="_blank">[email protected]</a></p>', ); expect(TextFormatting.formatText('[email protected]', {}, emojiMap).trim()).toBe( '<p><a class="theme" href="mailto:[email protected]" rel="noreferrer" target="_blank">[email protected]</a></p>', ); expect(TextFormatting.formatText('[email protected]', {}, emojiMap).trim()).toBe( '<p><a class="theme" href="mailto:[email protected]" rel="noreferrer" target="_blank">[email protected]</a></p>', ); expect(TextFormatting.formatText('[email protected]', {}, emojiMap).trim()).toBe( '<p><a class="theme" href="mailto:[email protected]" rel="noreferrer" target="_blank">[email protected]</a></p>', ); expect(TextFormatting.formatText('[email protected]', {}, emojiMap).trim()).toBe( '<p><a class="theme" href="mailto:[email protected]" rel="noreferrer" target="_blank">[email protected]</a></p>', ); expect(TextFormatting.formatText('[email protected]', {}, emojiMap).trim()).toBe( '<p><a class="theme" href="mailto:[email protected]" rel="noreferrer" target="_blank">[email protected]</a></p>', ); }); it('Should be valid, but matching GitHub', () => { expect(TextFormatting.formatText('[email protected]', {}, emojiMap).trim()).toBe( '<p>[email protected]</p>', ); expect(TextFormatting.formatText('email@[123.123.123.123]', {}, emojiMap).trim()).toBe( '<p>email@[123.123.123.123]</p>', ); expect(TextFormatting.formatText('"email"@domain.com', {}, emojiMap).trim()).toBe( '<p>&quot;email&quot;@domain.com</p>', ); }); it('Should be valid, but broken due to Markdown parsing happening before email autolinking', () => { expect(TextFormatting.formatText('[email protected]', {}, emojiMap).trim()).toBe( '<p><strong>___</strong>@domain.com</p>', ); }); it('Not valid emails', () => { expect(TextFormatting.formatText('plainaddress', {}, emojiMap).trim()).toBe( '<p>plainaddress</p>', ); expect(TextFormatting.formatText('#@%^%#$@#$@#.com', {}, emojiMap).trim()).toBe( '<p>#@%^%#$@#$@#.com</p>', ); expect(TextFormatting.formatText('@domain.com', {}, emojiMap).trim()).toBe( '<p>@domain.com</p>', ); expect(TextFormatting.formatText('Joe Smith <[email protected]>', {}, emojiMap).trim()).toBe( '<p>Joe Smith <a class="theme markdown__link" href="mailto:[email protected]" rel="noreferrer" target="_blank">[email protected]</a></p>', ); expect(TextFormatting.formatText('email.domain.com', {}, emojiMap).trim()).toBe( '<p>email.domain.com</p>', ); expect(TextFormatting.formatText('[email protected]', {}, emojiMap).trim()).toBe( '<p>[email protected]</p>', ); }); it('Should be invalid, but matching GitHub', () => { expect(TextFormatting.formatText('email@[email protected]', {}, emojiMap).trim()).toBe( '<p>email@<a class="theme" href="mailto:[email protected]" rel="noreferrer" target="_blank">[email protected]</a></p>', ); }); it('Should be invalid, but broken', () => { expect(TextFormatting.formatText('email@[email protected]', {}, emojiMap).trim()).toBe( '<p>email@<a class="theme" href="mailto:[email protected]" rel="noreferrer" target="_blank">[email protected]</a></p>', ); }); });
4,521
0
petrpan-code/mattermost/mattermost/webapp/channels/src
petrpan-code/mattermost/mattermost/webapp/channels/src/utils/text_formatting_hashtags.test.ts
// Copyright (c) 2015-present Mattermost, Inc. All Rights Reserved. // See LICENSE.txt for license information. import EmojiMap from 'utils/emoji_map'; import * as TextFormatting from 'utils/text_formatting'; const emojiMap = new EmojiMap(new Map()); describe('TextFormatting.Hashtags with default setting', () => { it('Not hashtags', () => { expect(TextFormatting.formatText('# hashtag', {}, emojiMap).trim()).toBe( '<h1 class="markdown__heading">hashtag</h1>', ); expect(TextFormatting.formatText('#ab', {}, emojiMap).trim()).toBe( '<p>#ab</p>', ); expect(TextFormatting.formatText('#123test', {}, emojiMap).trim()).toBe( '<p>#123test</p>', ); }); it('Hashtags', () => { expect(TextFormatting.formatText('#test', {}, emojiMap).trim()).toBe( "<p><a class='mention-link' href='#' data-hashtag='#test'>#test</a></p>", ); expect(TextFormatting.formatText('#test123', {}, emojiMap).trim()).toBe( "<p><a class='mention-link' href='#' data-hashtag='#test123'>#test123</a></p>", ); expect(TextFormatting.formatText('#test-test', {}, emojiMap).trim()).toBe( "<p><a class='mention-link' href='#' data-hashtag='#test-test'>#test-test</a></p>", ); expect(TextFormatting.formatText('#test_test', {}, emojiMap).trim()).toBe( "<p><a class='mention-link' href='#' data-hashtag='#test_test'>#test_test</a></p>", ); expect(TextFormatting.formatText('#test.test', {}, emojiMap).trim()).toBe( "<p><a class='mention-link' href='#' data-hashtag='#test.test'>#test.test</a></p>", ); expect(TextFormatting.formatText('#test1/#test2', {}, emojiMap).trim()).toBe( "<p><a class='mention-link' href='#' data-hashtag='#test1'>#test1</a>/<a class='mention-link' href='#' data-hashtag='#test2'>#test2</a></p>", ); expect(TextFormatting.formatText('(#test)', {}, emojiMap).trim()).toBe( "<p>(<a class='mention-link' href='#' data-hashtag='#test'>#test</a>)</p>", ); expect(TextFormatting.formatText('#test-', {}, emojiMap).trim()).toBe( "<p><a class='mention-link' href='#' data-hashtag='#test'>#test</a>-</p>", ); expect(TextFormatting.formatText('#test.', {}, emojiMap).trim()).toBe( "<p><a class='mention-link' href='#' data-hashtag='#test'>#test</a>.</p>", ); expect(TextFormatting.formatText('This is a sentence #test containing a hashtag', {}, emojiMap).trim()).toBe( "<p>This is a sentence <a class='mention-link' href='#' data-hashtag='#test'>#test</a> containing a hashtag</p>", ); }); it('Formatted hashtags', () => { expect(TextFormatting.formatText('*#test*', {}, emojiMap).trim()).toBe( "<p><em><a class='mention-link' href='#' data-hashtag='#test'>#test</a></em></p>", ); expect(TextFormatting.formatText('_#test_', {}, emojiMap).trim()).toBe( "<p><em><a class='mention-link' href='#' data-hashtag='#test'>#test</a></em></p>", ); expect(TextFormatting.formatText('**#test**', {}, emojiMap).trim()).toBe( "<p><strong><a class='mention-link' href='#' data-hashtag='#test'>#test</a></strong></p>", ); expect(TextFormatting.formatText('__#test__', {}, emojiMap).trim()).toBe( "<p><strong><a class='mention-link' href='#' data-hashtag='#test'>#test</a></strong></p>", ); expect(TextFormatting.formatText('~~#test~~', {}, emojiMap).trim()).toBe( "<p><del><a class='mention-link' href='#' data-hashtag='#test'>#test</a></del></p>", ); expect(TextFormatting.formatText('`#test`', {}, emojiMap).trim()).toBe( '<p>' + '<span class="codespan__pre-wrap">' + '<code>' + '#test' + '</code>' + '</span>' + '</p>', ); expect(TextFormatting.formatText('[this is a link #test](example.com)', {}, emojiMap).trim()).toBe( '<p><a class="theme markdown__link" href="http://example.com" rel="noreferrer" target="_blank">this is a link #test</a></p>', ); }); it('Searching for hashtags', () => { expect(TextFormatting.formatText('#test', {searchTerm: 'test'}, emojiMap).trim()).toBe( '<p><span class="search-highlight"><a class=\'mention-link\' href=\'#\' data-hashtag=\'#test\'>#test</a></span></p>', ); expect(TextFormatting.formatText('#test', {searchTerm: '#test'}, emojiMap).trim()).toBe( '<p><span class="search-highlight"><a class=\'mention-link\' href=\'#\' data-hashtag=\'#test\'>#test</a></span></p>', ); expect(TextFormatting.formatText('#foo/#bar', {searchTerm: '#foo'}, emojiMap).trim()).toBe( '<p><span class="search-highlight"><a class=\'mention-link\' href=\'#\' data-hashtag=\'#foo\'>#foo</a></span>/<a class=\'mention-link\' href=\'#\' data-hashtag=\'#bar\'>#bar</a></p>', ); expect(TextFormatting.formatText('#foo/#bar', {searchTerm: 'bar'}, emojiMap).trim()).toBe( '<p><a class=\'mention-link\' href=\'#\' data-hashtag=\'#foo\'>#foo</a>/<span class="search-highlight"><a class=\'mention-link\' href=\'#\' data-hashtag=\'#bar\'>#bar</a></span></p>', ); expect(TextFormatting.formatText('not#test', {searchTerm: '#test'}, emojiMap).trim()).toBe( '<p>not#test</p>', ); }); it('Potential hashtags with other entities nested', () => { expect(TextFormatting.formatText('#@test', {}, emojiMap).trim()).toBe( '<p>#@test</p>', ); let options: TextFormatting.TextFormattingOptions = { atMentions: true, }; expect(TextFormatting.formatText('#@test', options, emojiMap).trim()).toBe( '<p>#<span data-mention="test">@test</span></p>', ); expect(TextFormatting.formatText('#~test', {}, emojiMap).trim()).toBe( '<p>#~test</p>', ); options = { channelNamesMap: { test: {display_name: 'Test Channel'}, }, team: {id: 'abcd', name: 'abcd', display_name: 'Alphabet'}, }; expect(TextFormatting.formatText('#~test', options, emojiMap).trim()).toBe( '<p>#<a class="mention-link" href="/abcd/channels/test" data-channel-mention="test">~Test Channel</a></p>', ); expect(TextFormatting.formatText('#:mattermost:', {}, emojiMap).trim()).toBe( '<p>#<span data-emoticon="mattermost">:mattermost:</span></p>', ); expect(TextFormatting.formatText('#[email protected]', {}, emojiMap).trim()).toBe( "<p><a class='mention-link' href='#' data-hashtag='#[email protected]'>#[email protected]</a></p>", ); }); }); describe('TextFormatting.Hashtags with various settings', () => { it('Boundary of MinimumHashtagLength', () => { expect(TextFormatting.formatText('#疑問', {minimumHashtagLength: 2}, emojiMap).trim()).toBe( "<p><a class='mention-link' href='#' data-hashtag='#疑問'>#疑問</a></p>", ); expect(TextFormatting.formatText('This is a sentence #疑問 containing a hashtag', {minimumHashtagLength: 2}, emojiMap).trim()).toBe( "<p>This is a sentence <a class='mention-link' href='#' data-hashtag='#疑問'>#疑問</a> containing a hashtag</p>", ); expect(TextFormatting.formatText('#疑', {minimumHashtagLength: 2}, emojiMap).trim()).toBe( '<p>#疑</p>', ); expect(TextFormatting.formatText('This is a sentence #疑 containing a hashtag', {minimumHashtagLength: 2}, emojiMap).trim()).toBe( '<p>This is a sentence #疑 containing a hashtag</p>', ); }); });
4,522
0
petrpan-code/mattermost/mattermost/webapp/channels/src
petrpan-code/mattermost/mattermost/webapp/channels/src/utils/text_formatting_imgs.test.ts
// Copyright (c) 2015-present Mattermost, Inc. All Rights Reserved. // See LICENSE.txt for license information. import EmojiMap from 'utils/emoji_map'; import * as Markdown from 'utils/markdown'; import {formatText} from 'utils/text_formatting'; const emojiMap = new EmojiMap(new Map()); describe('Markdown.Imgs', () => { it('Inline mage', () => { expect(Markdown.format('![Mattermost](/images/icon.png)').trim()).toBe( '<p><img src="/images/icon.png" alt="Mattermost" class="markdown-inline-img"></p>', ); }); it('Image with hover text', () => { expect(Markdown.format('![Mattermost](/images/icon.png "Mattermost Icon")').trim()).toBe( '<p><img src="/images/icon.png" alt="Mattermost" title="Mattermost Icon" class="markdown-inline-img"></p>', ); }); it('Image with link', () => { expect(Markdown.format('[![Mattermost](../../images/icon-76x76.png)](https://github.com/mattermost/platform)').trim()).toBe( '<p><a class="theme markdown__link" href="https://github.com/mattermost/platform" rel="noreferrer" target="_blank"><img src="../../images/icon-76x76.png" alt="Mattermost" class="markdown-inline-img"></a></p>', ); }); it('Image with width and height', () => { expect(Markdown.format('![Mattermost](../../images/icon-76x76.png =50x76 "Mattermost Icon")').trim()).toBe( '<p><img src="../../images/icon-76x76.png" alt="Mattermost" title="Mattermost Icon" width="50" height="76" class="markdown-inline-img"></p>', ); }); it('Image with width', () => { expect(Markdown.format('![Mattermost](../../images/icon-76x76.png =50 "Mattermost Icon")').trim()).toBe( '<p><img src="../../images/icon-76x76.png" alt="Mattermost" title="Mattermost Icon" width="50" height="auto" class="markdown-inline-img"></p>', ); }); }); describe('Text-formatted inline markdown images', () => { it('Not enclosed in a p tag', () => { const options = {markdown: true}; const output = formatText('![Mattermost](/images/icon.png)', options, emojiMap); expect(output).toBe( '<div class="markdown-inline-img__container"><img src="/images/icon.png" alt="Mattermost" class="markdown-inline-img"></div>', ); }); });
4,523
0
petrpan-code/mattermost/mattermost/webapp/channels/src
petrpan-code/mattermost/mattermost/webapp/channels/src/utils/text_formatting_links.test.ts
// Copyright (c) 2015-present Mattermost, Inc. All Rights Reserved. // See LICENSE.txt for license information. import EmojiMap from 'utils/emoji_map'; import * as Markdown from 'utils/markdown'; import * as TextFormatting from 'utils/text_formatting'; const emojiMap = new EmojiMap(new Map()); describe('Markdown.Links', () => { it('Not links', () => { expect(Markdown.format('example.com').trim()).toBe( '<p>example.com</p>', ); expect(Markdown.format('readme.md').trim()).toBe( '<p>readme.md</p>', ); expect(Markdown.format('@example.com').trim()).toBe( '<p>@example.com</p>', ); expect(Markdown.format('./make-compiled-client.sh').trim()).toBe( '<p>./make-compiled-client.sh</p>', ); expect(Markdown.format('`https://example.com`').trim()).toBe( '<p>' + '<span class="codespan__pre-wrap">' + '<code>' + 'https://example.com' + '</code>' + '</span>' + '</p>', ); expect(Markdown.format('[link](example.com').trim()).toBe( '<p>[link](example.com</p>', ); }); it('External links', () => { expect(Markdown.format('test.:test').trim()).toBe( '<p><a class="theme markdown__link" href="test.:test" rel="noreferrer" target="_blank">test.:test</a></p>', ); expect(Markdown.format('http://example.com').trim()).toBe( '<p><a class="theme markdown__link" href="http://example.com" rel="noreferrer" target="_blank">http://example.com</a></p>', ); expect(Markdown.format('https://example.com').trim()).toBe( '<p><a class="theme markdown__link" href="https://example.com" rel="noreferrer" target="_blank">https://example.com</a></p>', ); expect(Markdown.format('www.example.com').trim()).toBe( '<p><a class="theme markdown__link" href="http://www.example.com" rel="noreferrer" target="_blank">www.example.com</a></p>', ); expect(Markdown.format('www.example.com/index').trim()).toBe( '<p><a class="theme markdown__link" href="http://www.example.com/index" rel="noreferrer" target="_blank">www.example.com/index</a></p>', ); expect(Markdown.format('www.example.com/index.html').trim()).toBe( '<p><a class="theme markdown__link" href="http://www.example.com/index.html" rel="noreferrer" target="_blank">www.example.com/index.html</a></p>', ); expect(Markdown.format('www.example.com/index/sub').trim()).toBe( '<p><a class="theme markdown__link" href="http://www.example.com/index/sub" rel="noreferrer" target="_blank">www.example.com/index/sub</a></p>', ); expect(Markdown.format('www1.example.com').trim()).toBe( '<p><a class="theme markdown__link" href="http://www1.example.com" rel="noreferrer" target="_blank">www1.example.com</a></p>', ); expect(Markdown.format('example.com/index').trim()).toBe( '<p><a class="theme markdown__link" href="http://example.com/index" rel="noreferrer" target="_blank">example.com/index</a></p>', ); }); it('IP addresses', () => { expect(Markdown.format('http://127.0.0.1').trim()).toBe( '<p><a class="theme markdown__link" href="http://127.0.0.1" rel="noreferrer" target="_blank">http://127.0.0.1</a></p>', ); expect(Markdown.format('http://192.168.1.1:4040').trim()).toBe( '<p><a class="theme markdown__link" href="http://192.168.1.1:4040" rel="noreferrer" target="_blank">http://192.168.1.1:4040</a></p>', ); expect(Markdown.format('http://[::1]:80').trim()).toBe( '<p><a class="theme markdown__link" href="http://[::1]:80" rel="noreferrer" target="_blank">http://[::1]:80</a></p>', ); expect(Markdown.format('http://[::1]:8065').trim()).toBe( '<p><a class="theme markdown__link" href="http://[::1]:8065" rel="noreferrer" target="_blank">http://[::1]:8065</a></p>', ); expect(Markdown.format('https://[::1]:80').trim()).toBe( '<p><a class="theme markdown__link" href="https://[::1]:80" rel="noreferrer" target="_blank">https://[::1]:80</a></p>', ); expect(Markdown.format('http://[2001:0:5ef5:79fb:303a:62d5:3312:ff42]:80').trim()).toBe( '<p><a class="theme markdown__link" href="http://[2001:0:5ef5:79fb:303a:62d5:3312:ff42]:80" rel="noreferrer" target="_blank">http://[2001:0:5ef5:79fb:303a:62d5:3312:ff42]:80</a></p>', ); expect(Markdown.format('http://[2001:0:5ef5:79fb:303a:62d5:3312:ff42]:8065').trim()).toBe( '<p><a class="theme markdown__link" href="http://[2001:0:5ef5:79fb:303a:62d5:3312:ff42]:8065" rel="noreferrer" target="_blank">http://[2001:0:5ef5:79fb:303a:62d5:3312:ff42]:8065</a></p>', ); expect(Markdown.format('https://[2001:0:5ef5:79fb:303a:62d5:3312:ff42]:443').trim()).toBe( '<p><a class="theme markdown__link" href="https://[2001:0:5ef5:79fb:303a:62d5:3312:ff42]:443" rel="noreferrer" target="_blank">https://[2001:0:5ef5:79fb:303a:62d5:3312:ff42]:443</a></p>', ); expect(Markdown.format('http://username:[email protected]').trim()).toBe( '<p><a class="theme markdown__link" href="http://username:[email protected]" rel="noreferrer" target="_blank">http://username:[email protected]</a></p>', ); expect(Markdown.format('http://username:password@[2001:0:5ef5:79fb:303a:62d5:3312:ff42]:80').trim()).toBe( '<p><a class="theme markdown__link" href="http://username:password@[2001:0:5ef5:79fb:303a:62d5:3312:ff42]:80" rel="noreferrer" target="_blank">http://username:password@[2001:0:5ef5:79fb:303a:62d5:3312:ff42]:80</a></p>', ); }); it('Links with anchors', () => { expect(Markdown.format('https://en.wikipedia.org/wiki/URLs#Syntax').trim()).toBe( '<p><a class="theme markdown__link" href="https://en.wikipedia.org/wiki/URLs#Syntax" rel="noreferrer" target="_blank">https://en.wikipedia.org/wiki/URLs#Syntax</a></p>', ); expect(Markdown.format('https://groups.google.com/forum/#!msg').trim()).toBe( '<p><a class="theme markdown__link" href="https://groups.google.com/forum/#!msg" rel="noreferrer" target="_blank">https://groups.google.com/forum/#!msg</a></p>', ); }); it('Links with parameters', () => { expect(Markdown.format('www.example.com/index?params=1').trim()).toBe( '<p><a class="theme markdown__link" href="http://www.example.com/index?params=1" rel="noreferrer" target="_blank">www.example.com/index?params=1</a></p>', ); expect(Markdown.format('www.example.com/index?params=1&other=2').trim()).toBe( '<p><a class="theme markdown__link" href="http://www.example.com/index?params=1&amp;other=2" rel="noreferrer" target="_blank">www.example.com/index?params=1&amp;other=2</a></p>', ); expect(Markdown.format('www.example.com/index?params=1;other=2').trim()).toBe( '<p><a class="theme markdown__link" href="http://www.example.com/index?params=1;other=2" rel="noreferrer" target="_blank">www.example.com/index?params=1;other=2</a></p>', ); expect(Markdown.format('http://example.com:8065').trim()).toBe( '<p><a class="theme markdown__link" href="http://example.com:8065" rel="noreferrer" target="_blank">http://example.com:8065</a></p>', ); expect(Markdown.format('http://username:[email protected]').trim()).toBe( '<p><a class="theme markdown__link" href="http://username:[email protected]" rel="noreferrer" target="_blank">http://username:[email protected]</a></p>', ); }); it('Special characters', () => { expect(Markdown.format('http://www.example.com/_/page').trim()).toBe( '<p><a class="theme markdown__link" href="http://www.example.com/_/page" rel="noreferrer" target="_blank">http://www.example.com/_/page</a></p>', ); expect(Markdown.format('www.example.com/_/page').trim()).toBe( '<p><a class="theme markdown__link" href="http://www.example.com/_/page" rel="noreferrer" target="_blank">www.example.com/_/page</a></p>', ); expect(Markdown.format('https://en.wikipedia.org/wiki/🐬').trim()).toBe( '<p><a class="theme markdown__link" href="https://en.wikipedia.org/wiki/🐬" rel="noreferrer" target="_blank">https://en.wikipedia.org/wiki/🐬</a></p>', ); expect(Markdown.format('http://✪df.ws/1234').trim()).toBe( '<p><a class="theme markdown__link" href="http://✪df.ws/1234" rel="noreferrer" target="_blank">http://✪df.ws/1234</a></p>', ); }); it('Brackets', () => { expect(Markdown.format('https://en.wikipedia.org/wiki/Rendering_(computer_graphics)').trim()).toBe( '<p><a class="theme markdown__link" href="https://en.wikipedia.org/wiki/Rendering_(computer_graphics)" rel="noreferrer" target="_blank">https://en.wikipedia.org/wiki/Rendering_(computer_graphics)</a></p>', ); expect(Markdown.format('http://example.com/more_(than)_one_(parens)').trim()).toBe( '<p><a class="theme markdown__link" href="http://example.com/more_(than)_one_(parens)" rel="noreferrer" target="_blank">http://example.com/more_(than)_one_(parens)</a></p>', ); expect(Markdown.format('http://example.com/(something)?after=parens').trim()).toBe( '<p><a class="theme markdown__link" href="http://example.com/(something)?after=parens" rel="noreferrer" target="_blank">http://example.com/(something)?after=parens</a></p>', ); expect(Markdown.format('http://foo.com/unicode_(✪)_in_parens').trim()).toBe( '<p><a class="theme markdown__link" href="http://foo.com/unicode_(✪)_in_parens" rel="noreferrer" target="_blank">http://foo.com/unicode_(✪)_in_parens</a></p>', ); }); it('Email addresses', () => { expect(Markdown.format('[email protected]').trim()).toBe( '<p><a class="theme" href="mailto:[email protected]" rel="noreferrer" target="_blank">[email protected]</a></p>', ); expect(Markdown.format('[email protected]').trim()).toBe( '<p><a class="theme" href="mailto:[email protected]" rel="noreferrer" target="_blank">[email protected]</a></p>', ); expect(Markdown.format('mailto:[email protected]').trim()).toBe( '<p><a class="theme markdown__link" href="mailto:[email protected]" rel="noreferrer" target="_blank">mailto:[email protected]</a></p>', ); }); it('Formatted links', () => { expect(Markdown.format('*https://example.com*').trim()).toBe( '<p><em><a class="theme markdown__link" href="https://example.com" rel="noreferrer" target="_blank">https://example.com</a></em></p>', ); expect(Markdown.format('_https://example.com_').trim()).toBe( '<p><em><a class="theme markdown__link" href="https://example.com" rel="noreferrer" target="_blank">https://example.com</a></em></p>', ); expect(Markdown.format('**https://example.com**').trim()).toBe( '<p><strong><a class="theme markdown__link" href="https://example.com" rel="noreferrer" target="_blank">https://example.com</a></strong></p>', ); expect(Markdown.format('__https://example.com__').trim()).toBe( '<p><strong><a class="theme markdown__link" href="https://example.com" rel="noreferrer" target="_blank">https://example.com</a></strong></p>', ); expect(Markdown.format('***https://example.com***').trim()).toBe( '<p><strong><em><a class="theme markdown__link" href="https://example.com" rel="noreferrer" target="_blank">https://example.com</a></em></strong></p>', ); expect(Markdown.format('___https://example.com___').trim()).toBe( '<p><strong><em><a class="theme markdown__link" href="https://example.com" rel="noreferrer" target="_blank">https://example.com</a></em></strong></p>', ); expect(Markdown.format('<https://example.com>').trim()).toBe( '<p><a class="theme markdown__link" href="https://example.com" rel="noreferrer" target="_blank">https://example.com</a></p>', ); expect(Markdown.format('<https://en.wikipedia.org/wiki/Rendering_(computer_graphics)>').trim()).toBe( '<p><a class="theme markdown__link" href="https://en.wikipedia.org/wiki/Rendering_(computer_graphics)" rel="noreferrer" target="_blank">https://en.wikipedia.org/wiki/Rendering_(computer_graphics)</a></p>', ); }); it('Links with text', () => { expect(Markdown.format('[example link](example.com)').trim()).toBe( '<p><a class="theme markdown__link" href="http://example.com" rel="noreferrer" target="_blank">example link</a></p>', ); expect(Markdown.format('[example.com](example.com)').trim()).toBe( '<p><a class="theme markdown__link" href="http://example.com" rel="noreferrer" target="_blank">example.com</a></p>', ); expect(Markdown.format('[example.com/other](example.com)').trim()).toBe( '<p><a class="theme markdown__link" href="http://example.com" rel="noreferrer" target="_blank">example.com/other</a></p>', ); expect(Markdown.format('[example.com/other_link](example.com/example)').trim()).toBe( '<p><a class="theme markdown__link" href="http://example.com/example" rel="noreferrer" target="_blank">example.com/other_link</a></p>', ); expect(Markdown.format('[link with spaces](example.com/ spaces in the url)').trim()).toBe( '<p><a class="theme markdown__link" href="http://example.com/ spaces in the url" rel="noreferrer" target="_blank">link with spaces</a></p>', ); expect(Markdown.format('[This whole #sentence should be a link](https://example.com)').trim()).toBe( '<p><a class="theme markdown__link" href="https://example.com" rel="noreferrer" target="_blank">This whole #sentence should be a link</a></p>', ); expect(Markdown.format('[email link](mailto:[email protected])').trim()).toBe( '<p><a class="theme markdown__link" href="mailto:[email protected]" rel="noreferrer" target="_blank">email link</a></p>', ); expect(Markdown.format('[other link](ts3server://example.com)').trim()).toBe( '<p><a class="theme markdown__link" href="ts3server://example.com" rel="noreferrer" target="_blank">other link</a></p>', ); }); it('Links with tooltips', () => { expect(Markdown.format('[link](example.com "catch phrase!")').trim()).toBe( '<p><a class="theme markdown__link" href="http://example.com" rel="noreferrer" target="_blank" title="catch phrase!">link</a></p>', ); expect(Markdown.format('[link](example.com "title with "quotes"")').trim()).toBe( '<p><a class="theme markdown__link" href="http://example.com" rel="noreferrer" target="_blank" title="title with &quot;quotes&quot;">link</a></p>', ); expect(Markdown.format('[link with spaces](example.com/ spaces in the url "and a title")').trim()).toBe( '<p><a class="theme markdown__link" href="http://example.com/ spaces in the url" rel="noreferrer" target="_blank" title="and a title">link with spaces</a></p>', ); }); it('Links with surrounding text', () => { expect(Markdown.format('This is a sentence with a http://example.com in it.').trim()).toBe( '<p>This is a sentence with a <a class="theme markdown__link" href="http://example.com" rel="noreferrer" target="_blank">http://example.com</a> in it.</p>', ); expect(Markdown.format('This is a sentence with a http://example.com/_/underscore in it.').trim()).toBe( '<p>This is a sentence with a <a class="theme markdown__link" href="http://example.com/_/underscore" rel="noreferrer" target="_blank">http://example.com/_/underscore</a> in it.</p>', ); expect(Markdown.format('This is a sentence with a http://192.168.1.1:4040 in it.').trim()).toBe( '<p>This is a sentence with a <a class="theme markdown__link" href="http://192.168.1.1:4040" rel="noreferrer" target="_blank">http://192.168.1.1:4040</a> in it.</p>', ); expect(Markdown.format('This is a sentence with a https://[::1]:80 in it.').trim()).toBe( '<p>This is a sentence with a <a class="theme markdown__link" href="https://[::1]:80" rel="noreferrer" target="_blank">https://[::1]:80</a> in it.</p>', ); }); it('Links with trailing punctuation', () => { expect(Markdown.format('This is a link to http://example.com.').trim()).toBe( '<p>This is a link to <a class="theme markdown__link" href="http://example.com" rel="noreferrer" target="_blank">http://example.com</a>.</p>', ); expect(Markdown.format('This is a link containing http://example.com/something?with,commas,in,url, but not at the end').trim()).toBe( '<p>This is a link containing <a class="theme markdown__link" href="http://example.com/something?with,commas,in,url" rel="noreferrer" target="_blank">http://example.com/something?with,commas,in,url</a>, but not at the end</p>', ); expect(Markdown.format('This is a question about a link http://example.com?').trim()).toBe( '<p>This is a question about a link <a class="theme markdown__link" href="http://example.com" rel="noreferrer" target="_blank">http://example.com</a>?</p>', ); }); it('Links with surrounding brackets', () => { expect(Markdown.format('(http://example.com)').trim()).toBe( '<p>(<a class="theme markdown__link" href="http://example.com" rel="noreferrer" target="_blank">http://example.com</a>)</p>', ); expect(Markdown.format('(see http://example.com)').trim()).toBe( '<p>(see <a class="theme markdown__link" href="http://example.com" rel="noreferrer" target="_blank">http://example.com</a>)</p>', ); expect(Markdown.format('(http://example.com watch this)').trim()).toBe( '<p>(<a class="theme markdown__link" href="http://example.com" rel="noreferrer" target="_blank">http://example.com</a> watch this)</p>', ); expect(Markdown.format('(www.example.com)').trim()).toBe( '<p>(<a class="theme markdown__link" href="http://www.example.com" rel="noreferrer" target="_blank">www.example.com</a>)</p>', ); expect(Markdown.format('(see www.example.com)').trim()).toBe( '<p>(see <a class="theme markdown__link" href="http://www.example.com" rel="noreferrer" target="_blank">www.example.com</a>)</p>', ); expect(Markdown.format('(www.example.com watch this)').trim()).toBe( '<p>(<a class="theme markdown__link" href="http://www.example.com" rel="noreferrer" target="_blank">www.example.com</a> watch this)</p>', ); expect(Markdown.format('([link](http://example.com))').trim()).toBe( '<p>(<a class="theme markdown__link" href="http://example.com" rel="noreferrer" target="_blank">link</a>)</p>', ); expect(Markdown.format('(see [link](http://example.com))').trim()).toBe( '<p>(see <a class="theme markdown__link" href="http://example.com" rel="noreferrer" target="_blank">link</a>)</p>', ); expect(Markdown.format('([link](http://example.com) watch this)').trim()).toBe( '<p>(<a class="theme markdown__link" href="http://example.com" rel="noreferrer" target="_blank">link</a> watch this)</p>', ); expect(Markdown.format('([email protected])').trim()).toBe( '<p>(<a class="theme" href="mailto:[email protected]" rel="noreferrer" target="_blank">[email protected]</a>)</p>', ); expect(Markdown.format('(email [email protected])').trim()).toBe( '<p>(email <a class="theme" href="mailto:[email protected]" rel="noreferrer" target="_blank">[email protected]</a>)</p>', ); expect(Markdown.format('([email protected] email)').trim()).toBe( '<p>(<a class="theme" href="mailto:[email protected]" rel="noreferrer" target="_blank">[email protected]</a> email)</p>', ); expect(Markdown.format('This is a sentence with a [link](http://example.com) in it.').trim()).toBe( '<p>This is a sentence with a <a class="theme markdown__link" href="http://example.com" rel="noreferrer" target="_blank">link</a> in it.</p>', ); expect(Markdown.format('This is a sentence with a link (http://example.com) in it.').trim()).toBe( '<p>This is a sentence with a link (<a class="theme markdown__link" href="http://example.com" rel="noreferrer" target="_blank">http://example.com</a>) in it.</p>', ); expect(Markdown.format('This is a sentence with a (https://en.wikipedia.org/wiki/Rendering_(computer_graphics)) in it.').trim()).toBe( '<p>This is a sentence with a (<a class="theme markdown__link" href="https://en.wikipedia.org/wiki/Rendering_(computer_graphics)" rel="noreferrer" target="_blank">https://en.wikipedia.org/wiki/Rendering_(computer_graphics)</a>) in it.</p>', ); }); it('Searching for links', () => { expect(TextFormatting.formatText('https://en.wikipedia.org/wiki/Unix', {searchTerm: 'wikipedia'}, emojiMap).trim()).toBe( '<p><a class="theme markdown__link search-highlight" href="https://en.wikipedia.org/wiki/Unix" rel="noreferrer" target="_blank">https://en.wikipedia.org/wiki/Unix</a></p>', ); expect(TextFormatting.formatText('[Link](https://en.wikipedia.org/wiki/Unix)', {searchTerm: 'unix'}, emojiMap).trim()).toBe( '<p><a class="theme markdown__link search-highlight" href="https://en.wikipedia.org/wiki/Unix" rel="noreferrer" target="_blank">Link</a></p>', ); }); it('Links containing %', () => { expect(Markdown.format('https://en.wikipedia.org/wiki/%C3%89').trim()).toBe( '<p><a class="theme markdown__link" href="https://en.wikipedia.org/wiki/%C3%89" rel="noreferrer" target="_blank">https://en.wikipedia.org/wiki/%C3%89</a></p>', ); expect(Markdown.format('https://en.wikipedia.org/wiki/%E9').trim()).toBe( '<p><a class="theme markdown__link" href="https://en.wikipedia.org/wiki/%E9" rel="noreferrer" target="_blank">https://en.wikipedia.org/wiki/%E9</a></p>', ); }); it('Relative link', () => { expect(Markdown.format('[A Relative Link](/static/files/5b4a7904a3e041018526a00dba59ee48.png)').trim()).toBe( '<p><a class="theme markdown__link" href="/static/files/5b4a7904a3e041018526a00dba59ee48.png" rel="noreferrer" target="_blank">A Relative Link</a></p>', ); }); describe('autolinkedUrlSchemes', () => { test('all links are rendered when not provided', () => { expect(Markdown.format('http://example.com').trim()).toBe(`<p>${link('http://example.com')}</p>`); expect(Markdown.format('https://example.com').trim()).toBe(`<p>${link('https://example.com')}</p>`); expect(Markdown.format('ftp://ftp.example.com').trim()).toBe(`<p>${link('ftp://ftp.example.com')}</p>`); expect(Markdown.format('tel:1-555-123-4567').trim()).toBe(`<p>${link('tel:1-555-123-4567')}</p>`); expect(Markdown.format('mailto:[email protected]').trim()).toBe(`<p>${link('mailto:[email protected]')}</p>`); expect(Markdown.format('git://git.example.com').trim()).toBe(`<p>${link('git://git.example.com')}</p>`); expect(Markdown.format('test:test').trim()).toBe(`<p>${link('test:test')}</p>`); }); test('no links are rendered when no schemes are provided', () => { const options = { autolinkedUrlSchemes: [], }; expect(Markdown.format('http://example.com', options).trim()).toBe('<p>http://example.com</p>'); expect(Markdown.format('https://example.com', options).trim()).toBe('<p>https://example.com</p>'); expect(Markdown.format('ftp://ftp.example.com', options).trim()).toBe('<p>ftp://ftp.example.com</p>'); expect(Markdown.format('tel:1-555-123-4567', options).trim()).toBe('<p>tel:1-555-123-4567</p>'); expect(Markdown.format('mailto:[email protected]', options).trim()).toBe('<p>mailto:[email protected]</p>'); expect(Markdown.format('git://git.example.com', options).trim()).toBe('<p>git://git.example.com</p>'); expect(Markdown.format('test:test', options).trim()).toBe('<p>test:test</p>'); }); test('only matching links are rendered when schemes are provided', () => { const options = { autolinkedUrlSchemes: ['https', 'git', 'test', 'test.', 'taco+what', 'taco.what'], }; expect(Markdown.format('http://example.com', options).trim()).toBe('<p>http://example.com</p>'); expect(Markdown.format('https://example.com', options).trim()).toBe(`<p>${link('https://example.com')}</p>`); expect(Markdown.format('ftp://ftp.example.com', options).trim()).toBe('<p>ftp://ftp.example.com</p>'); expect(Markdown.format('tel:1-555-123-4567', options).trim()).toBe('<p>tel:1-555-123-4567</p>'); expect(Markdown.format('mailto:[email protected]', options).trim()).toBe('<p>mailto:[email protected]</p>'); expect(Markdown.format('git://git.example.com', options).trim()).toBe(`<p>${link('git://git.example.com')}</p>`); expect(Markdown.format('test:test', options).trim()).toBe(`<p>${link('test:test')}</p>`); expect(Markdown.format('test.:test', options).trim()).toBe(`<p>${link('test.:test')}</p>`); expect(Markdown.format('taco+what://example.com', options).trim()).toBe(`<p>${link('taco+what://example.com')}</p>`); expect(Markdown.format('taco.what://example.com', options).trim()).toBe(`<p>${link('taco.what://example.com')}</p>`); }); test('explicit links are not affected by this setting', () => { const options = { autolinkedUrlSchemes: [], }; expect(Markdown.format('www.example.com', options).trim()).toBe(`<p>${link('http://www.example.com', 'www.example.com')}</p>`); expect(Markdown.format('[link](git://git.example.com)', options).trim()).toBe(`<p>${link('git://git.example.com', 'link')}</p>`); expect(Markdown.format('<http://example.com>', options).trim()).toBe(`<p>${link('http://example.com')}</p>`); }); }); }); function link(href: string, text?: string, title?: string) { let out = `<a class="theme markdown__link" href="${href}" rel="noreferrer" target="_blank"`; if (title) { out += ` title="${title}"`; } out += `>${text || href}</a>`; return out; }
4,524
0
petrpan-code/mattermost/mattermost/webapp/channels/src
petrpan-code/mattermost/mattermost/webapp/channels/src/utils/text_formatting_mention_highlighting.test.ts
// Copyright (c) 2015-present Mattermost, Inc. All Rights Reserved. // See LICENSE.txt for license information. import EmojiMap from 'utils/emoji_map'; import * as TextFormatting from 'utils/text_formatting'; const emojiMap = new EmojiMap(new Map()); describe('TextFormatting.mentionHighlighting', () => { const testCases = [{ name: 'no mentions', input: 'These are words', mentionKeys: [], expected: '<p>These are words</p>', }, { name: 'not an at-mention', input: 'These are words', mentionKeys: [{key: 'words'}], expected: '<p>These are <span class="mention--highlight">words</span></p>', }, { name: 'at-mention', input: 'These are @words', mentionKeys: [{key: '@words'}], expected: '<p>These are <span class="mention--highlight"><span data-mention="words">@words</span></span></p>', }, { name: 'at-mention and non-at-mention for same word', input: 'These are @words', mentionKeys: [{key: '@words'}, {key: 'words'}], expected: '<p>These are <span class="mention--highlight"><span data-mention="words">@words</span></span></p>', }, { name: 'case insensitive mentions', input: 'These are words and Words and wORDS', mentionKeys: [{key: 'words'}], expected: '<p>These are <span class="mention--highlight">words</span> and <span class="mention--highlight">Words</span> and <span class="mention--highlight">wORDS</span></p>', }, { name: 'case sensitive mentions', input: 'These are words and Words and wORDS', mentionKeys: [{key: 'Words', caseSensitive: true}], expected: '<p>These are words and <span class="mention--highlight">Words</span> and wORDS</p>', }, { name: 'multibyte mentions', input: '我爱吃番茄炒饭', mentionKeys: [{key: '番茄'}], expected: '<p>我爱吃<span class="mention--highlight">番茄</span>炒饭</p>', }, { name: 'multibyte mentions twice in one sentence', input: '石橋さんが石橋を渡る', mentionKeys: [{key: '石橋'}], expected: '<p><span class="mention--highlight">石橋</span>さんが<span class="mention--highlight">石橋</span>を渡る</p>', }, { name: 'combine multibyte and ascii mentions key', input: '3words 3words', mentionKeys: [{key: 'words'}], expected: '<p>3<span class="mention--highlight">words</span> 3words</p>', }, { name: 'at mention linking disabled, mentioned by non-at-mention', input: 'These are @words', atMentions: false, mentionKeys: [{key: 'words'}], expected: '<p>These are @<span class="mention--highlight">words</span></p>', }, { name: 'at mention linking disabled, mentioned by at-mention', input: 'These are @words', atMentions: false, mentionKeys: [{key: '@words'}], expected: '<p>These are <span class="mention--highlight">@words</span></p>', }, { name: 'mention highlighting disabled', input: 'These are words', mentionHighlight: false, mentionKeys: [{key: 'words'}], expected: '<p>These are words</p>', }, { name: 'mention highlighting and at mention linking disabled', input: 'These are @words', atMentions: false, mentionHighlight: false, mentionKeys: [{key: '@words'}], expected: '<p>These are @words</p>', }]; for (const testCase of testCases) { it(testCase.name, () => { const options = { atMentions: 'atMentions' in testCase ? testCase.atMentions : true, mentionHighlight: 'mentionHighlight' in testCase ? testCase.mentionHighlight : true, mentionKeys: testCase.mentionKeys, }; const output = TextFormatting.formatText(testCase.input, options, emojiMap).trim(); expect(output).toEqual(testCase.expected); }); } });
4,525
0
petrpan-code/mattermost/mattermost/webapp/channels/src
petrpan-code/mattermost/mattermost/webapp/channels/src/utils/text_formatting_search_highlighting.test.ts
// Copyright (c) 2015-present Mattermost, Inc. All Rights Reserved. // See LICENSE.txt for license information. import EmojiMap from 'utils/emoji_map'; import * as TextFormatting from 'utils/text_formatting'; const emojiMap = new EmojiMap(new Map()); describe('TextFormatting.searchHighlighting', () => { const testCases = [{ name: 'no search highlighting', input: 'These are words in a sentence.', searchMatches: [], searchTerm: '', expected: '<p>These are words in a sentence.</p>', }, { name: 'search term highlighting', input: 'These are words in a sentence.', searchTerm: 'words sentence', expected: '<p>These are <span class="search-highlight">words</span> in a <span class="search-highlight">sentence</span>.</p>', }, { name: 'search term highlighting with quoted phrase', input: 'These are words in a sentence. This is a sentence with words.', searchTerm: '"words in a sentence"', expected: '<p>These are <span class="search-highlight">words in a sentence</span>. This is a sentence with words.</p>', }, { name: 'search term highlighting with empty quoted phrase', input: 'These are words in a sentence. This is a sentence with words.', searchTerm: '""', expected: '<p>These are words in a sentence. This is a sentence with words.</p>', }, { name: 'search term highlighting with flags', input: 'These are words in a sentence.', searchTerm: 'words in:sentence', expected: '<p>These are <span class="search-highlight">words</span> in a sentence.</p>', }, { name: 'search term highlighting with at mentions', input: 'These are @words in a @sentence.', searchTerm: '@words sentence', expected: '<p>These are <span class="search-highlight"><span data-mention="words">@words</span></span> in a <span class="search-highlight"><span data-mention="sentence.">@sentence.</span></span></p>', }, { name: 'search term highlighting in a code span', input: 'These are `words in a sentence`.', searchTerm: 'words', expected: '<p>These are <span class="codespan__pre-wrap"><code><span class="search-highlight">words</span> in a sentence</code></span>.</p>', }, { name: 'search term highlighting in a code block', input: '```\nwords in a sentence\n```', searchTerm: 'words', expected: '<div data-codeblock-code="words in a sentence" data-codeblock-language="" data-codeblock-searchedcontent="&lt;div class=&quot;post-code__search-highlighting&quot;&gt;&lt;span class=&quot;search-highlight&quot;&gt;words&lt;/span&gt; in a sentence&lt;/div&gt;"></div>', }, { name: 'search term highlighting in link text', input: 'These are [words in a sentence](https://example.com).', searchTerm: 'words', expected: '<p>These are <a class="theme markdown__link" href="https://example.com" rel="noreferrer" target="_blank"><span class="search-highlight">words</span> in a sentence</a>.</p>', }, { name: 'search term highlighting in link url', input: 'These are [words in a sentence](https://example.com).', searchTerm: 'example', expected: '<p>These are <a class="theme markdown__link search-highlight" href="https://example.com" rel="noreferrer" target="_blank">words in a sentence</a>.</p>', }, { name: 'search match highlighting', input: 'These are words in a sentence.', searchMatches: ['words', 'sentence'], expected: '<p>These are <span class="search-highlight">words</span> in a <span class="search-highlight">sentence</span>.</p>', }, { name: 'search match highlighting with quoted phrase', input: 'These are words in a sentence. This is a sentence with words.', searchMatches: ['words in a sentence'], expected: '<p>These are <span class="search-highlight">words in a sentence</span>. This is a sentence with words.</p>', }, { name: 'search match highlighting with at mentions', input: 'These are @words in a @sentence.', searchMatches: ['@words', 'sentence'], expected: '<p>These are <span class="search-highlight"><span data-mention="words">@words</span></span> in a <span class="search-highlight"><span data-mention="sentence.">@sentence.</span></span></p>', }, { name: 'search match highlighting in a code span', input: 'These are `words in a sentence`.', searchMatches: ['words'], expected: '<p>These are <span class="codespan__pre-wrap"><code><span class="search-highlight">words</span> in a sentence</code></span>.</p>', }, { name: 'search match highlighting in a code block', input: '```\nwords in a sentence\n```', searchMatches: ['words'], expected: '<div data-codeblock-code="words in a sentence" data-codeblock-language="" data-codeblock-searchedcontent="&lt;div class=&quot;post-code__search-highlighting&quot;&gt;&lt;span class=&quot;search-highlight&quot;&gt;words&lt;/span&gt; in a sentence&lt;/div&gt;"></div>', }, { name: 'search match highlighting in link text', input: 'These are [words in a sentence](https://example.com).', searchMatches: ['words'], expected: '<p>These are <a class="theme markdown__link" href="https://example.com" rel="noreferrer" target="_blank"><span class="search-highlight">words</span> in a sentence</a>.</p>', }, { name: 'search match highlighting in link url', input: 'These are [words in a sentence](https://example.com).', searchMatches: ['example'], expected: '<p>These are <a class="theme markdown__link search-highlight" href="https://example.com" rel="noreferrer" target="_blank">words in a sentence</a>.</p>', }]; for (const testCase of testCases) { it(testCase.name, () => { const options = { atMentions: true, mentionHighlight: true, searchMatches: testCase.searchMatches, searchTerm: testCase.searchTerm || '', }; const output = TextFormatting.formatText(testCase.input, options, emojiMap).trim(); expect(output).toEqual(testCase.expected); }); } it('wildcard highlighting', () => { assertTextMatch('foobar', 'foo*', 'foo', 'bar'); assertTextMatch('foo1bar', 'foo1*', 'foo1', 'bar'); assertTextMatch('foo_bar', 'foo_*', 'foo_', 'bar'); assertTextMatch('foo.bar', 'foo.*', 'foo.', 'bar'); assertTextMatch('foo?bar', 'foo?*', 'foo?', 'bar'); assertTextMatch('foo bar', 'foo*', 'foo', ' bar'); assertTextMatch('foo bar', 'foo *', 'foo', ' bar'); assertTextMatch('foo⺑bar', 'foo⺑*', 'foo⺑', 'bar'); function assertTextMatch(input: string, search: string, expectedMatch: string, afterMatch: string) { expect(TextFormatting.formatText(input, {searchTerm: search}, emojiMap).trim()). toEqual(`<p><span class="search-highlight">${expectedMatch}</span>${afterMatch}</p>`); } }); });
4,528
0
petrpan-code/mattermost/mattermost/webapp/channels/src
petrpan-code/mattermost/mattermost/webapp/channels/src/utils/url.test.tsx
// Copyright (c) 2015-present Mattermost, Inc. All Rights Reserved. // See LICENSE.txt for license information. import { getRelativeChannelURL, getSiteURL, getSiteURLFromWindowObject, isPermalinkURL, validateChannelUrl, } from 'utils/url'; describe('Utils.URL', () => { test('getRelativeChannelURL', () => { expect(getRelativeChannelURL('teamName', 'channelName')).toEqual('/teamName/channels/channelName'); }); describe('getSiteURL', () => { const testCases = [ { description: 'origin', location: {origin: 'http://example.com:8065', protocol: '', hostname: '', port: ''}, basename: '', expectedSiteURL: 'http://example.com:8065', }, { description: 'origin, trailing slash', location: {origin: 'http://example.com:8065/', protocol: '', hostname: '', port: ''}, basename: '', expectedSiteURL: 'http://example.com:8065', }, { description: 'origin, with basename', location: {origin: 'http://example.com:8065', protocol: '', hostname: '', port: ''}, basename: '/subpath', expectedSiteURL: 'http://example.com:8065/subpath', }, { description: 'no origin', location: {origin: '', protocol: 'http:', hostname: 'example.com', port: '8065'}, basename: '', expectedSiteURL: 'http://example.com:8065', }, { description: 'no origin, with basename', location: {origin: '', protocol: 'http:', hostname: 'example.com', port: '8065'}, basename: '/subpath', expectedSiteURL: 'http://example.com:8065/subpath', }, ]; testCases.forEach((testCase) => it(testCase.description, () => { const obj = { location: testCase.location, basename: testCase.basename, }; expect(getSiteURLFromWindowObject(obj)).toEqual(testCase.expectedSiteURL); })); }); describe('validateChannelUrl', () => { const testCases = [ { description: 'Called with an empty string', url: '', expectedErrors: ['change_url.longer'], }, { description: 'Called with a url starting with a dash', url: '-Url', expectedErrors: ['change_url.startWithLetter'], }, { description: 'Called with a url starting with an underscore', url: '_URL', expectedErrors: ['change_url.startWithLetter'], }, { description: 'Called with a url starting and ending with an underscore', url: '_a_', expectedErrors: ['change_url.startAndEndWithLetter'], }, { description: 'Called with a url starting and ending with an dash', url: '-a-', expectedErrors: ['change_url.startAndEndWithLetter'], }, { description: 'Called with a url ending with an dash', url: 'a----', expectedErrors: ['change_url.endWithLetter'], }, { description: 'Called with a url containing two underscores', url: 'foo__bar', expectedErrors: [], }, { description: 'Called with a url resembling a direct message url', url: 'uzsfmtmniifsjgesce4u7yznyh__uzsfmtmniifsjgesce4u7yznyh', expectedErrors: ['change_url.invalidDirectMessage'], }, { description: 'Called with a containing two dashes', url: 'foo--bar', expectedErrors: [], }, { description: 'Called with a capital letters two dashes', url: 'Foo--bar', expectedErrors: ['change_url.invalidUrl'], }, ]; testCases.forEach((testCase) => it(testCase.description, () => { const returnedErrors = validateChannelUrl(testCase.url).map((error) => (typeof error === 'string' ? error : error.key)); returnedErrors.sort(); testCase.expectedErrors.sort(); expect(returnedErrors).toEqual(testCase.expectedErrors); })); }); describe('isPermalinkURL', () => { const siteURL = getSiteURL(); test.each([ ['/teamname-1/pl/affe2344234', true], [`${siteURL}/teamname-1/pl/affe2344234`, true], [siteURL, false], ['/teamname-1/channel/post', false], ['https://example.com', false], ['https://example.com/teamname-1/pl/affe2344234', false], ])('is permalink for %s should return %s', (url, expected) => { expect(isPermalinkURL(url)).toBe(expected); }); }); });
4,531
0
petrpan-code/mattermost/mattermost/webapp/channels/src
petrpan-code/mattermost/mattermost/webapp/channels/src/utils/utils.test.tsx
// Copyright (c) 2015-present Mattermost, Inc. All Rights Reserved. // See LICENSE.txt for license information. import type {UserProfile} from '@mattermost/types/users'; import {GeneralTypes} from 'mattermost-redux/action_types'; import store from 'stores/redux_store'; import * as lineBreakHelpers from 'tests/helpers/line_break_helpers'; import * as ua from 'tests/helpers/user_agent_mocks'; import Constants, {ValidationErrors} from 'utils/constants'; import * as Utils from 'utils/utils'; describe('Utils.getDisplayNameByUser', () => { afterEach(() => { store.dispatch({ type: GeneralTypes.CLIENT_CONFIG_RESET, data: {}, }); }); const userA = {username: 'a_user', nickname: 'a_nickname', first_name: 'a_first_name', last_name: ''}; const userB = {username: 'b_user', nickname: 'b_nickname', first_name: '', last_name: 'b_last_name'}; const userC = {username: 'c_user', nickname: '', first_name: 'c_first_name', last_name: 'c_last_name'}; const userD = {username: 'd_user', nickname: 'd_nickname', first_name: 'd_first_name', last_name: 'd_last_name'}; const userE = {username: 'e_user', nickname: '', first_name: 'e_first_name', last_name: 'e_last_name'}; const userF = {username: 'f_user', nickname: 'f_nickname', first_name: 'f_first_name', last_name: 'f_last_name'}; const userG = {username: 'g_user', nickname: '', first_name: 'g_first_name', last_name: 'g_last_name'}; const userH = {username: 'h_user', nickname: 'h_nickname', first_name: '', last_name: 'h_last_name'}; const userI = {username: 'i_user', nickname: 'i_nickname', first_name: 'i_first_name', last_name: ''}; const userJ = {username: 'j_user', nickname: '', first_name: 'j_first_name', last_name: ''}; test('Show display name of user with TeammateNameDisplay set to username', () => { store.dispatch({ type: GeneralTypes.CLIENT_CONFIG_RECEIVED, data: { TeammateNameDisplay: 'username', }, }); [userA, userB, userC, userD, userE, userF, userG, userH, userI, userJ].forEach((user) => { expect(Utils.getDisplayNameByUser(store.getState(), user as UserProfile)).toEqual(user.username); }); }); test('Show display name of user with TeammateNameDisplay set to nickname_full_name', () => { store.dispatch({ type: GeneralTypes.CLIENT_CONFIG_RECEIVED, data: { TeammateNameDisplay: 'nickname_full_name', }, }); for (const data of [ {user: userA, result: userA.nickname}, {user: userB, result: userB.nickname}, {user: userC, result: `${userC.first_name} ${userC.last_name}`}, {user: userD, result: userD.nickname}, {user: userE, result: `${userE.first_name} ${userE.last_name}`}, {user: userF, result: userF.nickname}, {user: userG, result: `${userG.first_name} ${userG.last_name}`}, {user: userH, result: userH.nickname}, {user: userI, result: userI.nickname}, {user: userJ, result: userJ.first_name}, ]) { expect(Utils.getDisplayNameByUser(store.getState(), data.user as UserProfile)).toEqual(data.result); } }); test('Show display name of user with TeammateNameDisplay set to username', () => { store.dispatch({ type: GeneralTypes.CLIENT_CONFIG_RECEIVED, data: { TeammateNameDisplay: 'full_name', }, }); for (const data of [ {user: userA, result: userA.first_name}, {user: userB, result: userB.last_name}, {user: userC, result: `${userC.first_name} ${userC.last_name}`}, {user: userD, result: `${userD.first_name} ${userD.last_name}`}, {user: userE, result: `${userE.first_name} ${userE.last_name}`}, {user: userF, result: `${userF.first_name} ${userF.last_name}`}, {user: userG, result: `${userG.first_name} ${userG.last_name}`}, {user: userH, result: userH.last_name}, {user: userI, result: userI.first_name}, {user: userJ, result: userJ.first_name}, ]) { expect(Utils.getDisplayNameByUser(store.getState(), data.user as UserProfile)).toEqual(data.result); } }); }); describe('Utils.isValidPassword', () => { test('Minimum length enforced', () => { for (const data of [ { password: 'tooshort', config: { minimumLength: 10, requireLowercase: false, requireUppercase: false, requireNumber: false, requireSymbol: false, }, valid: false, }, { password: 'longenoughpassword', config: { minimumLength: 10, requireLowercase: false, requireUppercase: false, requireNumber: false, requireSymbol: false, }, valid: true, }, ]) { const {valid} = Utils.isValidPassword(data.password, data.config); expect(data.valid).toEqual(valid); } }); test('Require lowercase enforced', () => { for (const data of [ { password: 'UPPERCASE', config: { minimumLength: 5, requireLowercase: true, requireUppercase: false, requireNumber: false, requireSymbol: false, }, valid: false, }, { password: 'SOMELowercase', config: { minimumLength: 5, requireLowercase: true, requireUppercase: false, requireNumber: false, requireSymbol: false, }, valid: true, }, ]) { const {valid} = Utils.isValidPassword(data.password, data.config); expect(data.valid).toEqual(valid); } }); test('Require uppercase enforced', () => { for (const data of [ { password: 'lowercase', config: { minimumLength: 5, requireLowercase: false, requireUppercase: true, requireNumber: false, requireSymbol: false, }, valid: false, }, { password: 'SOMEUppercase', config: { minimumLength: 5, requireLowercase: false, requireUppercase: true, requireNumber: false, requireSymbol: false, }, valid: true, }, ]) { const {valid} = Utils.isValidPassword(data.password, data.config); expect(data.valid).toEqual(valid); } }); test('Require number enforced', () => { for (const data of [ { password: 'NoNumbers', config: { minimumLength: 5, requireLowercase: true, requireUppercase: true, requireNumber: true, requireSymbol: false, }, valid: false, }, { password: 'S0m3Numb3rs', config: { minimumLength: 5, requireLowercase: true, requireUppercase: true, requireNumber: true, requireSymbol: false, }, valid: true, }, ]) { const {valid} = Utils.isValidPassword(data.password, data.config); expect(data.valid).toEqual(valid); } }); test('Require symbol enforced', () => { for (const data of [ { password: 'N0Symb0ls', config: { minimumLength: 5, requireLowercase: true, requireUppercase: true, requireNumber: true, requireSymbol: true, }, valid: false, }, { password: 'S0m3Symb0!s', config: { minimumLength: 5, requireLowercase: true, requireUppercase: true, requireNumber: true, requireSymbol: true, }, valid: true, }, ]) { const {valid} = Utils.isValidPassword(data.password, data.config); expect(data.valid).toEqual(valid); } }); }); describe('Utils.isValidUsername', () => { const tests = [ { testUserName: 'sonic.the.hedgehog', expectedError: undefined, }, { testUserName: 'sanic.the.speedy.errored.hedgehog@10_10-10', expectedError: ValidationErrors.INVALID_LENGTH, }, { testUserName: 'sanic⭑', expectedError: ValidationErrors.INVALID_CHARACTERS, }, { testUserName: '.sanic', expectedError: ValidationErrors.INVALID_FIRST_CHARACTER, }, { testUserName: 'valet', expectedError: ValidationErrors.RESERVED_NAME, }, ]; test('Validate username', () => { for (const test of tests) { const testError = Utils.isValidUsername(test.testUserName); if (testError) { expect(testError.id).toEqual(test.expectedError); } else { expect(testError).toBe(undefined); } } }); test('Validate bot username', () => { tests.push({ testUserName: 'sanic.the.hedgehog.', expectedError: ValidationErrors.INVALID_LAST_CHARACTER, }); for (const test of tests) { const testError = Utils.isValidUsername(test.testUserName); if (testError) { expect(testError.id).toEqual(test.expectedError); } else { expect(testError).toBe(undefined); } } }); }); describe('Utils.localizeMessage', () => { const originalGetState = store.getState; afterAll(() => { store.getState = originalGetState; }); const entities = { general: { config: {}, }, users: { currentUserId: 'abcd', profiles: { abcd: { locale: 'fr', }, }, }, }; describe('with translations', () => { beforeAll(() => { store.getState = () => ({ entities, views: { i18n: { translations: { fr: { 'test.hello_world': 'Bonjour tout le monde!', }, }, }, }, }); }); test('with translations', () => { expect(Utils.localizeMessage('test.hello_world', 'Hello, World!')).toEqual('Bonjour tout le monde!'); }); test('with missing string in translations', () => { expect(Utils.localizeMessage('test.hello_world2', 'Hello, World 2!')).toEqual('Hello, World 2!'); }); test('with missing string in translations and no default', () => { expect(Utils.localizeMessage('test.hello_world2')).toEqual('test.hello_world2'); }); }); describe('without translations', () => { beforeAll(() => { store.getState = () => ({ entities, views: { i18n: { translations: {}, }, }, }); }); test('without translations', () => { expect(Utils.localizeMessage('test.hello_world', 'Hello, World!')).toEqual('Hello, World!'); }); test('without translations and no default', () => { expect(Utils.localizeMessage('test.hello_world')).toEqual('test.hello_world'); }); }); }); describe('Utils.imageURLForUser', () => { test('should return url when user id and last_picture_update is given', () => { const imageUrl = Utils.imageURLForUser('foobar-123', 123456); expect(imageUrl).toEqual('/api/v4/users/foobar-123/image?_=123456'); }); test('should return url when user id is given without last_picture_update', () => { const imageUrl = Utils.imageURLForUser('foobar-123'); expect(imageUrl).toEqual('/api/v4/users/foobar-123/image?_=0'); }); }); describe('Utils.isUnhandledLineBreakKeyCombo', () => { test('isUnhandledLineBreakKeyCombo returns true for alt + enter for Chrome UA', () => { ua.mockChrome(); expect(Utils.isUnhandledLineBreakKeyCombo(lineBreakHelpers.getAltKeyEvent())).toBe(true); }); test('isUnhandledLineBreakKeyCombo returns false for alt + enter for Safari UA', () => { ua.mockSafari(); expect(Utils.isUnhandledLineBreakKeyCombo(lineBreakHelpers.getAltKeyEvent())).toBe(false); }); test('isUnhandledLineBreakKeyCombo returns false for shift + enter', () => { expect(Utils.isUnhandledLineBreakKeyCombo(lineBreakHelpers.getShiftKeyEvent())).toBe(false); }); test('isUnhandledLineBreakKeyCombo returns false for ctrl/command + enter', () => { expect(Utils.isUnhandledLineBreakKeyCombo(lineBreakHelpers.getCtrlKeyEvent())).toBe(false); expect(Utils.isUnhandledLineBreakKeyCombo(lineBreakHelpers.getMetaKeyEvent())).toBe(false); }); test('isUnhandledLineBreakKeyCombo returns false for just enter', () => { expect(Utils.isUnhandledLineBreakKeyCombo(lineBreakHelpers.BASE_EVENT)).toBe(false); }); test('isUnhandledLineBreakKeyCombo returns false for f (random key)', () => { const e = { ...lineBreakHelpers.BASE_EVENT, key: Constants.KeyCodes.F[0], keyCode: Constants.KeyCodes.F[1], }; expect(Utils.isUnhandledLineBreakKeyCombo(e)).toBe(false); }); // restore initial user agent afterEach(ua.reset); }); describe('Utils.insertLineBreakFromKeyEvent', () => { test('insertLineBreakFromKeyEvent returns with line break appending (no selection range)', () => { expect(Utils.insertLineBreakFromKeyEvent(lineBreakHelpers.getAppendEvent())).toBe(lineBreakHelpers.OUTPUT_APPEND); }); test('insertLineBreakFromKeyEvent returns with line break replacing (with selection range)', () => { expect(Utils.insertLineBreakFromKeyEvent(lineBreakHelpers.getReplaceEvent())).toBe(lineBreakHelpers.OUTPUT_REPLACE); }); }); describe('Utils.copyTextAreaToDiv', () => { const textArea = document.createElement('textarea'); test('copyTextAreaToDiv actually creates a div element', () => { const copy = Utils.copyTextAreaToDiv(textArea); expect(copy!.nodeName).toEqual('DIV'); }); test('copyTextAreaToDiv copies the content into the div element', () => { textArea.value = 'the content'; const copy = Utils.copyTextAreaToDiv(textArea); expect(copy!.innerHTML).toEqual('the content'); }); test('copyTextAreaToDiv correctly copies the styles of the textArea element', () => { textArea.style.fontFamily = 'Sans-serif'; const copy = Utils.copyTextAreaToDiv(textArea); expect(copy!.style.fontFamily).toEqual('Sans-serif'); }); }); describe('Utils.getCaretXYCoordinate', () => { const tmpCreateRange = document.createRange; const cleanUp = () => { document.createRange = tmpCreateRange; }; afterAll(cleanUp); const textArea = document.createElement('textarea'); document.createRange = () => { const range = new Range(); range.getClientRects = () => { return [{ top: 10, left: 15, }] as unknown as DOMRectList; }; return range; }; textArea.value = 'm'.repeat(10); test('getCaretXYCoordinate returns the coordinates of the caret', () => { const coordinates = Utils.getCaretXYCoordinate(textArea); expect(coordinates.x).toEqual(15); expect(coordinates.y).toEqual(10); }); test('getCaretXYCoordinate returns the coordinates of the caret with a left scroll', () => { textArea.scrollLeft = 5; const coordinates = Utils.getCaretXYCoordinate(textArea); expect(coordinates.x).toEqual(10); }); }); describe('Utils.getViewportSize', () => { test('getViewportSize returns the right viewport using default jsDom window', () => { // the default values of the jsDom window are w: 1024, h: 768 const viewportDimensions = Utils.getViewportSize(); expect(viewportDimensions.w).toEqual(1024); expect(viewportDimensions.h).toEqual(768); }); test('getViewportSize returns the right viewport width with custom parameter', () => { const mockWindow = {document: {body: {}, compatMode: undefined}}; (mockWindow.document.body as any).clientWidth = 1025; (mockWindow.document.body as any).clientHeight = 860; const viewportDimensions = Utils.getViewportSize(mockWindow as unknown as Window); expect(viewportDimensions.w).toEqual(1025); expect(viewportDimensions.h).toEqual(860); }); test('getViewportSize returns the right viewport width with custom parameter - innerWidth', () => { const mockWindow = {innerWidth: 1027, innerHeight: 767}; const viewportDimensions = Utils.getViewportSize(mockWindow as unknown as Window); expect(viewportDimensions.w).toEqual(1027); expect(viewportDimensions.h).toEqual(767); }); }); describe('Utils.offsetTopLeft', () => { test('offsetTopLeft returns the right offset values', () => { const textArea = document.createElement('textArea'); textArea.getBoundingClientRect = jest.fn(() => ({ top: 967, left: 851, } as DOMRect)); const offsetTopLeft = Utils.offsetTopLeft(textArea); expect(offsetTopLeft.top).toEqual(967); expect(offsetTopLeft.left).toEqual(851); }); }); describe('Utils.getSuggestionBoxAlgn', () => { const tmpCreateRange = document.createRange; const cleanUp = () => { document.createRange = tmpCreateRange; }; afterAll(cleanUp); const textArea: HTMLTextAreaElement = document.createElement('textArea') as HTMLTextAreaElement; textArea.value = 'a'.repeat(30); jest.spyOn(textArea, 'offsetWidth', 'get'). mockImplementation(() => 950); textArea.getBoundingClientRect = jest.fn(() => ({ left: 50, } as DOMRect)); const createRange = (size: number) => { document.createRange = () => { const range = new Range(); range.getClientRects = () => { return [{ top: 100, left: size, }] as unknown as DOMRectList; }; return range; }; }; const fixedToTheRight = textArea.offsetWidth - Constants.SUGGESTION_LIST_MODAL_WIDTH; test('getSuggestionBoxAlgn returns 0 (box stuck to left) when the length of the text is small', () => { const smallSizeText = 15; createRange(smallSizeText); const suggestionBoxAlgn = Utils.getSuggestionBoxAlgn(textArea, Utils.getPxToSubstract()); expect(suggestionBoxAlgn.pixelsToMoveX).toEqual(0); }); test('getSuggestionBoxAlgn returns pixels to move when text is medium size', () => { const mediumSizeText = 155; createRange(mediumSizeText); const suggestionBoxAlgn = Utils.getSuggestionBoxAlgn(textArea, Utils.getPxToSubstract()); expect(suggestionBoxAlgn.pixelsToMoveX).toBeGreaterThan(0); expect(suggestionBoxAlgn.pixelsToMoveX).not.toBe(fixedToTheRight); }); test('getSuggestionBoxAlgn align box to the righ when text is large size', () => { const largeSizeText = 700; createRange(largeSizeText); const suggestionBoxAlgn = Utils.getSuggestionBoxAlgn(textArea, Utils.getPxToSubstract()); expect(fixedToTheRight).toEqual(suggestionBoxAlgn.pixelsToMoveX); }); }); describe('Utils.numberToFixedDynamic', () => { const tests = [ { label: 'Removes period when no decimals needed', num: 123.001, places: 2, expected: '123', }, { label: 'Extra places are ignored', num: 123.45, places: 3, expected: '123.45', }, { label: 'rounds positives', num: 123.45, places: 1, expected: '123.5', }, { label: 'rounds negatives', num: -123.45, places: 1, expected: '-123.5', }, { label: 'negative places interpreted as 0 places', num: 123, places: -1, expected: '123', }, { label: 'handles integers', num: 123, places: 4, expected: '123', }, { label: 'handles integers with 0 places', num: 123, places: 4, expected: '123', }, { label: 'correctly excludes decimal when rounding exlcudes number', num: 0.004, places: 2, expected: '0', }, ]; tests.forEach((testCase) => { test(testCase.label, () => { const actual = Utils.numberToFixedDynamic(testCase.num, testCase.places); expect(actual).toBe(testCase.expected); }); }); });
4,533
0
petrpan-code/mattermost/mattermost/webapp/channels/src
petrpan-code/mattermost/mattermost/webapp/channels/src/utils/youtube.test.ts
// Copyright (c) 2015-present Mattermost, Inc. All Rights Reserved. // See LICENSE.txt for license information. import {handleYoutubeTime} from 'utils/youtube'; describe('Utils.YOUTUBE', () => { test('should correctly parse youtube start time formats', () => { for (const {link, time} of [ { link: 'https://www.youtube.com/watch?time_continue=490&v=xqCoNej8Zxo', time: '&start=490', }, { link: 'https://www.youtube.com/watch?start=490&v=xqCoNej8Zxo', time: '&start=490', }, { link: 'https://www.youtube.com/watch?t=490&v=xqCoNej8Zxo', time: '&start=490', }, { link: 'https://www.youtube.com/watch?time=490&v=xqCoNej8Zxo', time: '&start=490', }, { link: 'https://www.youtube.com/watch?time=8m10s&v=xqCoNej8Zxo', time: '&start=490', }, { link: 'https://www.youtube.com/watch?time=1h8m10s&v=xqCoNej8Zxo', time: '&start=4090', }, { link: 'https://www.youtube.com/watch?v=xqCoNej8Zxo', time: '', }, { link: 'https://www.youtube.com/watch?time=&v=xqCoNej8Zxo', time: '', }, ]) { expect(handleYoutubeTime(link)).toEqual(time); } }); });
4,535
0
petrpan-code/mattermost/mattermost/webapp/channels/src/utils
petrpan-code/mattermost/mattermost/webapp/channels/src/utils/__snapshots__/admin_console_plugin_index.test.ts.snap
// Jest Snapshot v1, https://goo.gl/fbAQLP exports[`AdminConsolePluginsIndex.getPluginEntries should return map with the text extracted from plugins 1`] = ` Object { "plugin_mattermost-autolink": Array [ "admin.plugin.enable_plugin", "admin.plugin.enable_plugin.help", "PluginSettings.PluginStates.mattermost-autolink.Enable", "Autolink", "mattermost-autolink", "Configure this plugin directly in the config.json file. Learn more in our documentation. To report an issue, make a suggestion or a contribution, check the plugin repository.", "Enable administration with /autolink command", "EnableAdminCommand", ], } `; exports[`AdminConsolePluginsIndex.getPluginEntries should return map with the text extracted from plugins 2`] = ` Object { "plugin_Some-random-plugin": Array [ "admin.plugin.enable_plugin", "admin.plugin.enable_plugin.help", "PluginSettings.PluginStates.Some-random-plugin.Enable", "Random", "Some-random-plugin", "random plugin footer", "random plugin header", "Generate with /generateRand command", "/generateRand 10", "GenerateRandomNumber", "set range with /setRange command", "setRange", ], "plugin_mattermost-autolink": Array [ "admin.plugin.enable_plugin", "admin.plugin.enable_plugin.help", "PluginSettings.PluginStates.mattermost-autolink.Enable", "Autolink", "mattermost-autolink", "Configure this plugin directly in the config.json file. Learn more in our documentation. To report an issue, make a suggestion or a contribution, check the plugin repository.", "Enable administration with /autolink command", "EnableAdminCommand", ], } `;
4,536
0
petrpan-code/mattermost/mattermost/webapp/channels/src/utils
petrpan-code/mattermost/mattermost/webapp/channels/src/utils/__snapshots__/message_html_to_component.test.tsx.snap
// Jest Snapshot v1, https://goo.gl/fbAQLP exports[`messageHtmlToComponent At mention 1`] = ` <p> <span className="mention--highlight" > <span data-mention="joram" > <Memo(Connect(Component)) disableGroupHighlight={false} disableHighlight={false} hasMention={true} mentionName="joram" > @joram </Memo(Connect(Component))> </span> </span> </p> `; exports[`messageHtmlToComponent At mention 2`] = ` <p> <span data-mention="joram" > <Memo(Connect(Component)) disableGroupHighlight={false} disableHighlight={true} hasMention={true} mentionName="joram" > @joram </Memo(Connect(Component))> </span> </p> `; exports[`messageHtmlToComponent At mention with group highlight disabled 1`] = ` <p> <span data-mention="developers" > <Memo(Connect(Component)) disableGroupHighlight={false} disableHighlight={false} hasMention={true} mentionName="developers" > @developers </Memo(Connect(Component))> </span> </p> `; exports[`messageHtmlToComponent At mention with group highlight disabled 2`] = ` <p> <span data-mention="developers" > <Memo(Connect(Component)) disableGroupHighlight={true} disableHighlight={false} hasMention={true} mentionName="developers" > @developers </Memo(Connect(Component))> </span> </p> `; exports[`messageHtmlToComponent Inline markdown image 1`] = ` <div className="markdown-inline-img__container" > <Memo(Connect(MarkdownImage)) alt="Mattermost" className="markdown-inline-img" imageIsLink={false} postId="post_id" postType="system_header_change" src="/images/icon.png" /> and a <a className="theme markdown__link" href="http://link" rel="noreferrer" target="_blank" > link </a> </div> `; exports[`messageHtmlToComponent Inline markdown image where image is link 1`] = ` <div className="markdown-inline-img__container" > <a className="theme markdown__link" href="http://images/icon.png" rel="noreferrer" target="_blank" > <Memo(Connect(MarkdownImage)) alt="Mattermost" className="markdown-inline-img" imageIsLink={true} postId="post_id" postType="system_header_change" src="images/icon.png" /> </a> </div> `; exports[`messageHtmlToComponent html 1`] = ` <CodeBlock code="<div>This is a html div</div>" language="html" searchedContent="" /> `; exports[`messageHtmlToComponent latex 1`] = ` Array [ <p> This is some latex! </p>, " ", <Memo(Connect(LatexBlock)) content="x^2 + y^2 = z^2" />, <Memo(Connect(LatexBlock)) content="F_m - 2 = F_0 F_1 \\\\dots F_{m-1}" />, <p> That was some latex! </p>, ] `; exports[`messageHtmlToComponent link with enabled a tooltip plugin 1`] = ` <p> lorem ipsum <a className="theme markdown__link" href="http://www.dolor.com" rel="noreferrer" target="_blank" > <LinkTooltip attributes={ Object { "class": "theme markdown__link", "href": "http://www.dolor.com", "rel": "noreferrer", "target": "_blank", } } href="http://www.dolor.com" > www.dolor.com </LinkTooltip> </a> sit amet </p> `; exports[`messageHtmlToComponent link without enabled tooltip plugins 1`] = ` <p> lorem ipsum <a className="theme markdown__link" href="http://www.dolor.com" rel="noreferrer" target="_blank" > www.dolor.com </a> sit amet </p> `; exports[`messageHtmlToComponent plain text 1`] = ` <p> Hello, world! </p> `; exports[`messageHtmlToComponent typescript 1`] = ` <CodeBlock code="const myFunction = () => { console.log('This is a meaningful function'); };" language="typescript" searchedContent="" /> `; exports[`messageHtmlToComponent typescript 2`] = ` <p> Text before typescript codeblock <span className="codespan__pre-wrap" > <code> typescript const myFunction = () =&gt; { console.log('This is a test function'); }; </code> </span> text after typescript block </p> `;
4,537
0
petrpan-code/mattermost/mattermost/webapp/channels/src/utils
petrpan-code/mattermost/mattermost/webapp/channels/src/utils/markdown/apply_markdown.test.tsx
// Copyright (c) 2015-present Mattermost, Inc. All Rights Reserved. // See LICENSE.txt for license information. import {applyMarkdown} from './apply_markdown'; describe('applyMarkdown', () => { /* *************** * ORDERED LIST * ************** */ test('should add ordered list to selected newline', () => { const value = 'brown\nfox jumps over lazy dog'; const result = applyMarkdown({ message: value, selectionStart: 5, selectionEnd: 6, markdownMode: 'ol', }); expect(result).toEqual({ message: '1. brown\n2. fox jumps over lazy dog', selectionStart: 8, selectionEnd: 12, }); }); test('should add ordered list', () => { const value = 'brown\nfox jumps over lazy dog'; const result = applyMarkdown({ message: value, selectionStart: 0, selectionEnd: 10, markdownMode: 'ol', }); expect(result).toEqual({ message: '1. brown\n2. fox jumps over lazy dog', selectionStart: 3, selectionEnd: 16, }); }); test('should remove ordered list', () => { const value = '0. brown\n1. fox jumps over lazy dog'; const result = applyMarkdown({ message: value, selectionStart: 0, selectionEnd: 0, markdownMode: 'ol', }); expect(result).toEqual({ message: 'brown\n1. fox jumps over lazy dog', selectionStart: 0, selectionEnd: 0, }); }); test('should remove ordered list', () => { // '0. brown\n2. f' const value = '0. brown\n1. fox jumps over lazy dog'; const result = applyMarkdown({ message: value, selectionStart: 0, selectionEnd: 13, markdownMode: 'ol', }); expect(result).toEqual({ message: 'brown\nfox jumps over lazy dog', selectionStart: 0, selectionEnd: 7, }); }); /* *************** * UNORDERED LIST * ************** */ test('should apply unordered list', () => { const value = 'brown fox jumps over lazy dog'; const result = applyMarkdown({ message: value, selectionStart: 0, selectionEnd: 0, markdownMode: 'ul', }); expect(result).toEqual({ message: '- ' + value, selectionStart: 2, selectionEnd: 2, }); }); test('should remove markdown, and not remove text similar to markdown signs from the string content', () => { const value = '- brown fox - jumps - over lazy dog'; const result = applyMarkdown({ message: value, selectionStart: 0, selectionEnd: 0, markdownMode: 'ul', }); expect(result).toEqual({ message: value.substring(2), selectionStart: 0, selectionEnd: 0, }); }); test('should remove markdown, and not remove text similar to markdown signs from the string content', () => { const value = '- brown fox - jumps - over lazy dog'; const result = applyMarkdown({ message: value, selectionStart: 0, selectionEnd: 0, markdownMode: 'ul', }); expect(result).toEqual({ message: value.substring(2), selectionStart: 0, selectionEnd: 0, }); }); /* *************** * HEADING * ************** */ test('heading markdown: should apply header', () => { const value = 'brown fox jumps over lazy dog'; const result = applyMarkdown({ selectionStart: 0, selectionEnd: 10, message: value, markdownMode: 'heading', }); expect(result).toEqual({ message: '### ' + value, selectionStart: 4, selectionEnd: 14, }); }); test('heading markdown: should remove header', () => { const value = '### brown fox jumps over lazy dog'; const result = applyMarkdown({ selectionStart: 9, selectionEnd: 14, message: value, markdownMode: 'heading', }); expect(result).toEqual({ message: value.substring(4), selectionStart: 5, selectionEnd: 10, }); }); test('heading markdown: should add multiline headings', () => { const value = 'brown\nfox\njumps\nover lazy dog'; const result = applyMarkdown({ selectionStart: 8, selectionEnd: 15, message: value, markdownMode: 'heading', }); expect(result).toEqual({ message: 'brown\n### fox\n### jumps\nover lazy dog', selectionStart: 12, selectionEnd: 23, }); }); test('heading markdown: should remove multiline headings', () => { // 'x\n### jumps' const value = 'brown\n### fox\n### jumps\nover lazy dog'; const result = applyMarkdown({ selectionStart: 12, selectionEnd: 23, message: value, markdownMode: 'heading', }); expect(result).toEqual({ message: 'brown\nfox\njumps\nover lazy dog', selectionStart: 8, selectionEnd: 15, }); }); test('heading markdown: should remove multiline headings (selection includes first line)', () => { const value = '### brown\n### fox\n### jumps\nover lazy dog'; const result = applyMarkdown({ selectionStart: 1, selectionEnd: 23, message: value, markdownMode: 'heading', }); expect(result).toEqual({ message: 'brown\nfox\njumps\nover lazy dog', selectionStart: 0, selectionEnd: 11, }); }); test('heading markdown: should add multiline headings (selection starts with new line)', () => { // '\nfox\njump' const value = 'brown\nfox\njumps\nover lazy dog'; const result = applyMarkdown({ selectionStart: 5, selectionEnd: 14, message: value, markdownMode: 'heading', }); expect(result).toEqual({ message: '### brown\n### fox\n### jumps\nover lazy dog', selectionStart: 9, selectionEnd: 26, }); }); /* *************** * QUOTE * ************** */ test('heading markdown: should apply quote', () => { const value = 'brown fox jumps over lazy dog'; const result = applyMarkdown({ selectionStart: 0, selectionEnd: 0, message: value, markdownMode: 'quote', }); expect(result).toEqual({ message: '> ' + value, selectionStart: 2, selectionEnd: 2, }); }); test('heading markdown: should apply quote', () => { const value = 'brown fox jumps over lazy dog'; const result = applyMarkdown({ selectionStart: 0, selectionEnd: 10, message: value, markdownMode: 'quote', }); expect(result).toEqual({ message: '> ' + value, selectionStart: 2, selectionEnd: 12, }); }); test('heading markdown: should remove quote', () => { const value = '> brown fox jumps over lazy dog'; const result = applyMarkdown({ selectionStart: 9, selectionEnd: 14, message: value, markdownMode: 'quote', }); expect(result).toEqual({ message: value.substring(2), selectionStart: 7, selectionEnd: 12, }); }); /* *************** * BOLD & ITALIC * ************** */ test('applyMarkdown returns correct markdown for bold hotkey', () => { // "Fafda" is selected with ctrl + B hotkey const result = applyMarkdown({ message: 'Jalebi Fafda & Sambharo', selectionStart: 7, selectionEnd: 12, markdownMode: 'bold', }); expect(result).toEqual({ message: 'Jalebi **Fafda** & Sambharo', selectionStart: 9, selectionEnd: 14, }); }); test('applyMarkdown returns correct markdown for undo bold', () => { // "Fafda" is selected with ctrl + B hotkey const result = applyMarkdown({ message: 'Jalebi **Fafda** & Sambharo', selectionStart: 9, selectionEnd: 14, markdownMode: 'bold', }); expect(result).toEqual({ message: 'Jalebi Fafda & Sambharo', selectionStart: 7, selectionEnd: 12, }); }); test('applyMarkdown returns correct markdown for italic hotkey', () => { // "Fafda" is selected with ctrl + I hotkey const result = applyMarkdown({ message: 'Jalebi Fafda & Sambharo', selectionStart: 7, selectionEnd: 12, markdownMode: 'italic', }); expect(result).toEqual({ message: 'Jalebi *Fafda* & Sambharo', selectionStart: 8, selectionEnd: 13, }); }); test('applyMarkdown returns correct markdown for undo italic', () => { // "Fafda" is selected with ctrl + I hotkey const result = applyMarkdown({ message: 'Jalebi *Fafda* & Sambharo', selectionStart: 8, selectionEnd: 13, markdownMode: 'italic', }); expect(result).toEqual({ message: 'Jalebi Fafda & Sambharo', selectionStart: 7, selectionEnd: 12, }); }); test('applyMarkdown returns correct markdown for bold hotkey and empty', () => { // Nothing is selected with ctrl + B hotkey and caret is just before "Fafda" const result = applyMarkdown({ message: 'Jalebi Fafda & Sambharo', selectionStart: 7, selectionEnd: 7, markdownMode: 'bold', }); expect(result).toEqual({ message: 'Jalebi ****Fafda & Sambharo', selectionStart: 9, selectionEnd: 9, }); }); test('applyMarkdown returns correct markdown for italic hotkey and empty', () => { // Nothing is selected with ctrl + I hotkey and caret is just before "Fafda" const result = applyMarkdown({ message: 'Jalebi Fafda & Sambharo', selectionStart: 7, selectionEnd: 7, markdownMode: 'italic', }); expect(result).toEqual({ message: 'Jalebi **Fafda & Sambharo', selectionStart: 8, selectionEnd: 8, }); }); test('applyMarkdown returns correct markdown for italic with bold', () => { // "Fafda" is selected with ctrl + I hotkey const result = applyMarkdown({ message: 'Jalebi **Fafda** & Sambharo', selectionStart: 9, selectionEnd: 14, markdownMode: 'italic', }); expect(result).toEqual({ message: 'Jalebi ***Fafda*** & Sambharo', selectionStart: 10, selectionEnd: 15, }); }); test('applyMarkdown returns correct markdown for bold with italic', () => { // "Fafda" is selected with ctrl + B hotkey const result = applyMarkdown({ message: 'Jalebi *Fafda* & Sambharo', selectionStart: 8, selectionEnd: 13, markdownMode: 'bold', }); expect(result).toEqual({ message: 'Jalebi ***Fafda*** & Sambharo', selectionStart: 10, selectionEnd: 15, }); }); test('applyMarkdown returns correct markdown for bold with italic+bold', () => { // "Fafda" is selected with ctrl + B hotkey const result = applyMarkdown({ message: 'Jalebi ***Fafda*** & Sambharo', selectionStart: 10, selectionEnd: 15, markdownMode: 'bold', }); // Should undo bold expect(result).toEqual({ message: 'Jalebi *Fafda* & Sambharo', selectionStart: 8, selectionEnd: 13, }); }); test('applyMarkdown returns correct markdown for italic with italic+bold', () => { // "Fafda" is selected with ctrl + I hotkey const result = applyMarkdown({ message: 'Jalebi ***Fafda*** & Sambharo', selectionStart: 10, selectionEnd: 15, markdownMode: 'italic', }); // Should undo italic expect(result).toEqual({ message: 'Jalebi **Fafda** & Sambharo', selectionStart: 9, selectionEnd: 14, }); }); /* *************** * CODE (inline code and code block) * ************** */ test('should apply inline code markdown to the selection', () => { // "Fafda" is selected with ctrl + alt + C hotkey const result = applyMarkdown({ message: 'Jalebi Fafda & Sambharo', selectionStart: 7, selectionEnd: 12, markdownMode: 'code', }); expect(result).toEqual({ message: 'Jalebi `Fafda` & Sambharo', selectionStart: 8, selectionEnd: 13, }); }); test('should remove inline code markdown to the selection', () => { // "Fafda" is selected with ctrl + alt + C hotkey const result = applyMarkdown({ message: 'Jalebi `Fafda` & Sambharo', selectionStart: 8, selectionEnd: 13, markdownMode: 'code', }); expect(result).toEqual({ message: 'Jalebi Fafda & Sambharo', selectionStart: 7, selectionEnd: 12, }); }); test('should apply code block markdown to the full message (multi-lines)', () => { // all message is selected with ctrl + alt + C hotkey const result = applyMarkdown({ message: 'Jalebi\nFafda\nSambharo', selectionStart: 0, selectionEnd: 21, markdownMode: 'code', }); expect(result).toEqual({ message: '```\nJalebi\nFafda\nSambharo\n```', selectionStart: 4, selectionEnd: 25, }); }); test('should remove code block markdown to the full message', () => { // all message is selected with ctrl + alt + C hotkey const result = applyMarkdown({ message: '```\nJalebi\nFafda\nSambharo\n```', selectionStart: 4, selectionEnd: 25, markdownMode: 'code', }); expect(result).toEqual({ message: 'Jalebi\nFafda\nSambharo', selectionStart: 0, selectionEnd: 21, }); }); test('should apply code block markdown to the sub-message (multi-lines)', () => { // "bi\nFaf" is selected with ctrl + alt + C hotkey const result = applyMarkdown({ message: 'Jalebi\nFafda\nSambharo', selectionStart: 4, selectionEnd: 10, markdownMode: 'code', }); expect(result).toEqual({ message: 'Jale```\nbi\nFaf\n```da\nSambharo', selectionStart: 8, selectionEnd: 14, }); }); test('should remove code block markdown to the sub-message', () => { // "bi\nFaf" is selected with ctrl + alt + C hotkey const result = applyMarkdown({ message: 'Jale```\nbi\nFaf\n```da\nSambharo', selectionStart: 8, selectionEnd: 14, markdownMode: 'code', }); expect(result).toEqual({ message: 'Jalebi\nFafda\nSambharo', selectionStart: 4, selectionEnd: 10, }); }); });
4,539
0
petrpan-code/mattermost/mattermost/webapp/channels/src/utils
petrpan-code/mattermost/mattermost/webapp/channels/src/utils/markdown/helpers.test.ts
// Copyright (c) 2015-present Mattermost, Inc. All Rights Reserved. // See LICENSE.txt for license information. import {parseImageDimensions} from './helpers'; describe('parseImageDimensions', () => { test('should return the original href when no dimensions are provided', () => { expect(parseImageDimensions('https://example.com')).toEqual({href: 'https://example.com', height: '', width: ''}); expect(parseImageDimensions('https://example.com/something.png')).toEqual({href: 'https://example.com/something.png', height: '', width: ''}); expect(parseImageDimensions('https://example.com/%20%20')).toEqual({href: 'https://example.com/%20%20', height: '', width: ''}); }); test('should return full dimensions when provided', () => { expect(parseImageDimensions('https://example.com/image.png =50x80')).toEqual({href: 'https://example.com/image.png', height: '80', width: '50'}); }); test('should return auto height when not provided', () => { expect(parseImageDimensions('https://example.com/image.png =50')).toEqual({href: 'https://example.com/image.png', height: 'auto', width: '50'}); }); test('should return auto width when not provided', () => { expect(parseImageDimensions('https://example.com/image.png =x60')).toEqual({href: 'https://example.com/image.png', height: '60', width: 'auto'}); }); test('should return the original href when invalid dimensions are provided', () => { expect(parseImageDimensions('https://example.com =')).toEqual({href: 'https://example.com =', height: '', width: ''}); expect(parseImageDimensions('https://example.com =x')).toEqual({href: 'https://example.com =x', height: '', width: ''}); expect(parseImageDimensions('https://example.com=400x500')).toEqual({href: 'https://example.com=400x500', height: '', width: ''}); }); });
4,541
0
petrpan-code/mattermost/mattermost/webapp/channels/src/utils
petrpan-code/mattermost/mattermost/webapp/channels/src/utils/markdown/index.test.ts
// Copyright (c) 2015-present Mattermost, Inc. All Rights Reserved. // See LICENSE.txt for license information. import {format} from './index'; describe('format', () => { const htmlOutput = '<div data-codeblock-code="{code}" data-codeblock-language="{language}" data-codeblock-searchedcontent=""></div>'; test('should return valid div for html to component transformation', () => { const language = 'diff'; const code = ` - something + something else `; const text = `~~~${language}\n${code}\n~~~`; const output = format(text); expect(output).toContain(htmlOutput.replace('{code}', code).replace('{language}', language)); }); test('should return valid div for tex/latex language', () => { const languageTex = 'tex'; const texCode = ` F_m - 2 = F_0 F_1 \\dots F_{m-1} `; const languageLatex = 'latex'; const latexCode = ` x^2 + y^2 = z^2 `; const outputTex = format(`~~~${languageTex}\n${texCode}\n~~~`); expect(outputTex).toContain(`<div data-latex="${texCode}"></div>`); const outputLatex = format(`~~~${languageLatex}\n${latexCode}\n~~~`); expect(outputLatex).toContain(`<div data-latex="${latexCode}"></div>`); }); describe('lists', () => { test('unordered lists should not include a start index', () => { const input = `- a - b - c`; const expected = `<ul className="markdown__list"> <li><span>a</span></li><li><span>b</span></li><li><span>c</span></li></ul>`; const output = format(input); expect(output).toBe(expected); }); test('ordered lists starting at 1 should include a start index', () => { const input = `1. a 2. b 3. c`; const expected = `<ol className="markdown__list" style="counter-reset: list 0"> <li><span>a</span></li><li><span>b</span></li><li><span>c</span></li></ol>`; const output = format(input); expect(output).toBe(expected); }); test('ordered lists starting at 0 should include a start index', () => { const input = `0. a 1. b 2. c`; const expected = `<ol className="markdown__list" style="counter-reset: list -1"> <li><span>a</span></li><li><span>b</span></li><li><span>c</span></li></ol>`; const output = format(input); expect(output).toBe(expected); }); test('ordered lists starting at any other number should include a start index', () => { const input = `999. a 1. b 1. c`; const expected = `<ol className="markdown__list" style="counter-reset: list 998"> <li><span>a</span></li><li><span>b</span></li><li><span>c</span></li></ol>`; const output = format(input); expect(output).toBe(expected); }); }); test('should not wrap code with a valid language tag', () => { const output = format(`~~~java this is long text this is long text this is long text this is long text this is long text this is long text ~~~`); expect(output).not.toContain('post-code--wrap'); }); test('should not wrap code with an invalid language', () => { const output = format(`~~~nowrap this is long text this is long text this is long text this is long text this is long text this is long text ~~~`); expect(output).not.toContain('post-code--wrap'); }); test('<a> should contain target=_blank for external links', () => { const output = format('[external_link](http://example.com)', {siteURL: 'http://localhost'}); expect(output).toContain('<a class="theme markdown__link" href="http://example.com" rel="noreferrer" target="_blank">external_link</a>'); }); test('<a> should not contain target=_blank for internal links', () => { const output = format('[internal_link](http://localhost/example)', {siteURL: 'http://localhost'}); expect(output).toContain('<a class="theme markdown__link" href="http://localhost/example" rel="noreferrer" data-link="/example">internal_link</a>'); }); test('<a> should contain target=_blank for internal links that live under /plugins', () => { const output = format('[internal_link](http://localhost/plugins/example)', {siteURL: 'http://localhost'}); expect(output).toContain('<a class="theme markdown__link" href="http://localhost/plugins/example" rel="noreferrer" target="_blank">internal_link</a>'); }); test('<a> should contain target=_blank for internal links that are files', () => { const output = format('http://localhost/files/o6eujqkmjfd138ykpzmsmc131y/public?h=j5nPX8JlgUeNVMOB3dLXwyG_jlxlSw4nSgZmegXfpHw', {siteURL: 'http://localhost'}); expect(output).toContain('<a class="theme markdown__link" href="http://localhost/files/o6eujqkmjfd138ykpzmsmc131y/public?h=j5nPX8JlgUeNVMOB3dLXwyG_jlxlSw4nSgZmegXfpHw" rel="noreferrer" target="_blank">http://localhost/files/o6eujqkmjfd138ykpzmsmc131y/public?h=j5nPX8JlgUeNVMOB3dLXwyG_jlxlSw4nSgZmegXfpHw</a>'); }); test('<a> should not contain target=_blank for pl|channels|messages links', () => { const pl = format('[thread](/reiciendis-0/pl/b3hrs3brjjn7fk4kge3xmeuffc))', {siteURL: 'http://localhost'}); expect(pl).toContain('<a class="theme markdown__link" href="/reiciendis-0/pl/b3hrs3brjjn7fk4kge3xmeuffc" rel="noreferrer" data-link="/reiciendis-0/pl/b3hrs3brjjn7fk4kge3xmeuffc">thread</a>'); const channels = format('[thread](/reiciendis-0/channels/b3hrs3brjjn7fk4kge3xmeuffc))', {siteURL: 'http://localhost'}); expect(channels).toContain('<a class="theme markdown__link" href="/reiciendis-0/channels/b3hrs3brjjn7fk4kge3xmeuffc" rel="noreferrer" data-link="/reiciendis-0/channels/b3hrs3brjjn7fk4kge3xmeuffc">thread</a>'); const messages = format('[thread](/reiciendis-0/messages/b3hrs3brjjn7fk4kge3xmeuffc))', {siteURL: 'http://localhost'}); expect(messages).toContain('<a class="theme markdown__link" href="/reiciendis-0/messages/b3hrs3brjjn7fk4kge3xmeuffc" rel="noreferrer" data-link="/reiciendis-0/messages/b3hrs3brjjn7fk4kge3xmeuffc">thread</a>'); const plugin = format('[plugin](/reiciendis-0/plugins/example))', {siteURL: 'http://localhost'}); expect(plugin).toContain('<a class="theme markdown__link" href="/reiciendis-0/plugins/example" rel="noreferrer" data-link="/reiciendis-0/plugins/example">plugin</a>'); }); describe('should correctly open links in the current tab based on whether they are handled by the web app', () => { for (const testCase of [{name: 'regular link', link: 'https://example.com', handled: false}, {name: 'www link', link: 'www.example.com', handled: false}, {name: 'link to a channel', link: 'http://localhost/team/channels/foo', handled: true}, {name: 'link to a DM', link: 'http://localhost/team/messages/@bar', handled: true}, {name: 'link to the system console', link: 'http://localhost/admin_console', handled: true}, {name: 'permalink', link: 'http://localhost/reiciendis-0/pl/b3hrs3brjjn7fk4kge3xmeuffc', handled: true}, {name: 'link to a specific system console page', link: 'http://localhost/admin_console/plugins/plugin_com.github.matterpoll.matterpoll', handled: true}, {name: 'relative link', link: '/', handled: true}, {name: 'relative link to a channel', link: '/reiciendis-0/channels/b3hrs3brjjn7fk4kge3xmeuffc', handled: true}, {name: 'relative link to a DM', link: '/reiciendis-0/messages/b3hrs3brjjn7fk4kge3xmeuffc', handled: true}, {name: 'relative permalink', link: '/reiciendis-0/pl/b3hrs3brjjn7fk4kge3xmeuffc', handled: true}, {name: 'relative link to the system console', link: '/admin_console', handled: true}, {name: 'relative link to a specific system console page', link: '/admin_console/plugins/plugin_com.github.matterpoll.matterpoll', handled: true}, {name: 'link to a plugin-handled path', link: 'http://localhost/plugins/example', handled: false}, {name: 'link to a file attachment public link', link: 'http://localhost/files/o6eujqkmjfd138ykpzmsmc131y/public?h=j5nPX8JlgUeNVMOB3dLXwyG_jlxlSw4nSgZmegXfpHw', handled: false}, {name: 'relative link to a plugin-handled path', link: '/plugins/example', handled: false}, {name: 'relative link to a file attachment public link', link: '/files/o6eujqkmjfd138ykpzmsmc131y/public?h=j5nPX8JlgUeNVMOB3dLXwyG_jlxlSw4nSgZmegXfpHw', handled: false}, {name: 'link to a managed resource', link: 'http://localhost/trusted/jitsi', options: {managedResourcePaths: ['trusted']}, handled: false}, {name: 'relative link to a managed resource', link: '/trusted/jitsi', options: {managedResourcePaths: ['trusted']}, handled: false}, {name: 'link that is not to a managed resource', link: 'http://localhost/trusted/jitsi', options: {managedResourcePaths: ['jitsi']}, handled: true}, ]) { test(testCase.name, () => { const options = { siteURL: 'http://localhost', ...testCase.options, }; const output = format(`[link](${testCase.link})`, options); if (testCase.handled) { expect(output).not.toContain('target="_blank"'); } else { expect(output).toContain('rel="noreferrer" target="_blank"'); } }); } }); });
4,543
0
petrpan-code/mattermost/mattermost/webapp/channels/src/utils
petrpan-code/mattermost/mattermost/webapp/channels/src/utils/markdown/link_only_renderer.test.tsx
// Copyright (c) 2015-present Mattermost, Inc. All Rights Reserved. // See LICENSE.txt for license information. import {formatWithRenderer} from 'utils/markdown'; import LinkOnlyRenderer from 'utils/markdown/link_only_renderer'; describe('formatWithRenderer | LinkOnlyRenderer', () => { const testCases = [ { description: 'emoji: same', inputText: 'Hey :smile: :+1: :)', outputText: 'Hey :smile: :+1: :)', }, { description: 'at-mention: same', inputText: 'Hey @user and @test', outputText: 'Hey @user and @test', }, { description: 'channel-link: same', inputText: 'join ~channelname', outputText: 'join ~channelname', }, { description: 'codespan: single backtick', inputText: '`single backtick`', outputText: 'single backtick', }, { description: 'codespan: double backtick', inputText: '``double backtick``', outputText: 'double backtick', }, { description: 'codespan: triple backtick', inputText: '```triple backtick```', outputText: 'triple backtick', }, { description: 'codespan: inline code', inputText: 'Inline `code` has ``double backtick`` and ```triple backtick``` around it.', outputText: 'Inline code has double backtick and triple backtick around it.', }, { description: 'code block: single line code block', inputText: 'Code block\n```\nline\n```', outputText: 'Code block line', }, { description: 'code block: multiline code block 2', inputText: 'Multiline\n```function(number) {\n return number + 1;\n}```', outputText: 'Multiline function(number) { return number + 1; }', }, { description: 'code block: language highlighting', inputText: '```javascript\nvar s = "JavaScript syntax highlighting";\nalert(s);\n```', outputText: 'var s = "JavaScript syntax highlighting"; alert(s);', }, { description: 'blockquote:', inputText: '> Hey quote', outputText: 'Hey quote', }, { description: 'blockquote: multiline', inputText: '> Hey quote.\n> Hello quote.', outputText: 'Hey quote. Hello quote.', }, { description: 'heading: # H1 header', inputText: '# H1 header', outputText: 'H1 header', }, { description: 'heading: heading with @user', inputText: '# H1 @user', outputText: 'H1 @user', }, { description: 'heading: ## H2 header', inputText: '## H2 header', outputText: 'H2 header', }, { description: 'heading: ### H3 header', inputText: '### H3 header', outputText: 'H3 header', }, { description: 'heading: #### H4 header', inputText: '#### H4 header', outputText: 'H4 header', }, { description: 'heading: ##### H5 header', inputText: '##### H5 header', outputText: 'H5 header', }, { description: 'heading: ###### H6 header', inputText: '###### H6 header', outputText: 'H6 header', }, { description: 'heading: multiline with header and paragraph', inputText: '###### H6 header\nThis is next line.\nAnother line.', outputText: 'H6 header This is next line. Another line.', }, { description: 'heading: multiline with header and list items', inputText: '###### H6 header\n- list item 1\n- list item 2', outputText: 'H6 header list item 1 list item 2', }, { description: 'heading: multiline with header and links', inputText: '###### H6 header\n[link 1](https://mattermost.com) - [link 2](https://mattermost.com)', outputText: 'H6 header <a class="theme markdown__link" href="https://mattermost.com" target="_blank">' + 'link 1</a> - <a class="theme markdown__link" href="https://mattermost.com" target="_blank">link 2</a>', }, { description: 'list: 1. First ordered list item', inputText: '1. First ordered list item', outputText: 'First ordered list item', }, { description: 'list: 2. Another item', inputText: '1. 2. Another item', outputText: 'Another item', }, { description: 'list: * Unordered sub-list.', inputText: '* Unordered sub-list.', outputText: 'Unordered sub-list.', }, { description: 'list: - Or minuses', inputText: '- Or minuses', outputText: 'Or minuses', }, { description: 'list: + Or pluses', inputText: '+ Or pluses', outputText: 'Or pluses', }, { description: 'list: multiline', inputText: '1. First ordered list item\n2. Another item', outputText: 'First ordered list item Another item', }, { description: 'tablerow:)', inputText: 'Markdown | Less | Pretty\n' + '--- | --- | ---\n' + '*Still* | `renders` | **nicely**\n' + '1 | 2 | 3\n', outputText: '', }, { description: 'table:', inputText: '| Tables | Are | Cool |\n' + '| ------------- |:-------------:| -----:|\n' + '| col 3 is | right-aligned | $1600 |\n' + '| col 2 is | centered | $12 |\n' + '| zebra stripes | are neat | $1 |\n', outputText: '', }, { description: 'strong: Bold with **asterisks** or __underscores__.', inputText: 'Bold with **asterisks** or __underscores__.', outputText: 'Bold with asterisks or underscores.', }, { description: 'strong & em: Bold and italics with **asterisks and _underscores_**.', inputText: 'Bold and italics with **asterisks and _underscores_**.', outputText: 'Bold and italics with asterisks and underscores.', }, { description: 'em: Italics with *asterisks* or _underscores_.', inputText: 'Italics with *asterisks* or _underscores_.', outputText: 'Italics with asterisks or underscores.', }, { description: 'del: Strikethrough ~~strike this.~~', inputText: 'Strikethrough ~~strike this.~~', outputText: 'Strikethrough strike this.', }, { description: 'links: [inline-style link](http://localhost:8065)', inputText: '[inline-style link](http://localhost:8065)', outputText: '<a class="theme markdown__link" href="http://localhost:8065" target="_blank">' + 'inline-style link</a>', }, { description: 'image: ![image link](http://localhost:8065/image)', inputText: '![image link](http://localhost:8065/image)', outputText: 'image link', }, { description: 'text: plain', inputText: 'This is plain text.', outputText: 'This is plain text.', }, { description: 'text: multiline', inputText: 'This is multiline text.\nHere is the next line.\n', outputText: 'This is multiline text. Here is the next line.', }, { description: 'text: &amp; entity', inputText: 'you & me', outputText: 'you &amp; me', }, { description: 'text: &lt; entity', inputText: '1<2', outputText: '1&lt;2', }, { description: 'text: &gt; entity', inputText: '2>1', outputText: '2&gt;1', }, { description: 'text: &#39; entity', inputText: 'he\'s out', outputText: 'he&#39;s out', }, { description: 'text: &quot; entity', inputText: 'That is "unique"', outputText: 'That is &quot;unique&quot;', }, { description: 'text: multiple entities', inputText: '&<>\'"', outputText: '&amp;&lt;&gt;&#39;&quot;', }, { description: 'text: multiple entities', inputText: '"\'><&', outputText: '&quot;&#39;&gt;&lt;&amp;', }, { description: 'text: multiple entities', inputText: '&amp;&lt;&gt;&#39;&quot;', outputText: '&amp;&lt;&gt;&#39;&quot;', }, { description: 'text: multiple entities', inputText: '&quot;&#39;&gt;&lt;&amp;', outputText: '&quot;&#39;&gt;&lt;&amp;', }, { description: 'text: multiple entities', inputText: '&amp;lt;', outputText: '&amp;lt;', }, { description: 'text: empty string', inputText: '', outputText: '', }, { description: 'link: link without a scheme', inputText: 'Do you like www.mattermost.com?', outputText: 'Do you like <a class="theme markdown__link" href="http://www.mattermost.com" target="_blank">' + 'www.mattermost.com</a>?', }, { description: 'link: link with a scheme', inputText: 'Do you like http://www.mattermost.com?', outputText: 'Do you like <a class="theme markdown__link" href="http://www.mattermost.com" target="_blank">' + 'http://www.mattermost.com</a>?', }, { description: 'link: link with a title', inputText: 'Do you like [Mattermost](http://www.mattermost.com)?', outputText: 'Do you like <a class="theme markdown__link" href="http://www.mattermost.com" target="_blank">' + 'Mattermost</a>?', }, { description: 'link: link with curly brackets', inputText: 'Let\'s try http://example/result?things={stuff}', outputText: 'Let&#39;s try <a class="theme markdown__link" href="http://example/result?things={stuff}" target="_blank">http://example/result?things={stuff}</a>', }, ]; const linkOnlyRenderer = new LinkOnlyRenderer(); testCases.forEach((testCase) => it(testCase.description, () => { expect(formatWithRenderer(testCase.inputText, linkOnlyRenderer)).toEqual(testCase.outputText); })); });
4,547
0
petrpan-code/mattermost/mattermost/webapp/channels/src/utils
petrpan-code/mattermost/mattermost/webapp/channels/src/utils/markdown/remove_markdown.test.tsx
// Copyright (c) 2015-present Mattermost, Inc. All Rights Reserved. // See LICENSE.txt for license information. import React from 'react'; import {stripMarkdown} from 'utils/markdown'; describe('stripMarkdown | RemoveMarkdown', () => { const testCases = [ { description: 'emoji: same', inputText: 'Hey :smile: :+1: :)', outputText: 'Hey :smile: :+1: :)', }, { description: 'at-mention: same', inputText: 'Hey @user and @test', outputText: 'Hey @user and @test', }, { description: 'channel-link: same', inputText: 'join ~channelname', outputText: 'join ~channelname', }, { description: 'codespan: single backtick', inputText: '`single backtick`', outputText: 'single backtick', }, { description: 'codespan: double backtick', inputText: '``double backtick``', outputText: 'double backtick', }, { description: 'codespan: triple backtick', inputText: '```triple backtick```', outputText: 'triple backtick', }, { description: 'codespan: inline code', inputText: 'Inline `code` has ``double backtick`` and ```triple backtick``` around it.', outputText: 'Inline code has double backtick and triple backtick around it.', }, { description: 'code block: single line code block', inputText: 'Code block\n```\nline\n```', outputText: 'Code block line', }, { description: 'code block: multiline code block 2', inputText: 'Multiline\n```function(number) {\n return number + 1;\n}```', outputText: 'Multiline function(number) { return number + 1; }', }, { description: 'code block: language highlighting', inputText: '```javascript\nvar s = "JavaScript syntax highlighting";\nalert(s);\n```', outputText: 'var s = "JavaScript syntax highlighting"; alert(s);', }, { description: 'blockquote:', inputText: '> Hey quote', outputText: 'Hey quote', }, { description: 'blockquote: multiline', inputText: '> Hey quote.\n> Hello quote.', outputText: 'Hey quote. Hello quote.', }, { description: 'heading: # H1 header', inputText: '# H1 header', outputText: 'H1 header', }, { description: 'heading: heading with @user', inputText: '# H1 @user', outputText: 'H1 @user', }, { description: 'heading: ## H2 header', inputText: '## H2 header', outputText: 'H2 header', }, { description: 'heading: ### H3 header', inputText: '### H3 header', outputText: 'H3 header', }, { description: 'heading: #### H4 header', inputText: '#### H4 header', outputText: 'H4 header', }, { description: 'heading: ##### H5 header', inputText: '##### H5 header', outputText: 'H5 header', }, { description: 'heading: ###### H6 header', inputText: '###### H6 header', outputText: 'H6 header', }, { description: 'heading: multiline with header and paragraph', inputText: '###### H6 header\nThis is next line.\nAnother line.', outputText: 'H6 header This is next line. Another line.', }, { description: 'heading: multiline with header and list items', inputText: '###### H6 header\n- list item 1\n- list item 2', outputText: 'H6 header list item 1 list item 2', }, { description: 'heading: multiline with header and links', inputText: '###### H6 header\n[link 1](https://mattermost.com) - [link 2](https://mattermost.com)', outputText: 'H6 header link 1 - link 2', }, { description: 'list: 1. First ordered list item', inputText: '1. First ordered list item', outputText: 'First ordered list item', }, { description: 'list: 2. Another item', inputText: '1. 2. Another item', outputText: 'Another item', }, { description: 'list: * Unordered sub-list.', inputText: '* Unordered sub-list.', outputText: 'Unordered sub-list.', }, { description: 'list: - Or minuses', inputText: '- Or minuses', outputText: 'Or minuses', }, { description: 'list: + Or pluses', inputText: '+ Or pluses', outputText: 'Or pluses', }, { description: 'list: multiline', inputText: '1. First ordered list item\n2. Another item', outputText: 'First ordered list item Another item', }, { description: 'tablerow:)', inputText: 'Markdown | Less | Pretty\n' + '--- | --- | ---\n' + '*Still* | `renders` | **nicely**\n' + '1 | 2 | 3\n', outputText: '', }, { description: 'table:', inputText: '| Tables | Are | Cool |\n' + '| ------------- |:-------------:| -----:|\n' + '| col 3 is | right-aligned | $1600 |\n' + '| col 2 is | centered | $12 |\n' + '| zebra stripes | are neat | $1 |\n', outputText: '', }, { description: 'strong: Bold with **asterisks** or __underscores__.', inputText: 'Bold with **asterisks** or __underscores__.', outputText: 'Bold with asterisks or underscores.', }, { description: 'strong & em: Bold and italics with **asterisks and _underscores_**.', inputText: 'Bold and italics with **asterisks and _underscores_**.', outputText: 'Bold and italics with asterisks and underscores.', }, { description: 'em: Italics with *asterisks* or _underscores_.', inputText: 'Italics with *asterisks* or _underscores_.', outputText: 'Italics with asterisks or underscores.', }, { description: 'del: Strikethrough ~~strike this.~~', inputText: 'Strikethrough ~~strike this.~~', outputText: 'Strikethrough strike this.', }, { description: 'links: [inline-style link](http://localhost:8065)', inputText: '[inline-style link](http://localhost:8065)', outputText: 'inline-style link', }, { description: 'image: ![image link](http://localhost:8065/image)', inputText: '![image link](http://localhost:8065/image)', outputText: 'image link', }, { description: 'text: plain', inputText: 'This is plain text.', outputText: 'This is plain text.', }, { description: 'text: multiline', inputText: 'This is multiline text.\nHere is the next line.\n', outputText: 'This is multiline text. Here is the next line.', }, { description: 'text: multiline with blockquote', inputText: 'This is multiline text.\n> With quote', outputText: 'This is multiline text. With quote', }, { description: 'text: multiline with list items', inputText: 'This is multiline text.\n * List item ', outputText: 'This is multiline text. List item', }, { description: 'text: &amp; entity', inputText: 'you & me', outputText: 'you & me', }, { description: 'text: &lt; entity', inputText: '1<2', outputText: '1<2', }, { description: 'text: &gt; entity', inputText: '2>1', outputText: '2>1', }, { description: 'text: &#39; entity', inputText: 'he\'s out', outputText: 'he\'s out', }, { description: 'text: &quot; entity', inputText: 'That is "unique"', outputText: 'That is "unique"', }, { description: 'text: multiple entities', inputText: '&<>\'"', outputText: '&<>\'"', }, { description: 'text: multiple entities', inputText: '"\'><&', outputText: '"\'><&', }, { description: 'text: multiple entities', inputText: '&amp;&lt;&gt;&#39;&quot;', outputText: '&<>\'"', }, { description: 'text: multiple entities', inputText: '&quot;&#39;&gt;&lt;&amp;', outputText: '"\'><&', }, { description: 'text: multiple entities', inputText: '&amp;lt;', outputText: '&lt;', }, { description: 'text: empty string', inputText: '', outputText: '', }, { description: 'text: null', inputText: null, outputText: null, }, { description: 'text: {}', inputText: {key: 'value'}, outputText: {key: 'value'}, }, { description: 'text: []', inputText: [1], outputText: [1], }, { description: 'text: node', inputText: (<div/>), outputText: (<div/>), }, ]; testCases.forEach((testCase) => it(testCase.description, () => { expect(stripMarkdown(testCase.inputText as any)).toEqual(testCase.outputText); })); });
4,560
0
petrpan-code/mattermost/mattermost/webapp/platform/client
petrpan-code/mattermost/mattermost/webapp/platform/client/src/client4.test.ts
// Copyright (c) 2015-present Mattermost, Inc. All Rights Reserved. // See LICENSE.txt for license information. import nock from 'nock'; import Client4, {ClientError, HEADER_X_VERSION_ID} from './client4'; import {TelemetryHandler} from './telemetry'; describe('Client4', () => { beforeAll(() => { if (!nock.isActive()) { nock.activate(); } }); afterAll(() => { nock.restore(); }); describe('doFetchWithResponse', () => { test('serverVersion should be set from response header', async () => { const client = new Client4(); client.setUrl('http://mattermost.example.com'); expect(client.serverVersion).toEqual(''); nock(client.getBaseRoute()). get('/users/me'). reply(200, '{}', {[HEADER_X_VERSION_ID]: '5.0.0.5.0.0.abc123'}); await client.getMe(); expect(client.serverVersion).toEqual('5.0.0.5.0.0.abc123'); nock(client.getBaseRoute()). get('/users/me'). reply(200, '{}', {[HEADER_X_VERSION_ID]: '5.3.0.5.3.0.abc123'}); await client.getMe(); expect(client.serverVersion).toEqual('5.3.0.5.3.0.abc123'); }); }); }); describe('ClientError', () => { test('standard fields should be enumerable', () => { const error = new ClientError('https://example.com', { message: 'This is a message', server_error_id: 'test.app_error', status_code: 418, url: 'https://example.com/api/v4/error', }); const copy = {...error}; expect(copy.message).toEqual(error.message); expect(copy.server_error_id).toEqual(error.server_error_id); expect(copy.status_code).toEqual(error.status_code); expect(copy.url).toEqual(error.url); }); test('cause should be preserved when provided', () => { const cause = new Error('the original error'); const error = new ClientError('https://example.com', { message: 'This is a message', server_error_id: 'test.app_error', status_code: 418, url: 'https://example.com/api/v4/error', }, cause); const copy = {...error}; expect(copy.message).toEqual(error.message); expect(copy.server_error_id).toEqual(error.server_error_id); expect(copy.status_code).toEqual(error.status_code); expect(copy.url).toEqual(error.url); expect(error.cause).toEqual(cause); }); }); describe('trackEvent', () => { class TestTelemetryHandler implements TelemetryHandler { trackEvent = jest.fn(); pageVisited = jest.fn(); } test('should call the attached RudderTelemetryHandler, if one is attached to Client4', () => { const client = new Client4(); client.setUrl('http://mattermost.example.com'); expect(() => client.trackEvent('test', 'onClick')).not.toThrowError(); const handler = new TestTelemetryHandler(); client.setTelemetryHandler(handler); client.trackEvent('test', 'onClick'); expect(handler.trackEvent).toHaveBeenCalledTimes(1); }); });
4,562
0
petrpan-code/mattermost/mattermost/webapp/platform/client
petrpan-code/mattermost/mattermost/webapp/platform/client/src/errors.test.ts
// Copyright (c) 2015-present Mattermost, Inc. All Rights Reserved. // See LICENSE.txt for license information. import Client4 from './client4'; import {cleanUrlForLogging} from './errors'; describe('cleanUrlForLogging', () => { const baseUrl = 'https://mattermost.example.com/subpath'; const client = new Client4(); client.setUrl(baseUrl); const testCases = [{ name: 'should remove server URL', input: client.getUserRoute('me'), expected: `${client.urlVersion}/users/me`, }, { name: 'should filter user IDs', input: client.getUserRoute('1234'), expected: `${client.urlVersion}/users/<filtered>`, }, { name: 'should filter email addresses', input: `${client.getUsersRoute()}/email/[email protected]`, expected: `${client.urlVersion}/users/email/<filtered>`, }, { name: 'should filter query parameters', input: `${client.getUserRoute('me')}?foo=bar`, expected: `${client.urlVersion}/users/me?<filtered>`, }]; for (const testCase of testCases) { test(testCase.name, () => { expect(cleanUrlForLogging(baseUrl, testCase.input)).toEqual(testCase.expected); }); } });
4,564
0
petrpan-code/mattermost/mattermost/webapp/platform/client
petrpan-code/mattermost/mattermost/webapp/platform/client/src/helpers.test.ts
// Copyright (c) 2015-present Mattermost, Inc. All Rights Reserved. // See LICENSE.txt for license information. import {buildQueryString} from './helpers'; describe('Helpers', () => { test.each([ [{}, ''], [{a: 1}, '?a=1'], [{a: 1, b: 'str'}, '?a=1&b=str'], [{a: 1, b: 'str', c: undefined}, '?a=1&b=str'], [{a: 1, b: 'str', c: 0}, '?a=1&b=str&c=0'], [{a: 1, b: 'str', c: ''}, '?a=1&b=str&c='], [{a: 1, b: undefined, c: 'str'}, '?a=1&c=str'], ])('buildQueryString with %o should return %s', (params, expected) => { expect(buildQueryString(params)).toEqual(expected); }); });
4,584
0
petrpan-code/mattermost/mattermost/webapp/platform/components/src
petrpan-code/mattermost/mattermost/webapp/platform/components/src/footer_pagination/footer_pagination.test.tsx
// Copyright (c) 2015-present Mattermost, Inc. All Rights Reserved. // See LICENSE.txt for license information. import React from 'react'; import {render, screen} from '@testing-library/react'; import {FooterPagination} from './footer_pagination'; import {wrapIntl} from '../testUtils' describe('LegacyGenericModal/FooterPagination', () => { const baseProps = { page: 0, total: 0, itemsPerPage: 0, onNextPage: jest.fn(), onPreviousPage: jest.fn(), }; test('should render default', () => { const wrapper = render(wrapIntl(<FooterPagination {...baseProps}/>)); expect(wrapper).toMatchSnapshot(); }); test('should render pagination legend', () => { const props = { ...baseProps, page: 0, total: 17, itemsPerPage: 10, } render(wrapIntl(<FooterPagination {...props}/>)); expect(screen.getByText('Showing 1-10 of 17')).toBeInTheDocument(); }); });
4,586
0
petrpan-code/mattermost/mattermost/webapp/platform/components/src/footer_pagination
petrpan-code/mattermost/mattermost/webapp/platform/components/src/footer_pagination/__snapshots__/footer_pagination.test.tsx.snap
// Jest Snapshot v1, https://goo.gl/fbAQLP exports[`LegacyGenericModal/FooterPagination should render default 1`] = ` Object { "asFragment": [Function], "baseElement": <body> <div> <div class="footer-pagination" > <div class="footer-pagination__legend" /> <div class="footer-pagination__button-container" > <button class="footer-pagination__button-container__button disabled" disabled="" type="button" > <svg fill="currentColor" height="16" version="1.1" viewBox="0 0 24 24" width="16" xmlns="http://www.w3.org/2000/svg" > <path d="M15.41,16.58L10.83,12L15.41,7.41L14,6L8,12L14,18L15.41,16.58Z" /> </svg> <span> Previous </span> </button> <button class="footer-pagination__button-container__button disabled" disabled="" type="button" > <span> Next </span> <svg fill="currentColor" height="16" version="1.1" viewBox="0 0 24 24" width="16" xmlns="http://www.w3.org/2000/svg" > <path d="M8.59,16.58L13.17,12L8.59,7.41L10,6L16,12L10,18L8.59,16.58Z" /> </svg> </button> </div> </div> </div> </body>, "container": <div> <div class="footer-pagination" > <div class="footer-pagination__legend" /> <div class="footer-pagination__button-container" > <button class="footer-pagination__button-container__button disabled" disabled="" type="button" > <svg fill="currentColor" height="16" version="1.1" viewBox="0 0 24 24" width="16" xmlns="http://www.w3.org/2000/svg" > <path d="M15.41,16.58L10.83,12L15.41,7.41L14,6L8,12L14,18L15.41,16.58Z" /> </svg> <span> Previous </span> </button> <button class="footer-pagination__button-container__button disabled" disabled="" type="button" > <span> Next </span> <svg fill="currentColor" height="16" version="1.1" viewBox="0 0 24 24" width="16" xmlns="http://www.w3.org/2000/svg" > <path d="M8.59,16.58L13.17,12L8.59,7.41L10,6L16,12L10,18L8.59,16.58Z" /> </svg> </button> </div> </div> </div>, "debug": [Function], "findAllByAltText": [Function], "findAllByDisplayValue": [Function], "findAllByLabelText": [Function], "findAllByPlaceholderText": [Function], "findAllByRole": [Function], "findAllByTestId": [Function], "findAllByText": [Function], "findAllByTitle": [Function], "findByAltText": [Function], "findByDisplayValue": [Function], "findByLabelText": [Function], "findByPlaceholderText": [Function], "findByRole": [Function], "findByTestId": [Function], "findByText": [Function], "findByTitle": [Function], "getAllByAltText": [Function], "getAllByDisplayValue": [Function], "getAllByLabelText": [Function], "getAllByPlaceholderText": [Function], "getAllByRole": [Function], "getAllByTestId": [Function], "getAllByText": [Function], "getAllByTitle": [Function], "getByAltText": [Function], "getByDisplayValue": [Function], "getByLabelText": [Function], "getByPlaceholderText": [Function], "getByRole": [Function], "getByTestId": [Function], "getByText": [Function], "getByTitle": [Function], "queryAllByAltText": [Function], "queryAllByDisplayValue": [Function], "queryAllByLabelText": [Function], "queryAllByPlaceholderText": [Function], "queryAllByRole": [Function], "queryAllByTestId": [Function], "queryAllByText": [Function], "queryAllByTitle": [Function], "queryByAltText": [Function], "queryByDisplayValue": [Function], "queryByLabelText": [Function], "queryByPlaceholderText": [Function], "queryByRole": [Function], "queryByTestId": [Function], "queryByText": [Function], "queryByTitle": [Function], "rerender": [Function], "unmount": [Function], } `;
4,588
0
petrpan-code/mattermost/mattermost/webapp/platform/components/src
petrpan-code/mattermost/mattermost/webapp/platform/components/src/generic_modal/generic_modal.test.tsx
// Copyright (c) 2015-present Mattermost, Inc. All Rights Reserved. // See LICENSE.txt for license information. import React from 'react'; import {render, screen} from '@testing-library/react'; import {GenericModal} from './generic_modal'; import {wrapIntl} from '../testUtils'; describe('GenericModal', () => { const baseProps = { onExited: jest.fn(), modalHeaderText: 'Modal Header Text', children: <></>, }; test('should match snapshot for base case', () => { const wrapper = render( wrapIntl(<GenericModal {...baseProps}/>), ); expect(wrapper).toMatchSnapshot(); }); test('should have confirm and cancels buttons when handlers are passed for both buttons', () => { const props = { ...baseProps, handleConfirm: jest.fn(), handleCancel: jest.fn(), }; render( wrapIntl(<GenericModal {...props}/>), ); expect(screen.getByText('Confirm')).toBeInTheDocument(); expect(screen.getByText('Cancel')).toBeInTheDocument(); }); });
4,590
0
petrpan-code/mattermost/mattermost/webapp/platform/components/src/generic_modal
petrpan-code/mattermost/mattermost/webapp/platform/components/src/generic_modal/__snapshots__/generic_modal.test.tsx.snap
// Jest Snapshot v1, https://goo.gl/fbAQLP exports[`GenericModal should match snapshot for base case 1`] = ` Object { "asFragment": [Function], "baseElement": <body class="modal-open" style="padding-right: 0px;" > <div aria-hidden="true" /> <div role="dialog" > <div class="fade modal-backdrop in" /> <div aria-labelledby="genericModalLabel" class="fade in modal" id="genericModal" role="dialog" style="display: block; padding-right: 0px;" tabindex="-1" > <div class="a11y__modal GenericModal modal-dialog" > <div class="modal-content" role="document" > <div class="GenericModal__wrapper-enter-key-press-catcher" tabindex="0" > <div class="modal-header" > <button aria-label="Close" class="close" type="button" > <span aria-hidden="true" > × </span> <span class="sr-only" > Close </span> </button> </div> <div class="modal-body" > <div class="GenericModal__header" > <h1 id="genericModalLabel" > Modal Header Text </h1> </div> <div class="GenericModal__body padding" /> </div> </div> </div> </div> </div> </div> </body>, "container": <div aria-hidden="true" />, "debug": [Function], "findAllByAltText": [Function], "findAllByDisplayValue": [Function], "findAllByLabelText": [Function], "findAllByPlaceholderText": [Function], "findAllByRole": [Function], "findAllByTestId": [Function], "findAllByText": [Function], "findAllByTitle": [Function], "findByAltText": [Function], "findByDisplayValue": [Function], "findByLabelText": [Function], "findByPlaceholderText": [Function], "findByRole": [Function], "findByTestId": [Function], "findByText": [Function], "findByTitle": [Function], "getAllByAltText": [Function], "getAllByDisplayValue": [Function], "getAllByLabelText": [Function], "getAllByPlaceholderText": [Function], "getAllByRole": [Function], "getAllByTestId": [Function], "getAllByText": [Function], "getAllByTitle": [Function], "getByAltText": [Function], "getByDisplayValue": [Function], "getByLabelText": [Function], "getByPlaceholderText": [Function], "getByRole": [Function], "getByTestId": [Function], "getByText": [Function], "getByTitle": [Function], "queryAllByAltText": [Function], "queryAllByDisplayValue": [Function], "queryAllByLabelText": [Function], "queryAllByPlaceholderText": [Function], "queryAllByRole": [Function], "queryAllByTestId": [Function], "queryAllByText": [Function], "queryAllByTitle": [Function], "queryByAltText": [Function], "queryByDisplayValue": [Function], "queryByLabelText": [Function], "queryByPlaceholderText": [Function], "queryByRole": [Function], "queryByTestId": [Function], "queryByText": [Function], "queryByTitle": [Function], "rerender": [Function], "unmount": [Function], } `;
4,801
0
petrpan-code/mobxjs/mobx/packages/mobx-react-lite
petrpan-code/mobxjs/mobx/packages/mobx-react-lite/__tests__/ObserverComponent.test.tsx
import mockConsole from "jest-mock-console" import * as mobx from "mobx" import * as React from "react" import { act, cleanup, render } from "@testing-library/react" import { Observer } from "../src" afterEach(cleanup) describe("regions should rerender component", () => { const execute = () => { const data = mobx.observable.box("hi") const Comp = () => ( <div> <Observer>{() => <span>{data.get()}</span>}</Observer> <li>{data.get()}</li> </div> ) return { ...render(<Comp />), data } } test("init state is correct", () => { const { container } = execute() expect(container.querySelector("span")!.innerHTML).toBe("hi") expect(container.querySelector("li")!.innerHTML).toBe("hi") }) test("set the data to hello", async () => { const { container, data } = execute() act(() => { data.set("hello") }) expect(container.querySelector("span")!.innerHTML).toBe("hello") expect(container.querySelector("li")!.innerHTML).toBe("hi") }) }) it("renders null if no children/render prop is supplied a function", () => { const restoreConsole = mockConsole() const Comp = () => <Observer /> const { container } = render(<Comp />) expect(container).toMatchInlineSnapshot(`<div />`) restoreConsole() }) it.skip("prop types checks for children/render usage", () => { const Comp = () => ( <Observer render={() => <span>children</span>}>{() => <span>children</span>}</Observer> ) const restoreConsole = mockConsole("error") render(<Comp />) // tslint:disable-next-line:no-console expect(console.error).toHaveBeenCalledWith( expect.stringContaining("Do not use children and render in the same time") ) restoreConsole() })
4,802
0
petrpan-code/mobxjs/mobx/packages/mobx-react-lite
petrpan-code/mobxjs/mobx/packages/mobx-react-lite/__tests__/api.test.ts
const api = require("../src/index.ts") test("correct api should be exposed", function () { expect( Object.keys(api) .filter(key => api[key] !== undefined) .sort() ).toEqual( [ "isUsingStaticRendering", "enableStaticRendering", "observer", "Observer", "useLocalObservable", "useLocalStore", "useAsObservableSource", "clearTimers", "useObserver", "isObserverBatched", "observerBatching", "useStaticRendering", "_observerFinalizationRegistry" ].sort() ) })
4,803
0
petrpan-code/mobxjs/mobx/packages/mobx-react-lite
petrpan-code/mobxjs/mobx/packages/mobx-react-lite/__tests__/assertEnvironment.test.ts
afterEach(() => { jest.resetModules() jest.resetAllMocks() }) it("throws if react is not installed", () => { jest.mock("react", () => ({})) expect(() => require("../src/utils/assertEnvironment.ts")).toThrowErrorMatchingInlineSnapshot( `"mobx-react-lite requires React with Hooks support"` ) }) it("throws if mobx is not installed", () => { jest.mock("react", () => ({ useState: true })) jest.mock("mobx", () => ({})) expect(() => require("../src/utils/assertEnvironment.ts")).toThrowErrorMatchingInlineSnapshot( `"mobx-react-lite@3 requires mobx at least version 6 to be available"` ) }) export default "Cannot use import statement outside a module"
4,804
0
petrpan-code/mobxjs/mobx/packages/mobx-react-lite
petrpan-code/mobxjs/mobx/packages/mobx-react-lite/__tests__/enforceActions.test.tsx
import * as mobx from "mobx" import { _resetGlobalState } from "mobx" import * as React from "react" import { useEffect } from "react" import { observer, useLocalObservable } from "mobx-react" import { render } from "@testing-library/react" let consoleWarnMock: jest.SpyInstance | undefined afterEach(() => { consoleWarnMock?.mockRestore() }) afterEach(() => { _resetGlobalState() }) describe("enforcing actions", () => { it("'never' should work", () => { consoleWarnMock = jest.spyOn(console, "warn").mockImplementation(() => {}) mobx.configure({ enforceActions: "never" }) const Parent = observer(() => { const obs = useLocalObservable(() => ({ x: 1 })) useEffect(() => { obs.x++ }, []) return <div>{obs.x}</div> }) render(<Parent />) expect(consoleWarnMock).not.toBeCalled() }) it("'observed' should work", () => { consoleWarnMock = jest.spyOn(console, "warn").mockImplementation(() => {}) mobx.configure({ enforceActions: "observed" }) const Parent = observer(() => { const obs = useLocalObservable(() => ({ x: 1 })) useEffect(() => { obs.x++ }, []) return <div>{obs.x}</div> }) render(<Parent />) expect(consoleWarnMock).toBeCalledTimes(1) }) it("'always' should work", () => { consoleWarnMock = jest.spyOn(console, "warn").mockImplementation(() => {}) mobx.configure({ enforceActions: "always" }) const Parent = observer(() => { const obs = useLocalObservable(() => ({ x: 1 })) useEffect(() => { obs.x++ }, []) return <div>{obs.x}</div> }) render(<Parent />) expect(consoleWarnMock).toBeCalledTimes(1) }) })
4,805
0
petrpan-code/mobxjs/mobx/packages/mobx-react-lite
petrpan-code/mobxjs/mobx/packages/mobx-react-lite/__tests__/observer.test.tsx
import { act, cleanup, fireEvent, render } from "@testing-library/react" import mockConsole from "jest-mock-console" import * as mobx from "mobx" import React from "react" import { observer, useObserver, isObserverBatched, enableStaticRendering } from "../src" const getDNode = (obj: any, prop?: string) => mobx.getObserverTree(obj, prop) afterEach(cleanup) let consoleWarnMock: jest.SpyInstance | undefined afterEach(() => { consoleWarnMock?.mockRestore() }) function runTestSuite(mode: "observer" | "useObserver") { function obsComponent<P extends object>( component: React.FunctionComponent<P>, forceMemo = false ) { if (mode === "observer") { return observer(component) } else { const c = (props: P) => { consoleWarnMock = jest.spyOn(console, "warn").mockImplementation(() => {}) return useObserver(() => { return component(props) }) } return forceMemo ? React.memo(c) : c } } describe(`nestedRendering - ${mode}`, () => { const execute = () => { // init element const store = mobx.observable({ todos: [ { completed: false, title: "a" } ] }) const renderings = { item: 0, list: 0 } const TodoItem = obsComponent(({ todo }: { todo: typeof store.todos[0] }) => { renderings.item++ return <li>|{todo.title}</li> }, true) const TodoList = obsComponent(() => { renderings.list++ return ( <div> <span>{store.todos.length}</span> {store.todos.map((todo, idx) => ( <TodoItem key={idx} todo={todo} /> ))} </div> ) }, true) const rendered = render(<TodoList />) return { ...rendered, store, renderings } } test("first rendering", () => { const { getAllByText, renderings } = execute() expect(renderings.list).toBe(1) expect(renderings.item).toBe(1) expect(getAllByText("1")).toHaveLength(1) expect(getAllByText("|a")).toHaveLength(1) }) test("inner store changed", () => { const { store, getAllByText, renderings } = execute() act(() => { store.todos[0].title += "a" }) expect(renderings.list).toBe(1) expect(renderings.item).toBe(2) expect(getAllByText("1")).toHaveLength(1) expect(getAllByText("|aa")).toHaveLength(1) expect(getDNode(store, "todos").observers!.length).toBe(1) expect(getDNode(store.todos[0], "title").observers!.length).toBe(1) }) test("rerendering with outer store added", () => { const { store, container, getAllByText, renderings } = execute() act(() => { store.todos.push({ completed: true, title: "b" }) }) expect(container.querySelectorAll("li").length).toBe(2) expect(getAllByText("2")).toHaveLength(1) expect(getAllByText("|b")).toHaveLength(1) expect(renderings.list).toBe(2) expect(renderings.item).toBe(2) expect(getDNode(store.todos[1], "title").observers!.length).toBe(1) expect(getDNode(store.todos[1], "completed").observers).toBeFalsy() }) test("rerendering with outer store pop", () => { const { store, container, renderings } = execute() let oldTodo act(() => { oldTodo = store.todos.pop() }) expect(renderings.list).toBe(2) expect(renderings.item).toBe(1) expect(container.querySelectorAll("li").length).toBe(0) expect(getDNode(oldTodo, "title").observers).toBeFalsy() expect(getDNode(oldTodo, "completed").observers).toBeFalsy() }) }) describe("isObjectShallowModified detects when React will update the component", () => { const store = mobx.observable({ count: 0 }) let counterRenderings = 0 const Counter = obsComponent(function TodoItem() { counterRenderings++ return <div>{store.count}</div> }) test("does not assume React will update due to NaN prop", () => { // @ts-ignore Not sure what this test does, the value is not used render(<Counter value={NaN} />) act(() => { store.count++ }) expect(counterRenderings).toBe(2) }) }) describe("keep views alive", () => { const execute = () => { const data = mobx.observable({ x: 3, yCalcCount: 0, get y() { this.yCalcCount++ return this.x * 2 }, z: "hi" }) const TestComponent = obsComponent(() => { return ( <div> {data.z} {data.y} </div> ) }) return { ...render(<TestComponent />), data } } test("init state", () => { const { data, queryByText } = execute() expect(data.yCalcCount).toBe(1) expect(queryByText("hi6")).toBeTruthy() }) test("rerender should not need a recomputation of data.y", () => { const { data, queryByText } = execute() act(() => { data.z = "hello" }) expect(data.yCalcCount).toBe(1) expect(queryByText("hello6")).toBeTruthy() }) }) describe("does not keep views alive when using static rendering", () => { const execute = () => { enableStaticRendering(true) let renderCount = 0 const data = mobx.observable({ z: "hi" }) const TestComponent = obsComponent(() => { renderCount++ return <div>{data.z}</div> }) return { ...render(<TestComponent />), data, getRenderCount: () => renderCount } } afterEach(() => { enableStaticRendering(false) }) test("init state is correct", () => { const { getRenderCount, getByText } = execute() expect(getRenderCount()).toBe(1) expect(getByText("hi")).toBeTruthy() }) test("no re-rendering on static rendering", () => { const { getRenderCount, getByText, data } = execute() act(() => { data.z = "hello" }) expect(getRenderCount()).toBe(1) expect(getByText("hi")).toBeTruthy() expect(getDNode(data, "z").observers!).toBeFalsy() }) }) describe("issue 12", () => { const createData = () => mobx.observable({ selected: "coffee", items: [ { name: "coffee" }, { name: "tea" } ] }) interface IItem { name: string } interface IRowProps { item: IItem selected: string } const Row: React.FC<IRowProps> = props => { return ( <span> {props.item.name} {props.selected === props.item.name ? "!" : ""} </span> ) } /** table stateles component */ const Table = obsComponent<{ data: { items: IItem[]; selected: string } }>(props => { return ( <div> {props.data.items.map(item => ( <Row key={item.name} item={item} selected={props.data.selected} /> ))} </div> ) }) test("init state is correct", () => { const data = createData() const { container } = render(<Table data={data} />) expect(container).toMatchSnapshot() }) test("run transaction", () => { const data = createData() const { container } = render(<Table data={data} />) act(() => { mobx.transaction(() => { data.items[1].name = "boe" data.items.splice(0, 2, { name: "soup" }) data.selected = "tea" }) }) expect(container).toMatchSnapshot() }) }) describe("issue 309", () => { test("isObserverBatched is still defined and yields true by default", () => { consoleWarnMock = jest.spyOn(console, "warn").mockImplementation(() => {}) expect(isObserverBatched()).toBe(true) expect(consoleWarnMock).toMatchSnapshot() }) }) test("changing state in render should fail", () => { // This test is most likely obsolete ... exception is not thrown const data = mobx.observable.box(2) const Comp = obsComponent(() => { if (data.get() === 3) { try { data.set(4) // wouldn't throw first time for lack of observers.. (could we tighten this?) } catch (err) { expect(err).toBeInstanceOf(Error) expect(err).toMatch( /Side effects like changing state are not allowed at this point/ ) } } return <div>{data.get()}</div> }) const { container } = render(<Comp />) act(() => { data.set(3) }) expect(container).toMatchSnapshot() mobx._resetGlobalState() }) describe("should render component even if setState called with exactly the same props", () => { const execute = () => { let renderCount = 0 const Component = obsComponent(() => { const [, setState] = React.useState({}) const onClick = () => { setState({}) } renderCount++ return <div onClick={onClick} data-testid="clickableDiv" /> }) return { ...render(<Component />), getCount: () => renderCount } } test("renderCount === 1", () => { const { getCount } = execute() expect(getCount()).toBe(1) }) test("after click once renderCount === 2", async () => { const { getCount, getByTestId } = execute() fireEvent.click(getByTestId("clickableDiv")) expect(getCount()).toBe(2) }) test("after click twice renderCount === 3", async () => { const { getCount, getByTestId } = execute() fireEvent.click(getByTestId("clickableDiv")) fireEvent.click(getByTestId("clickableDiv")) expect(getCount()).toBe(3) }) }) describe("it rerenders correctly when useMemo is wrapping observable", () => { const execute = () => { let renderCount = 0 const createProps = () => { const odata = mobx.observable({ x: 1 }) const data = { y: 1 } function doStuff() { data.y++ odata.x++ } return { odata, data, doStuff } } const Component = obsComponent((props: any) => { const computed = React.useMemo(() => props.odata.x, [props.odata.x]) renderCount++ return ( <span onClick={props.doStuff}> {props.odata.x}-{props.data.y}-{computed} </span> ) }) const rendered = render(<Component {...createProps()} />) return { ...rendered, getCount: () => renderCount, span: rendered.container.querySelector("span")! } } test("init renderCount === 1", () => { const { span, getCount } = execute() expect(getCount()).toBe(1) expect(span.innerHTML).toBe("1-1-1") }) test("after click renderCount === 2", async () => { const { span, getCount } = execute() fireEvent.click(span) expect(getCount()).toBe(2) expect(span.innerHTML).toBe("2-2-2") }) test("after click twice renderCount === 3", async () => { const { span, getCount } = execute() fireEvent.click(span) fireEvent.click(span) expect(getCount()).toBe(3) expect(span.innerHTML).toBe("3-3-3") }) }) describe("should not re-render on shallow equal new props", () => { const execute = () => { const renderings = { child: 0, parent: 0 } const data = { x: 1 } const odata = mobx.observable({ y: 1 }) const Child = obsComponent((props: any) => { renderings.child++ return <span>{props.data.x}</span> }, true) const Parent = obsComponent(() => { renderings.parent++ // tslint:disable-next-line no-unused-expression odata.y /// depend return <Child data={data} /> }, true) return { ...render(<Parent />), renderings, odata } } test("init state is correct", () => { const { container, renderings } = execute() expect(renderings.parent).toBe(1) expect(renderings.child).toBe(1) expect(container.querySelector("span")!.innerHTML).toBe("1") }) test("after odata change", async () => { const { container, renderings, odata } = execute() act(() => { odata.y++ }) expect(renderings.parent).toBe(2) expect(renderings.child).toBe(1) expect(container.querySelector("span")!.innerHTML).toBe("1") }) }) describe("error handling", () => { test("errors should propagate", () => { const x = mobx.observable.box(1) const errorsSeen: any[] = [] class ErrorBoundary extends React.Component<{ children: any }> { public static getDerivedStateFromError() { return { hasError: true } } public state = { hasError: false } public componentDidCatch(error: any, info: any) { errorsSeen.push("" + error) } public render() { if (this.state.hasError) { return <span>Saw error!</span> } return this.props.children } } const C = obsComponent(() => { if (x.get() === 42) { throw new Error("The meaning of life!") } return <span>{x.get()}</span> }) const restoreConsole = mockConsole() try { const rendered = render( <ErrorBoundary> <C /> </ErrorBoundary> ) expect(rendered.container.querySelector("span")!.innerHTML).toBe("1") act(() => { x.set(42) }) expect(errorsSeen).toEqual(["Error: The meaning of life!"]) expect(rendered.container.querySelector("span")!.innerHTML).toBe("Saw error!") } finally { restoreConsole() } }) }) } runTestSuite("observer") runTestSuite("useObserver") test("observer(cmp, { forwardRef: true }) + useImperativeHandle", () => { consoleWarnMock = jest.spyOn(console, "warn").mockImplementation(() => {}) interface IMethods { focus(): void } interface IProps { value: string ref: React.Ref<IMethods> } const FancyInput = observer<IProps>( (props: IProps, ref: React.Ref<IMethods>) => { const inputRef = React.useRef<HTMLInputElement>(null) React.useImperativeHandle( ref, () => ({ focus: () => { inputRef.current!.focus() } }), [] ) return <input ref={inputRef} defaultValue={props.value} /> }, { forwardRef: true } ) const cr = React.createRef<IMethods>() render(<FancyInput ref={cr} value="" />) expect(cr).toBeTruthy() expect(cr.current).toBeTruthy() expect(typeof cr.current!.focus).toBe("function") expect(consoleWarnMock).toMatchSnapshot() }) test("observer(forwardRef(cmp)) + useImperativeHandle", () => { interface IMethods { focus(): void } interface IProps { value: string } const FancyInput = observer( React.forwardRef((props: IProps, ref: React.Ref<IMethods>) => { const inputRef = React.useRef<HTMLInputElement>(null) React.useImperativeHandle( ref, () => ({ focus: () => { inputRef.current!.focus() } }), [] ) return <input ref={inputRef} defaultValue={props.value} /> }) ) const cr = React.createRef<IMethods>() render(<FancyInput ref={cr} value="" />) expect(cr).toBeTruthy() expect(cr.current).toBeTruthy() expect(typeof cr.current!.focus).toBe("function") }) test("useImperativeHandle and forwardRef should work with useObserver", () => { consoleWarnMock = jest.spyOn(console, "warn").mockImplementation(() => {}) interface IMethods { focus(): void } interface IProps { value: string } const FancyInput = React.memo( React.forwardRef((props: IProps, ref: React.Ref<IMethods>) => { const inputRef = React.useRef<HTMLInputElement>(null) React.useImperativeHandle( ref, () => ({ focus: () => { inputRef.current!.focus() } }), [] ) return useObserver(() => { return <input ref={inputRef} defaultValue={props.value} /> }) }) ) const cr = React.createRef<IMethods>() render(<FancyInput ref={cr} value="" />) expect(cr).toBeTruthy() expect(cr.current).toBeTruthy() expect(typeof cr.current!.focus).toBe("function") expect(consoleWarnMock).toMatchSnapshot() }) it("should hoist known statics only", () => { function isNumber() { return null } function MyHipsterComponent() { return null } MyHipsterComponent.defaultProps = { x: 3 } MyHipsterComponent.propTypes = { x: isNumber } MyHipsterComponent.randomStaticThing = 3 MyHipsterComponent.type = "Nope!" MyHipsterComponent.compare = "Nope!" MyHipsterComponent.render = "Nope!" const wrapped = observer(MyHipsterComponent) expect(wrapped.randomStaticThing).toEqual(3) expect(wrapped.defaultProps).toEqual({ x: 3 }) expect(wrapped.propTypes).toEqual({ x: isNumber }) expect(wrapped.type).toBeInstanceOf(Function) // And not "Nope!"; this is the wrapped component, the property is introduced by memo expect(wrapped.compare).toBe(null) // another memo field expect(wrapped.render).toBe(undefined) }) it("should inherit original name/displayName #3438", () => { function Name() { return null } Name.displayName = "DisplayName" const TestComponent = observer(Name) expect((TestComponent as any).type.name).toBe("Name") expect((TestComponent as any).type.displayName).toBe("DisplayName") }) test("parent / childs render in the right order", done => { // See: https://jsfiddle.net/gkaemmer/q1kv7hbL/13/ const events: string[] = [] class User { public name = "User's name" constructor() { mobx.makeObservable(this, { name: mobx.observable }) } } class Store { public user: User | null = new User() public logout() { this.user = null } constructor() { mobx.makeObservable(this, { user: mobx.observable, logout: mobx.action }) } } const store = new Store() function tryLogout() { try { store.logout() expect(true).toBeTruthy() } catch (e) { // t.fail(e) } } const Parent = observer(() => { events.push("parent") if (!store.user) { return <span>Not logged in.</span> } return ( <div> <Child /> <button onClick={tryLogout}>Logout</button> </div> ) }) const Child = observer(() => { events.push("child") if (!store.user) { return null } return <span>Logged in as: {store.user.name}</span> }) render(<Parent />) tryLogout() expect(events).toEqual(["parent", "child"]) done() }) it("should have overload for props with children", () => { interface IProps { value: string } const TestComponent = observer<IProps>(({ value }) => { return null }) render(<TestComponent value="1" />) // this test has no `expect` calls as it verifies whether such component compiles or not }) it("should have overload for empty options", () => { // empty options are not really making sense now, but we shouldn't rely on `forwardRef` // being specified in case other options are added in the future interface IProps { value: string } const TestComponent = observer<IProps>(({ value }) => { return null }, {}) render(<TestComponent value="1" />) // this test has no `expect` calls as it verifies whether such component compiles or not }) it("should have overload for props with children when forwardRef", () => { interface IMethods { focus(): void } interface IProps { value: string } const TestComponent = observer<IProps, IMethods>( ({ value }, ref) => { return null }, { forwardRef: true } ) render(<TestComponent value="1" />) // this test has no `expect` calls as it verifies whether such component compiles or not }) it("should preserve generic parameters", () => { interface IColor { name: string css: string } interface ITestComponentProps<T> { value: T callback: (value: T) => void } const TestComponent = observer(<T extends unknown>(props: ITestComponentProps<T>) => { return null }) function callbackString(value: string) { return } function callbackColor(value: IColor) { return } render(<TestComponent value="1" callback={callbackString} />) render( <TestComponent value={{ name: "red", css: "rgb(255, 0, 0)" }} callback={callbackColor} /> ) // this test has no `expect` calls as it verifies whether such component compiles or not }) it("should preserve generic parameters when forwardRef", () => { interface IMethods { focus(): void } interface IColor { name: string css: string } interface ITestComponentProps<T> { value: T callback: (value: T) => void } const TestComponent = observer( <T extends unknown>(props: ITestComponentProps<T>, ref: React.Ref<IMethods>) => { return null }, { forwardRef: true } ) function callbackString(value: string) { return } function callbackColor(value: IColor) { return } render(<TestComponent value="1" callback={callbackString} />) render( <TestComponent value={{ name: "red", css: "rgb(255, 0, 0)" }} callback={callbackColor} /> ) // this test has no `expect` calls as it verifies whether such component compiles or not }) it("should keep original props types", () => { interface TestComponentProps { a: number } function TestComponent({ a }: TestComponentProps): JSX.Element | null { return null } const ObserverTestComponent = observer(TestComponent) const element = React.createElement(ObserverTestComponent, { a: 1 }) render(element) // this test has no `expect` calls as it verifies whether such component compiles or not }) // describe("206 - @observer should produce usefull errors if it throws", () => { // const data = mobx.observable({ x: 1 }) // let renderCount = 0 // const emmitedErrors = [] // const disposeErrorsHandler = onError(error => { // emmitedErrors.push(error) // }) // @observer // class Child extends React.Component { // render() { // renderCount++ // if (data.x === 42) throw new Error("Oops!") // return <span>{data.x}</span> // } // } // beforeAll(async done => { // await asyncReactDOMRender(<Child />, testRoot) // done() // }) // test("init renderCount should === 1", () => { // expect(renderCount).toBe(1) // }) // test("catch exception", () => { // expect(() => { // withConsole(() => { // data.x = 42 // }) // }).toThrow(/Oops!/) // expect(renderCount).toBe(3) // React fiber will try to replay the rendering, so the exception gets thrown a second time // }) // test("component recovers!", async () => { // await sleepHelper(500) // data.x = 3 // TestUtils.renderIntoDocument(<Child />) // expect(renderCount).toBe(4) // expect(emmitedErrors).toEqual([new Error("Oops!"), new Error("Oops!")]) // see above comment // }) // }) // test("195 - async componentWillMount does not work", async () => { // const renderedValues = [] // @observer // class WillMount extends React.Component { // @mobx.observable // counter = 0 // @mobx.action // inc = () => this.counter++ // componentWillMount() { // setTimeout(() => this.inc(), 300) // } // render() { // renderedValues.push(this.counter) // return ( // <p> // {this.counter} // <button onClick={this.inc}>+</button> // </p> // ) // } // } // TestUtils.renderIntoDocument(<WillMount />) // await sleepHelper(500) // expect(renderedValues).toEqual([0, 1]) // }) // test.skip("195 - should throw if trying to overwrite lifecycle methods", () => { // // Test disabled, see #231... // @observer // class WillMount extends React.Component { // componentWillMount = () => {} // render() { // return null // } // } // expect(TestUtils.renderIntoDocument(<WillMount />)).toThrow( // /Cannot assign to read only property 'componentWillMount'/ // ) // }) it("dependencies should not become temporarily unobserved", async () => { jest.spyOn(React, "useEffect") let p: Promise<any>[] = [] const cleanups: any[] = [] async function runEffects() { await Promise.all(p.splice(0)) } // @ts-ignore React.useEffect.mockImplementation(effect => { p.push( new Promise<void>(resolve => { setTimeout(() => { act(() => { cleanups.push(effect()) }) resolve() }, 10) }) ) }) let computed = 0 let renders = 0 const store = mobx.makeAutoObservable({ x: 1, get double() { computed++ return this.x * 2 }, inc() { this.x++ } }) const doubleDisposed = jest.fn() const reactionFired = jest.fn() mobx.onBecomeUnobserved(store, "double", doubleDisposed) const TestComponent = observer(() => { renders++ return <div>{store.double}</div> }) const r = render(<TestComponent />) expect(computed).toBe(1) expect(renders).toBe(1) expect(doubleDisposed).toBeCalledTimes(0) store.inc() expect(computed).toBe(2) // change propagated expect(renders).toBe(1) // but not yet rendered expect(doubleDisposed).toBeCalledTimes(0) // if we dispose to early, this fails! // Bug: change the state, before the useEffect fires, can cause the reaction to be disposed mobx.reaction(() => store.x, reactionFired) expect(reactionFired).toBeCalledTimes(0) expect(computed).toBe(2) // Not 3! expect(renders).toBe(1) expect(doubleDisposed).toBeCalledTimes(0) await runEffects() expect(reactionFired).toBeCalledTimes(0) expect(computed).toBe(2) // Not 3! expect(renders).toBe(2) expect(doubleDisposed).toBeCalledTimes(0) r.unmount() cleanups.filter(Boolean).forEach(f => f()) expect(reactionFired).toBeCalledTimes(0) expect(computed).toBe(2) expect(renders).toBe(2) expect(doubleDisposed).toBeCalledTimes(1) }) it("Legacy context support", () => { const contextKey = "key" const contextValue = "value" function ContextConsumer(_, context) { expect(context[contextKey]).toBe(contextValue) return null } ContextConsumer.contextTypes = { [contextKey]: () => null } const ObserverContextConsumer = observer(ContextConsumer) class ContextProvider extends React.Component { getChildContext() { return { [contextKey]: contextValue } } render() { return <ObserverContextConsumer /> } } ;(ContextProvider as any).childContextTypes = { [contextKey]: () => null } render(<ContextProvider />) }) it("Throw when trying to set contextType on observer", () => { const NamedObserver = observer(function TestCmp() { return null }) const AnonymousObserver = observer(() => null) expect(() => { ;(NamedObserver as any).contextTypes = {} }).toThrow(/\[mobx-react-lite\] `TestCmp.contextTypes` must be set before applying `observer`./) expect(() => { ;(AnonymousObserver as any).contextTypes = {} }).toThrow( /\[mobx-react-lite\] `Component.contextTypes` must be set before applying `observer`./ ) }) test("Anonymous component displayName #3192", () => { // React prints errors even if we catch em const consoleErrorSpy = jest.spyOn(console, "error").mockImplementation(() => {}) // Simulate returning something not renderable: // Error: n_a_m_e(...): // The point is to get correct displayName in error msg. let memoError let observerError // @ts-ignore const MemoCmp = React.memo(() => { return { hello: "world" } }) // @ts-ignore const ObserverCmp = observer(() => { return { hello: "world" } }) ObserverCmp.displayName = MemoCmp.displayName = "n_a_m_e" try { render(<MemoCmp />) } catch (error) { memoError = error } try { // @ts-ignore render(<ObserverCmp />) } catch (error) { observerError = error } expect(memoError).toBeInstanceOf(Error) expect(observerError).toBeInstanceOf(Error) expect(memoError.message.includes(MemoCmp.displayName)) expect(MemoCmp.displayName).toEqual(ObserverCmp.displayName) expect(observerError.message).toEqual(memoError.message) consoleErrorSpy.mockRestore() }) test("StrictMode #3671", async () => { const o = mobx.observable({ x: 0 }) const Cmp = observer(() => o.x as any) const { container, unmount } = render( <React.StrictMode> <Cmp /> </React.StrictMode> ) expect(container).toHaveTextContent("0") act( mobx.action(() => { o.x++ }) ) expect(container).toHaveTextContent("1") }) test("`isolateGlobalState` shouldn't break reactivity #3734", async () => { mobx.configure({ isolateGlobalState: true }) const o = mobx.observable({ x: 0 }) const Cmp = observer(() => o.x as any) const { container, unmount } = render(<Cmp />) expect(container).toHaveTextContent("0") act( mobx.action(() => { o.x++ }) ) expect(container).toHaveTextContent("1") unmount() mobx._resetGlobalState() })
4,806
0
petrpan-code/mobxjs/mobx/packages/mobx-react-lite
petrpan-code/mobxjs/mobx/packages/mobx-react-lite/__tests__/printDebugValue.test.ts
import { $mobx, autorun, observable } from "mobx" import { printDebugValue } from "../src/utils/printDebugValue" test("printDebugValue", () => { const money = observable({ euro: 10, get pound() { return this.euro / 1.15 } }) const disposer = autorun(() => { const { euro, pound } = money if (euro === pound) { // tslint:disable-next-line: no-console console.log("Weird..") } }) const value = (disposer as any)[$mobx] expect(printDebugValue(value)).toMatchSnapshot() disposer() expect(printDebugValue(value)).toMatchSnapshot() })
4,807
0
petrpan-code/mobxjs/mobx/packages/mobx-react-lite
petrpan-code/mobxjs/mobx/packages/mobx-react-lite/__tests__/strictAndConcurrentMode.test.tsx
import { act, cleanup, render } from "@testing-library/react" import mockConsole from "jest-mock-console" import * as mobx from "mobx" import * as React from "react" import { useObserver } from "../src/useObserver" afterEach(cleanup) test("uncommitted observing components should not attempt state changes", () => { const store = mobx.observable({ count: 0 }) const TestComponent = () => useObserver(() => <div>{store.count}</div>) // Render our observing component wrapped in StrictMode const rendering = render( <React.StrictMode> <TestComponent /> </React.StrictMode> ) // That will have caused our component to have been rendered // more than once, but when we unmount it'll only unmount once. rendering.unmount() // Trigger a change to the observable. If the reactions were // not disposed correctly, we'll see some console errors from // React StrictMode because we're calling state mutators to // trigger an update. const restoreConsole = mockConsole() try { act(() => { store.count++ }) // Check to see if any console errors were reported. // tslint:disable-next-line: no-console expect(console.error).not.toHaveBeenCalled() } finally { restoreConsole() } }) test(`observable changes before first commit are not lost`, async () => { const store = mobx.observable({ value: "initial" }) const TestComponent = () => useObserver(() => { const res = <div>{store.value}</div> // Change our observable. This is happening between the initial render of // our component and its initial commit, so it isn't fully mounted yet. // We want to ensure that the change isn't lost. store.value = "changed" return res }) const rootNode = document.createElement("div") document.body.appendChild(rootNode) const rendering = render( <React.StrictMode> <TestComponent /> </React.StrictMode> ) expect(rendering.baseElement.textContent).toBe("changed") })
4,808
0
petrpan-code/mobxjs/mobx/packages/mobx-react-lite
petrpan-code/mobxjs/mobx/packages/mobx-react-lite/__tests__/strictAndConcurrentModeUsingFinalizationRegistry.test.tsx
import { cleanup, render, waitFor } from "@testing-library/react" import * as mobx from "mobx" import * as React from "react" import { useObserver } from "../src/useObserver" import gc from "expose-gc/function" import { observerFinalizationRegistry } from "../src/utils/observerFinalizationRegistry" if (typeof globalThis.FinalizationRegistry !== "function") { throw new Error("This test must run with node >= 14") } expect(observerFinalizationRegistry).toBeInstanceOf(globalThis.FinalizationRegistry) afterEach(cleanup) function nextFrame() { return new Promise(accept => setTimeout(accept, 1)) } async function gc_cycle() { await nextFrame() gc() await nextFrame() } test("uncommitted components should not leak observations", async () => { jest.setTimeout(30_000) const store = mobx.observable({ count1: 0, count2: 0 }) // Track whether counts are observed let count1IsObserved = false let count2IsObserved = false mobx.onBecomeObserved(store, "count1", () => (count1IsObserved = true)) mobx.onBecomeUnobserved(store, "count1", () => (count1IsObserved = false)) mobx.onBecomeObserved(store, "count2", () => (count2IsObserved = true)) mobx.onBecomeUnobserved(store, "count2", () => (count2IsObserved = false)) const TestComponent1 = () => useObserver(() => <div>{store.count1}</div>) const TestComponent2 = () => useObserver(() => <div>{store.count2}</div>) // Render, then remove only #2 const rendering = render( <React.StrictMode> <TestComponent1 /> <TestComponent2 /> </React.StrictMode> ) rendering.rerender( <React.StrictMode> <TestComponent1 /> </React.StrictMode> ) // Allow gc to kick in in case to let finalization registry cleanup await gc_cycle() // Can take a while (especially on CI) before gc actually calls the registry await waitFor( () => { // count1 should still be being observed by Component1, // but count2 should have had its reaction cleaned up. expect(count1IsObserved).toBeTruthy() expect(count2IsObserved).toBeFalsy() }, { timeout: 15_000, interval: 200 } ) })
4,809
0
petrpan-code/mobxjs/mobx/packages/mobx-react-lite
petrpan-code/mobxjs/mobx/packages/mobx-react-lite/__tests__/strictAndConcurrentModeUsingTimers.test.tsx
import "./utils/killFinalizationRegistry" import { act, cleanup, render } from "@testing-library/react" import * as mobx from "mobx" import * as React from "react" import { useObserver } from "../src/useObserver" import { REGISTRY_FINALIZE_AFTER, REGISTRY_SWEEP_INTERVAL } from "../src/utils/UniversalFinalizationRegistry" import { observerFinalizationRegistry } from "../src/utils/observerFinalizationRegistry" import { TimerBasedFinalizationRegistry } from "../src/utils/UniversalFinalizationRegistry" expect(observerFinalizationRegistry).toBeInstanceOf(TimerBasedFinalizationRegistry) const registry = observerFinalizationRegistry as TimerBasedFinalizationRegistry<unknown> afterEach(cleanup) test("uncommitted components should not leak observations", async () => { registry.finalizeAllImmediately() // Unfortunately, Jest fake timers don't mock out Date.now, so we fake // that out in parallel to Jest useFakeTimers let fakeNow = Date.now() jest.useFakeTimers() jest.spyOn(Date, "now").mockImplementation(() => fakeNow) const store = mobx.observable({ count1: 0, count2: 0 }) // Track whether counts are observed let count1IsObserved = false let count2IsObserved = false mobx.onBecomeObserved(store, "count1", () => (count1IsObserved = true)) mobx.onBecomeUnobserved(store, "count1", () => (count1IsObserved = false)) mobx.onBecomeObserved(store, "count2", () => (count2IsObserved = true)) mobx.onBecomeUnobserved(store, "count2", () => (count2IsObserved = false)) const TestComponent1 = () => useObserver(() => <div>{store.count1}</div>) const TestComponent2 = () => useObserver(() => <div>{store.count2}</div>) // Render, then remove only #2 const rendering = render( <React.StrictMode> <TestComponent1 /> <TestComponent2 /> </React.StrictMode> ) rendering.rerender( <React.StrictMode> <TestComponent1 /> </React.StrictMode> ) // Allow any reaction-disposal cleanup timers to run const skip = Math.max(REGISTRY_FINALIZE_AFTER, REGISTRY_SWEEP_INTERVAL) fakeNow += skip jest.advanceTimersByTime(skip) // count1 should still be being observed by Component1, // but count2 should have had its reaction cleaned up. expect(count1IsObserved).toBeTruthy() expect(count2IsObserved).toBeFalsy() }) test("cleanup timer should not clean up recently-pended reactions", () => { // If we're not careful with timings, it's possible to get the // following scenario: // 1. Component instance A is being created; it renders, we put its reaction R1 into the cleanup list // 2. Strict/Concurrent mode causes that render to be thrown away // 3. Component instance A is being created; it renders, we put its reaction R2 into the cleanup list // 4. The MobX reaction timer from 5 seconds ago kicks in and cleans up all reactions from uncommitted // components, including R1 and R2 // 5. The commit phase runs for component A, but reaction R2 has already been disposed. Game over. // This unit test attempts to replicate that scenario: registry.finalizeAllImmediately() // Unfortunately, Jest fake timers don't mock out Date.now, so we fake // that out in parallel to Jest useFakeTimers const fakeNow = Date.now() jest.useFakeTimers() jest.spyOn(Date, "now").mockImplementation(() => fakeNow) const store = mobx.observable({ count: 0 }) // Track whether the count is observed let countIsObserved = false mobx.onBecomeObserved(store, "count", () => (countIsObserved = true)) mobx.onBecomeUnobserved(store, "count", () => (countIsObserved = false)) const TestComponent1 = () => useObserver(() => <div>{store.count}</div>) const rendering = render( // We use StrictMode here, but it would be helpful to switch this to use real // concurrent mode: we don't have a true async render right now so this test // isn't as thorough as it could be. <React.StrictMode> <TestComponent1 /> </React.StrictMode> ) // We need to trigger our cleanup timer to run. We can't do this simply // by running all jest's faked timers as that would allow the scheduled // `useEffect` calls to run, and we want to simulate our cleanup timer // getting in between those stages. // We force our cleanup loop to run even though enough time hasn't _really_ // elapsed. In theory, it won't do anything because not enough time has // elapsed since the reactions were queued, and so they won't be disposed. registry.sweep() // Advance time enough to allow any timer-queued effects to run jest.advanceTimersByTime(500) // Now allow the useEffect calls to run to completion. act(() => { // no-op, but triggers effect flushing }) // count should still be observed expect(countIsObserved).toBeTruthy() }) // TODO: MWE: disabled during React 18 migration, not sure how to express it icmw with testing-lib, // and using new React renderRoot will fail icmw JSDOM test.skip("component should recreate reaction if necessary", () => { // There _may_ be very strange cases where the reaction gets tidied up // but is actually still needed. This _really_ shouldn't happen. // e.g. if we're using Suspense and the component starts to render, // but then gets paused for 60 seconds, and then comes back to life. // With the implementation of React at the time of writing this, React // will actually fully re-render that component (discarding previous // hook slots) before going ahead with a commit, but it's unwise // to depend on such an implementation detail. So we must cope with // the component having had its reaction tidied and still going on to // be committed. In that case we recreate the reaction and force // an update. // This unit test attempts to replicate that scenario: registry.finalizeAllImmediately() // Unfortunately, Jest fake timers don't mock out Date.now, so we fake // that out in parallel to Jest useFakeTimers let fakeNow = Date.now() jest.useFakeTimers() jest.spyOn(Date, "now").mockImplementation(() => fakeNow) const store = mobx.observable({ count: 0 }) // Track whether the count is observed let countIsObserved = false mobx.onBecomeObserved(store, "count", () => (countIsObserved = true)) mobx.onBecomeUnobserved(store, "count", () => (countIsObserved = false)) const TestComponent1 = () => useObserver(() => <div>{store.count}</div>) const rendering = render( <React.StrictMode> <TestComponent1 /> </React.StrictMode> ) // We need to trigger our cleanup timer to run. We don't want // to allow Jest's effects to run, however: we want to simulate the // case where the component is rendered, then the reaction gets cleaned up, // and _then_ the component commits. // Force everything to be disposed. const skip = Math.max(REGISTRY_FINALIZE_AFTER, REGISTRY_SWEEP_INTERVAL) fakeNow += skip registry.sweep() // The reaction should have been cleaned up. expect(countIsObserved).toBeFalsy() // Whilst nobody's looking, change the observable value store.count = 42 // Now allow the useEffect calls to run to completion, // re-awakening the component. jest.advanceTimersByTime(500) act(() => { // no-op, but triggers effect flushing }) // count should be observed once more. expect(countIsObserved).toBeTruthy() // and the component should have rendered enough to // show the latest value, which was set whilst it // wasn't even looking. expect(rendering.baseElement.textContent).toContain("42") })
4,810
0
petrpan-code/mobxjs/mobx/packages/mobx-react-lite
petrpan-code/mobxjs/mobx/packages/mobx-react-lite/__tests__/transactions.test.tsx
import * as mobx from "mobx" import * as React from "react" import { act, render } from "@testing-library/react" import { observer } from "../src" test("mobx issue 50", done => { const foo = { a: mobx.observable.box(true), b: mobx.observable.box(false), c: mobx.computed((): boolean => { // console.log("evaluate c") return foo.b.get() }) } function flipStuff() { mobx.transaction(() => { foo.a.set(!foo.a.get()) foo.b.set(!foo.b.get()) }) } let asText = "" let willReactCount = 0 mobx.autorun(() => (asText = [foo.a.get(), foo.b.get(), foo.c.get()].join(":"))) const Test = observer(() => { willReactCount++ return <div id="x">{[foo.a.get(), foo.b.get(), foo.c.get()].join(",")}</div> }) render(<Test />) setImmediate(() => { act(() => { flipStuff() }) expect(asText).toBe("false:true:true") expect(document.getElementById("x")!.innerHTML).toBe("false,true,true") expect(willReactCount).toBe(2) done() }) }) it("should respect transaction", async () => { const a = mobx.observable.box(2) const loaded = mobx.observable.box(false) const valuesSeen = [] as number[] const Component = observer(() => { valuesSeen.push(a.get()) if (loaded.get()) { return <div>{a.get()}</div> } return <div>loading</div> }) const { container } = render(<Component />) act(() => { mobx.transaction(() => { a.set(3) a.set(4) loaded.set(true) }) }) expect(container.textContent!.replace(/\s+/g, "")).toBe("4") expect(valuesSeen.sort()).toEqual([2, 4].sort()) })
4,812
0
petrpan-code/mobxjs/mobx/packages/mobx-react-lite
petrpan-code/mobxjs/mobx/packages/mobx-react-lite/__tests__/useAsObservableSource.deprecated.test.tsx
import { act, cleanup, render } from "@testing-library/react" import { renderHook } from "@testing-library/react-hooks" import { autorun, configure, observable } from "mobx" import * as React from "react" import { useEffect, useState } from "react" import { Observer, observer, useAsObservableSource, useLocalStore } from "../src" import { resetMobx } from "./utils" afterEach(cleanup) afterEach(resetMobx) let consoleWarnMock: jest.SpyInstance | undefined afterEach(() => { consoleWarnMock?.mockRestore() }) describe("base useAsObservableSource should work", () => { it("with <Observer>", () => { consoleWarnMock = jest.spyOn(console, "warn").mockImplementation(() => {}) let counterRender = 0 let observerRender = 0 function Counter({ multiplier }: { multiplier: number }) { counterRender++ const observableProps = useAsObservableSource({ multiplier }) const store = useLocalStore(() => ({ count: 10, get multiplied() { return observableProps.multiplier * this.count }, inc() { this.count += 1 } })) return ( <Observer> {() => { observerRender++ return ( <div> Multiplied count: <span>{store.multiplied}</span> <button id="inc" onClick={store.inc}> Increment </button> </div> ) }} </Observer> ) } function Parent() { const [multiplier, setMultiplier] = useState(1) return ( <div> <Counter multiplier={multiplier} /> <button id="incmultiplier" onClick={() => setMultiplier(m => m + 1)} /> </div> ) } const { container } = render(<Parent />) expect(container.querySelector("span")!.innerHTML).toBe("10") expect(counterRender).toBe(1) expect(observerRender).toBe(1) act(() => { ;(container.querySelector("#inc")! as any).click() }) expect(container.querySelector("span")!.innerHTML).toBe("11") expect(counterRender).toBe(1) expect(observerRender).toBe(2) act(() => { ;(container.querySelector("#incmultiplier")! as any).click() }) expect(container.querySelector("span")!.innerHTML).toBe("22") expect(counterRender).toBe(2) expect(observerRender).toBe(3) expect(consoleWarnMock).toMatchSnapshot() }) it("with observer()", () => { let counterRender = 0 const Counter = observer(({ multiplier }: { multiplier: number }) => { counterRender++ const observableProps = useAsObservableSource({ multiplier }) const store = useLocalStore(() => ({ count: 10, get multiplied() { return observableProps.multiplier * this.count }, inc() { this.count += 1 } })) return ( <div> Multiplied count: <span>{store.multiplied}</span> <button id="inc" onClick={store.inc}> Increment </button> </div> ) }) function Parent() { const [multiplier, setMultiplier] = useState(1) return ( <div> <Counter multiplier={multiplier} /> <button id="incmultiplier" onClick={() => setMultiplier(m => m + 1)} /> </div> ) } const { container } = render(<Parent />) expect(container.querySelector("span")!.innerHTML).toBe("10") expect(counterRender).toBe(1) act(() => { ;(container.querySelector("#inc")! as any).click() }) expect(container.querySelector("span")!.innerHTML).toBe("11") expect(counterRender).toBe(2) act(() => { ;(container.querySelector("#incmultiplier")! as any).click() }) expect(container.querySelector("span")!.innerHTML).toBe("22") expect(counterRender).toBe(4) // One from props, second from updating local observable (setState during render) }) }) test("useAsObservableSource with effects should work", () => { const multiplierSeenByEffect: number[] = [] const valuesSeenByEffect: number[] = [] const thingsSeenByEffect: Array<[number, number, number]> = [] function Counter({ multiplier }: { multiplier: number }) { const observableProps = useAsObservableSource({ multiplier }) const store = useLocalStore(() => ({ count: 10, get multiplied() { return observableProps.multiplier * this.count }, inc() { this.count += 1 } })) useEffect( () => autorun(() => { multiplierSeenByEffect.push(observableProps.multiplier) }), [] ) useEffect( () => autorun(() => { valuesSeenByEffect.push(store.count) }), [] ) useEffect( () => autorun(() => { thingsSeenByEffect.push([ observableProps.multiplier, store.multiplied, multiplier ]) // multiplier is trapped! }), [] ) return ( <button id="inc" onClick={store.inc}> Increment </button> ) } function Parent() { const [multiplier, setMultiplier] = useState(1) return ( <div> <Counter multiplier={multiplier} /> <button id="incmultiplier" onClick={() => setMultiplier(m => m + 1)} /> </div> ) } const { container } = render(<Parent />) act(() => { ;(container.querySelector("#inc")! as any).click() }) act(() => { ;(container.querySelector("#incmultiplier")! as any).click() }) expect(valuesSeenByEffect).toEqual([10, 11]) expect(multiplierSeenByEffect).toEqual([1, 2]) expect(thingsSeenByEffect).toEqual([ [1, 10, 1], [1, 11, 1], [2, 22, 1] ]) }) describe("combining observer with props and stores", () => { it("keeps track of observable values", () => { const TestComponent = observer((props: any) => { const localStore = useLocalStore(() => ({ get value() { return props.store.x + 5 * props.store.y } })) return <div>{localStore.value}</div> }) const store = observable({ x: 5, y: 1 }) const { container } = render(<TestComponent store={store} />) const div = container.querySelector("div")! expect(div.textContent).toBe("10") act(() => { store.y = 2 }) expect(div.textContent).toBe("15") act(() => { store.x = 10 }) expect(div.textContent).toBe("20") }) it("allows non-observables to be used if specified as as source", () => { const renderedValues: number[] = [] const TestComponent = observer((props: any) => { const obsProps = useAsObservableSource({ y: props.y }) const localStore = useLocalStore(() => ({ get value() { return props.store.x + 5 * obsProps.y } })) renderedValues.push(localStore.value) return <div>{localStore.value}</div> }) const store = observable({ x: 5 }) const { container, rerender } = render(<TestComponent store={store} y={1} />) const div = container.querySelector("div")! expect(div.textContent).toBe("10") rerender(<TestComponent store={store} y={2} />) expect(div.textContent).toBe("15") act(() => { store.x = 10 }) expect(renderedValues).toEqual([ 10, 15, // props change 15, // local observable change (setState during render) 20 ]) // TODO: re-enable this line. When debugging, the correct value is returned from render, // which is also visible with renderedValues, however, querying the dom doesn't show the correct result // possible a bug with @testing-library/react? // expect(container.querySelector("div")!.textContent).toBe("20") // TODO: somehow this change is not visible in the tester! }) }) describe("enforcing actions", () => { it("'never' should work", () => { configure({ enforceActions: "never" }) const { result } = renderHook(() => { const [thing, setThing] = React.useState("world") useAsObservableSource({ hello: thing }) useEffect(() => setThing("react"), []) }) expect(result.error).not.toBeDefined() }) it("only when 'observed' should work", () => { configure({ enforceActions: "observed" }) const { result } = renderHook(() => { const [thing, setThing] = React.useState("world") useAsObservableSource({ hello: thing }) useEffect(() => setThing("react"), []) }) expect(result.error).not.toBeDefined() }) it("'always' should work", () => { configure({ enforceActions: "always" }) const { result } = renderHook(() => { const [thing, setThing] = React.useState("world") useAsObservableSource({ hello: thing }) useEffect(() => setThing("react"), []) }) expect(result.error).not.toBeDefined() }) })
4,813
0
petrpan-code/mobxjs/mobx/packages/mobx-react-lite
petrpan-code/mobxjs/mobx/packages/mobx-react-lite/__tests__/useAsObservableSource.test.tsx
import { act, cleanup, render } from "@testing-library/react" import { renderHook } from "@testing-library/react-hooks" import mockConsole from "jest-mock-console" import { autorun, configure, observable } from "mobx" import * as React from "react" import { useEffect, useState } from "react" import { Observer, observer, useLocalObservable } from "../src" import { resetMobx } from "./utils" import { useObserver } from "../src/useObserver" afterEach(cleanup) afterEach(resetMobx) describe("base useAsObservableSource should work", () => { it("with useObserver", () => { let counterRender = 0 let observerRender = 0 function Counter({ multiplier }: { multiplier: number }) { counterRender++ const observableProps = useLocalObservable(() => ({ multiplier })) Object.assign(observableProps, { multiplier }) const store = useLocalObservable(() => ({ count: 10, get multiplied() { return observableProps.multiplier * this.count }, inc() { this.count += 1 } })) return useObserver( () => ( observerRender++, ( <div> Multiplied count: <span>{store.multiplied}</span> <button id="inc" onClick={store.inc}> Increment </button> </div> ) ) ) } function Parent() { const [multiplier, setMultiplier] = useState(1) return ( <div> <Counter multiplier={multiplier} /> <button id="incmultiplier" onClick={() => setMultiplier(m => m + 1)} /> </div> ) } const { container } = render(<Parent />) expect(container.querySelector("span")!.innerHTML).toBe("10") expect(counterRender).toBe(1) expect(observerRender).toBe(1) act(() => { ;(container.querySelector("#inc")! as any).click() }) expect(container.querySelector("span")!.innerHTML).toBe("11") expect(counterRender).toBe(2) // 1 would be better! expect(observerRender).toBe(2) act(() => { ;(container.querySelector("#incmultiplier")! as any).click() }) expect(container.querySelector("span")!.innerHTML).toBe("22") expect(counterRender).toBe(4) // TODO: avoid double rendering here! expect(observerRender).toBe(4) // TODO: avoid double rendering here! }) it("with <Observer>", () => { let counterRender = 0 let observerRender = 0 function Counter({ multiplier }: { multiplier: number }) { counterRender++ const store = useLocalObservable(() => ({ multiplier, count: 10, get multiplied() { return this.multiplier * this.count }, inc() { this.count += 1 } })) useEffect(() => { store.multiplier = multiplier }, [multiplier]) return ( <Observer> {() => { observerRender++ return ( <div> Multiplied count: <span>{store.multiplied}</span> <button id="inc" onClick={store.inc}> Increment </button> </div> ) }} </Observer> ) } function Parent() { const [multiplier, setMultiplier] = useState(1) return ( <div> <Counter multiplier={multiplier} /> <button id="incmultiplier" onClick={() => setMultiplier(m => m + 1)} /> </div> ) } const { container } = render(<Parent />) expect(container.querySelector("span")!.innerHTML).toBe("10") expect(counterRender).toBe(1) expect(observerRender).toBe(1) act(() => { ;(container.querySelector("#inc")! as any).click() }) expect(container.querySelector("span")!.innerHTML).toBe("11") expect(counterRender).toBe(1) expect(observerRender).toBe(2) act(() => { ;(container.querySelector("#incmultiplier")! as any).click() }) expect(container.querySelector("span")!.innerHTML).toBe("22") expect(counterRender).toBe(2) expect(observerRender).toBe(4) }) it("with observer()", () => { let counterRender = 0 const Counter = observer(({ multiplier }: { multiplier: number }) => { counterRender++ const store = useLocalObservable(() => ({ multiplier, count: 10, get multiplied() { return this.multiplier * this.count }, inc() { this.count += 1 } })) useEffect(() => { store.multiplier = multiplier }, [multiplier]) return ( <div> Multiplied count: <span>{store.multiplied}</span> <button id="inc" onClick={store.inc}> Increment </button> </div> ) }) function Parent() { const [multiplier, setMultiplier] = useState(1) return ( <div> <Counter multiplier={multiplier} /> <button id="incmultiplier" onClick={() => setMultiplier(m => m + 1)} /> </div> ) } const { container } = render(<Parent />) expect(container.querySelector("span")!.innerHTML).toBe("10") expect(counterRender).toBe(1) act(() => { ;(container.querySelector("#inc")! as any).click() }) expect(container.querySelector("span")!.innerHTML).toBe("11") expect(counterRender).toBe(2) act(() => { ;(container.querySelector("#incmultiplier")! as any).click() }) expect(container.querySelector("span")!.innerHTML).toBe("22") expect(counterRender).toBe(4) // One from props, second from updating local observable with effect }) }) test("useAsObservableSource with effects should work", () => { const multiplierSeenByEffect: number[] = [] const valuesSeenByEffect: number[] = [] const thingsSeenByEffect: Array<[number, number, number]> = [] function Counter({ multiplier }: { multiplier: number }) { const store = useLocalObservable(() => ({ multiplier, count: 10, get multiplied() { return this.multiplier * this.count }, inc() { this.count += 1 } })) useEffect(() => { store.multiplier = multiplier }, [multiplier]) useEffect( () => autorun(() => { multiplierSeenByEffect.push(store.multiplier) }), [] ) useEffect( () => autorun(() => { valuesSeenByEffect.push(store.count) }), [] ) useEffect( () => autorun(() => { thingsSeenByEffect.push([store.multiplier, store.multiplied, multiplier]) // multiplier is trapped! }), [] ) return ( <button id="inc" onClick={store.inc}> Increment </button> ) } function Parent() { const [multiplier, setMultiplier] = useState(1) return ( <div> <Counter multiplier={multiplier} /> <button id="incmultiplier" onClick={() => setMultiplier(m => m + 1)} /> </div> ) } const { container } = render(<Parent />) act(() => { ;(container.querySelector("#inc")! as any).click() }) act(() => { ;(container.querySelector("#incmultiplier")! as any).click() }) expect(valuesSeenByEffect).toEqual([10, 11]) expect(multiplierSeenByEffect).toEqual([1, 2]) expect(thingsSeenByEffect).toEqual([ [1, 10, 1], [1, 11, 1], [2, 22, 1] ]) }) describe("combining observer with props and stores", () => { it("keeps track of observable values", () => { const TestComponent = observer((props: any) => { const localStore = useLocalObservable(() => ({ get value() { return props.store.x + 5 * props.store.y } })) return <div>{localStore.value}</div> }) const store = observable({ x: 5, y: 1 }) const { container } = render(<TestComponent store={store} />) const div = container.querySelector("div")! expect(div.textContent).toBe("10") act(() => { store.y = 2 }) expect(div.textContent).toBe("15") act(() => { store.x = 10 }) expect(div.textContent).toBe("20") }) it("allows non-observables to be used if specified as as source", () => { const renderedValues: number[] = [] const TestComponent = observer((props: any) => { const localStore = useLocalObservable(() => ({ y: props.y, get value() { return props.store.x + 5 * this.y } })) localStore.y = props.y renderedValues.push(localStore.value) return <div>{localStore.value}</div> }) const store = observable({ x: 5 }) const { container, rerender } = render(<TestComponent store={store} y={1} />) const div = container.querySelector("div")! expect(div.textContent).toBe("10") rerender(<TestComponent store={store} y={2} />) expect(div.textContent).toBe("15") act(() => { store.x = 10 }) expect(renderedValues).toEqual([ 10, 15, // props change 15, // local observable change during render (localStore.y = props.y) 20 ]) expect(container.querySelector("div")!.textContent).toBe("20") }) }) describe("enforcing actions", () => { it("'never' should work", () => { configure({ enforceActions: "never" }) const { result } = renderHook(() => { const [thing, setThing] = React.useState("world") useLocalObservable(() => ({ hello: thing })) useEffect(() => setThing("react"), []) }) expect(result.error).not.toBeDefined() }) it("only when 'observed' should work", () => { configure({ enforceActions: "observed" }) const { result } = renderHook(() => { const [thing, setThing] = React.useState("world") useLocalObservable(() => ({ hello: thing })) useEffect(() => setThing("react"), []) }) expect(result.error).not.toBeDefined() }) it("'always' should work", () => { configure({ enforceActions: "always" }) const { result } = renderHook(() => { const [thing, setThing] = React.useState("world") useLocalObservable(() => ({ hello: thing })) useEffect(() => setThing("react"), []) }) expect(result.error).not.toBeDefined() }) }) it("doesn't update a component while rendering a different component - #274", () => { // https://github.com/facebook/react/pull/17099 const Parent = observer((props: any) => { const observableProps = useLocalObservable(() => props) useEffect(() => { Object.assign(observableProps, props) }, [props]) return <Child observableProps={observableProps} /> }) const Child = observer(({ observableProps }: any) => { return observableProps.foo }) const { container, rerender } = render(<Parent foo={1} />) expect(container.textContent).toBe("1") const restoreConsole = mockConsole() rerender(<Parent foo={2} />) expect(console.error).not.toHaveBeenCalled() restoreConsole() expect(container.textContent).toBe("2") })
4,814
0
petrpan-code/mobxjs/mobx/packages/mobx-react-lite
petrpan-code/mobxjs/mobx/packages/mobx-react-lite/__tests__/useLocalObservable.test.tsx
import * as mobx from "mobx" import * as React from "react" import { renderHook } from "@testing-library/react-hooks" import { act, cleanup, fireEvent, render } from "@testing-library/react" import { Observer, observer, useLocalObservable } from "../src" import { useEffect, useState } from "react" import { autorun } from "mobx" import { useObserver } from "../src/useObserver" afterEach(cleanup) let consoleWarnMock: jest.SpyInstance | undefined afterEach(() => { consoleWarnMock?.mockRestore() }) test("base useLocalStore should work", () => { let counterRender = 0 let observerRender = 0 let outerStoreRef: any function Counter() { counterRender++ const store = (outerStoreRef = useLocalObservable(() => ({ count: 0, count2: 0, // not used in render inc() { this.count += 1 } }))) return useObserver(() => { observerRender++ return ( <div> Count: <span>{store.count}</span> <button onClick={store.inc}>Increment</button> </div> ) }) } const { container } = render(<Counter />) expect(container.querySelector("span")!.innerHTML).toBe("0") expect(counterRender).toBe(1) expect(observerRender).toBe(1) act(() => { container.querySelector("button")!.click() }) expect(container.querySelector("span")!.innerHTML).toBe("1") expect(counterRender).toBe(2) expect(observerRender).toBe(2) act(() => { outerStoreRef.count++ }) expect(container.querySelector("span")!.innerHTML).toBe("2") expect(counterRender).toBe(3) expect(observerRender).toBe(3) act(() => { outerStoreRef.count2++ }) // No re-render! expect(container.querySelector("span")!.innerHTML).toBe("2") expect(counterRender).toBe(3) expect(observerRender).toBe(3) }) describe("is used to keep observable within component body", () => { it("value can be changed over renders", () => { const TestComponent = () => { const obs = useLocalObservable(() => ({ x: 1, y: 2 })) return ( <div onClick={() => (obs.x += 1)}> {obs.x}-{obs.y} </div> ) } const { container, rerender } = render(<TestComponent />) const div = container.querySelector("div")! expect(div.textContent).toBe("1-2") fireEvent.click(div) // observer not used, need to render from outside rerender(<TestComponent />) expect(div.textContent).toBe("2-2") }) it("works with observer as well", () => { let renderCount = 0 const TestComponent = observer(() => { renderCount++ const obs = useLocalObservable(() => ({ x: 1, y: 2 })) return ( <div onClick={() => (obs.x += 1)}> {obs.x}-{obs.y} </div> ) }) const { container } = render(<TestComponent />) const div = container.querySelector("div")! expect(div.textContent).toBe("1-2") fireEvent.click(div) expect(div.textContent).toBe("2-2") fireEvent.click(div) expect(div.textContent).toBe("3-2") expect(renderCount).toBe(3) }) it("actions can be used", () => { const TestComponent = observer(() => { const obs = useLocalObservable(() => ({ x: 1, y: 2, inc() { obs.x += 1 } })) return ( <div onClick={obs.inc}> {obs.x}-{obs.y} </div> ) }) const { container } = render(<TestComponent />) const div = container.querySelector("div")! expect(div.textContent).toBe("1-2") fireEvent.click(div) expect(div.textContent).toBe("2-2") }) it("computed properties works as well", () => { const TestComponent = observer(() => { const obs = useLocalObservable(() => ({ x: 1, y: 2, get z() { return obs.x + obs.y } })) return <div onClick={() => (obs.x += 1)}>{obs.z}</div> }) const { container } = render(<TestComponent />) const div = container.querySelector("div")! expect(div.textContent).toBe("3") fireEvent.click(div) expect(div.textContent).toBe("4") }) it("computed properties can use local functions", () => { const TestComponent = observer(() => { const obs = useLocalObservable(() => ({ x: 1, y: 2, getMeThatX() { return this.x }, get z() { return this.getMeThatX() + obs.y } })) return <div onClick={() => (obs.x += 1)}>{obs.z}</div> }) const { container } = render(<TestComponent />) const div = container.querySelector("div")! expect(div.textContent).toBe("3") fireEvent.click(div) expect(div.textContent).toBe("4") }) it("transactions are respected", () => { const seen: number[] = [] const TestComponent = observer(() => { const obs = useLocalObservable(() => ({ x: 1, inc(delta: number) { this.x += delta this.x += delta } })) useEffect( () => autorun(() => { seen.push(obs.x) }), [] ) return ( <div onClick={() => { obs.inc(2) }} > Test </div> ) }) const { container } = render(<TestComponent />) const div = container.querySelector("div")! fireEvent.click(div) expect(seen).toEqual([1, 5]) // No 3! }) it("Map can used instead of object", () => { const TestComponent = observer(() => { const map = useLocalObservable(() => new Map([["initial", 10]])) return ( <div onClick={() => map.set("later", 20)}> {Array.from(map).map(([key, value]) => ( <div key={key}> {key} - {value} </div> ))} </div> ) }) const { container } = render(<TestComponent />) const div = container.querySelector("div")! expect(div.textContent).toBe("initial - 10") fireEvent.click(div) expect(div.textContent).toBe("initial - 10later - 20") }) describe("with props", () => { it("and useObserver", () => { let counterRender = 0 let observerRender = 0 function Counter({ multiplier }: { multiplier: number }) { counterRender++ const store = useLocalObservable(() => ({ multiplier, count: 10, get multiplied() { return this.multiplier * this.count }, inc() { this.count += 1 } })) useEffect(() => { store.multiplier = multiplier }, [multiplier]) return useObserver( () => ( observerRender++, ( <div> Multiplied count: <span>{store.multiplied}</span> <button id="inc" onClick={store.inc}> Increment </button> </div> ) ) ) } function Parent() { const [multiplier, setMultiplier] = useState(1) return ( <div> <Counter multiplier={multiplier} /> <button id="incmultiplier" onClick={() => setMultiplier(m => m + 1)} /> </div> ) } const { container } = render(<Parent />) expect(container.querySelector("span")!.innerHTML).toBe("10") expect(counterRender).toBe(1) expect(observerRender).toBe(1) act(() => { ;(container.querySelector("#inc")! as any).click() }) expect(container.querySelector("span")!.innerHTML).toBe("11") expect(counterRender).toBe(2) // 1 would be better! expect(observerRender).toBe(2) act(() => { ;(container.querySelector("#incmultiplier")! as any).click() }) expect(container.querySelector("span")!.innerHTML).toBe("22") expect(counterRender).toBe(4) // TODO: avoid double rendering here! expect(observerRender).toBe(4) // TODO: avoid double rendering here! }) it("with <Observer>", () => { let counterRender = 0 let observerRender = 0 function Counter({ multiplier }: { multiplier: number }) { counterRender++ const store = useLocalObservable(() => ({ multiplier, count: 10, get multiplied() { return this.multiplier * this.count }, inc() { this.count += 1 } })) useEffect(() => { store.multiplier = multiplier }, [multiplier]) return ( <Observer> {() => { observerRender++ return ( <div> Multiplied count: <span>{store.multiplied}</span> <button id="inc" onClick={store.inc}> Increment </button> </div> ) }} </Observer> ) } function Parent() { const [multiplier, setMultiplier] = useState(1) return ( <div> <Counter multiplier={multiplier} /> <button id="incmultiplier" onClick={() => setMultiplier(m => m + 1)} /> </div> ) } const { container } = render(<Parent />) expect(container.querySelector("span")!.innerHTML).toBe("10") expect(counterRender).toBe(1) expect(observerRender).toBe(1) act(() => { ;(container.querySelector("#inc")! as any).click() }) expect(container.querySelector("span")!.innerHTML).toBe("11") expect(counterRender).toBe(1) expect(observerRender).toBe(2) act(() => { ;(container.querySelector("#incmultiplier")! as any).click() }) expect(container.querySelector("span")!.innerHTML).toBe("22") expect(counterRender).toBe(2) expect(observerRender).toBe(4) }) it("with observer()", () => { let counterRender = 0 const Counter = observer(({ multiplier }: { multiplier: number }) => { counterRender++ const store = useLocalObservable(() => ({ multiplier, count: 10, get multiplied() { return this.multiplier * this.count }, inc() { this.count += 1 } })) useEffect(() => { store.multiplier = multiplier }, [multiplier]) return ( <div> Multiplied count: <span>{store.multiplied}</span> <button id="inc" onClick={store.inc}> Increment </button> </div> ) }) function Parent() { const [multiplier, setMultiplier] = useState(1) return ( <div> <Counter multiplier={multiplier} /> <button id="incmultiplier" onClick={() => setMultiplier(m => m + 1)} /> </div> ) } const { container } = render(<Parent />) expect(container.querySelector("span")!.innerHTML).toBe("10") expect(counterRender).toBe(1) act(() => { ;(container.querySelector("#inc")! as any).click() }) expect(container.querySelector("span")!.innerHTML).toBe("11") expect(counterRender).toBe(2) act(() => { ;(container.querySelector("#incmultiplier")! as any).click() }) expect(container.querySelector("span")!.innerHTML).toBe("22") expect(counterRender).toBe(4) // One from props, second from updating local observable with effect }) }) }) describe("enforcing actions", () => { it("'never' should work", () => { mobx.configure({ enforceActions: "never" }) consoleWarnMock = jest.spyOn(console, "warn").mockImplementation(() => {}) const { result } = renderHook(() => { const [multiplier, setMultiplier] = React.useState(2) const store = useLocalObservable(() => ({ multiplier, count: 10, get multiplied() { return this.multiplier * this.count }, inc() { this.count += 1 } })) useEffect(() => { store.multiplier = multiplier }, [multiplier]) useEffect(() => setMultiplier(3), []) }) expect(result.error).not.toBeDefined() expect(consoleWarnMock).not.toBeCalled() }) it("only when 'observed' should work", () => { mobx.configure({ enforceActions: "observed" }) consoleWarnMock = jest.spyOn(console, "warn").mockImplementation(() => {}) const { result } = renderHook(() => { const [multiplier, setMultiplier] = React.useState(2) const store = useLocalObservable(() => ({ multiplier, count: 10, get multiplied() { return this.multiplier * this.count }, inc() { this.count += 1 } })) useEffect(() => { store.multiplier = multiplier }, [multiplier]) useEffect(() => setMultiplier(3), []) }) expect(result.error).not.toBeDefined() expect(consoleWarnMock).not.toBeCalled() }) it("'always' should work", () => { mobx.configure({ enforceActions: "always" }) consoleWarnMock = jest.spyOn(console, "warn").mockImplementation(() => {}) const { result } = renderHook(() => { const [multiplier, setMultiplier] = React.useState(2) const store = useLocalObservable(() => ({ multiplier, count: 10, get multiplied() { return this.multiplier * this.count }, inc() { this.count += 1 } })) useEffect(() => { store.multiplier = multiplier }, [multiplier]) useEffect(() => setMultiplier(3), []) }) expect(result.error).not.toBeDefined() expect(consoleWarnMock).toBeCalledTimes(2) }) })
4,815
0
petrpan-code/mobxjs/mobx/packages/mobx-react-lite
petrpan-code/mobxjs/mobx/packages/mobx-react-lite/__tests__/useLocalStore.deprecated.test.tsx
import * as React from "react" import { act, cleanup, fireEvent, render } from "@testing-library/react" import { Observer, observer, useLocalStore } from "../src" import { useEffect, useState } from "react" import { autorun } from "mobx" afterEach(cleanup) let consoleWarnMock: jest.SpyInstance | undefined afterEach(() => { consoleWarnMock?.mockRestore() }) test("base useLocalStore should work", () => { consoleWarnMock = jest.spyOn(console, "warn").mockImplementation(() => {}) let counterRender = 0 let observerRender = 0 let outerStoreRef: any function Counter() { counterRender++ const store = (outerStoreRef = useLocalStore(() => ({ count: 0, count2: 0, // not used in render inc() { this.count += 1 } }))) return ( <Observer> {() => { observerRender++ return ( <div> Count: <span>{store.count}</span> <button onClick={store.inc}>Increment</button> </div> ) }} </Observer> ) } const { container } = render(<Counter />) expect(container.querySelector("span")!.innerHTML).toBe("0") expect(counterRender).toBe(1) expect(observerRender).toBe(1) act(() => { container.querySelector("button")!.click() }) expect(container.querySelector("span")!.innerHTML).toBe("1") expect(counterRender).toBe(1) expect(observerRender).toBe(2) act(() => { outerStoreRef.count++ }) expect(container.querySelector("span")!.innerHTML).toBe("2") expect(counterRender).toBe(1) expect(observerRender).toBe(3) act(() => { outerStoreRef.count2++ }) // No re-render! expect(container.querySelector("span")!.innerHTML).toBe("2") expect(counterRender).toBe(1) expect(observerRender).toBe(3) expect(consoleWarnMock).toMatchSnapshot() }) describe("is used to keep observable within component body", () => { it("value can be changed over renders", () => { const TestComponent = () => { const obs = useLocalStore(() => ({ x: 1, y: 2 })) return ( <div onClick={() => (obs.x += 1)}> {obs.x}-{obs.y} </div> ) } const { container, rerender } = render(<TestComponent />) const div = container.querySelector("div")! expect(div.textContent).toBe("1-2") fireEvent.click(div) // observer not used, need to render from outside rerender(<TestComponent />) expect(div.textContent).toBe("2-2") }) it("works with observer as well", () => { let renderCount = 0 const TestComponent = observer(() => { renderCount++ const obs = useLocalStore(() => ({ x: 1, y: 2 })) return ( <div onClick={() => (obs.x += 1)}> {obs.x}-{obs.y} </div> ) }) const { container } = render(<TestComponent />) const div = container.querySelector("div")! expect(div.textContent).toBe("1-2") fireEvent.click(div) expect(div.textContent).toBe("2-2") fireEvent.click(div) expect(div.textContent).toBe("3-2") expect(renderCount).toBe(3) }) it("actions can be used", () => { const TestComponent = observer(() => { const obs = useLocalStore(() => ({ x: 1, y: 2, inc() { obs.x += 1 } })) return ( <div onClick={obs.inc}> {obs.x}-{obs.y} </div> ) }) const { container } = render(<TestComponent />) const div = container.querySelector("div")! expect(div.textContent).toBe("1-2") fireEvent.click(div) expect(div.textContent).toBe("2-2") }) it("computed properties works as well", () => { const TestComponent = observer(() => { const obs = useLocalStore(() => ({ x: 1, y: 2, get z() { return obs.x + obs.y } })) return <div onClick={() => (obs.x += 1)}>{obs.z}</div> }) const { container } = render(<TestComponent />) const div = container.querySelector("div")! expect(div.textContent).toBe("3") fireEvent.click(div) expect(div.textContent).toBe("4") }) it("computed properties can use local functions", () => { const TestComponent = observer(() => { const obs = useLocalStore(() => ({ x: 1, y: 2, getMeThatX() { return this.x }, get z() { return this.getMeThatX() + obs.y } })) return <div onClick={() => (obs.x += 1)}>{obs.z}</div> }) const { container } = render(<TestComponent />) const div = container.querySelector("div")! expect(div.textContent).toBe("3") fireEvent.click(div) expect(div.textContent).toBe("4") }) it("transactions are respected", () => { const seen: number[] = [] const TestComponent = observer(() => { const obs = useLocalStore(() => ({ x: 1, inc(delta: number) { this.x += delta this.x += delta } })) useEffect( () => autorun(() => { seen.push(obs.x) }), [] ) return ( <div onClick={() => { obs.inc(2) }} > Test </div> ) }) const { container } = render(<TestComponent />) const div = container.querySelector("div")! fireEvent.click(div) expect(seen).toEqual([1, 5]) // No 3! }) it("Map can used instead of object", () => { const TestComponent = observer(() => { const map = useLocalStore(() => new Map([["initial", 10]])) return ( <div onClick={() => map.set("later", 20)}> {Array.from(map).map(([key, value]) => ( <div key={key}> {key} - {value} </div> ))} </div> ) }) const { container } = render(<TestComponent />) const div = container.querySelector("div")! expect(div.textContent).toBe("initial - 10") fireEvent.click(div) expect(div.textContent).toBe("initial - 10later - 20") }) describe("with props", () => { it("and useObserver", () => { consoleWarnMock = jest.spyOn(console, "warn").mockImplementation(() => {}) let counterRender = 0 let observerRender = 0 function Counter({ multiplier }: { multiplier: number }) { counterRender++ const store = useLocalStore( props => ({ count: 10, get multiplied() { return props.multiplier * this.count }, inc() { this.count += 1 } }), { multiplier } ) return ( <Observer> {() => ( observerRender++, ( <div> Multiplied count: <span>{store.multiplied}</span> <button id="inc" onClick={store.inc}> Increment </button> </div> ) )} </Observer> ) } function Parent() { const [multiplier, setMultiplier] = useState(1) return ( <div> <Counter multiplier={multiplier} /> <button id="incmultiplier" onClick={() => setMultiplier(m => m + 1)} /> </div> ) } const { container } = render(<Parent />) expect(container.querySelector("span")!.innerHTML).toBe("10") expect(counterRender).toBe(1) expect(observerRender).toBe(1) act(() => { ;(container.querySelector("#inc")! as any).click() }) expect(container.querySelector("span")!.innerHTML).toBe("11") expect(counterRender).toBe(1) // or 2 expect(observerRender).toBe(2) act(() => { ;(container.querySelector("#incmultiplier")! as any).click() }) expect(container.querySelector("span")!.innerHTML).toBe("22") expect(counterRender).toBe(2) expect(observerRender).toBe(3) expect(consoleWarnMock).toMatchSnapshot() }) it("with <Observer>", () => { let counterRender = 0 let observerRender = 0 function Counter({ multiplier }: { multiplier: number }) { counterRender++ const store = useLocalStore( props => ({ count: 10, get multiplied() { return props.multiplier * this.count }, inc() { this.count += 1 } }), { multiplier } ) return ( <Observer> {() => { observerRender++ return ( <div> Multiplied count: <span>{store.multiplied}</span> <button id="inc" onClick={store.inc}> Increment </button> </div> ) }} </Observer> ) } function Parent() { const [multiplier, setMultiplier] = useState(1) return ( <div> <Counter multiplier={multiplier} /> <button id="incmultiplier" onClick={() => setMultiplier(m => m + 1)} /> </div> ) } const { container } = render(<Parent />) expect(container.querySelector("span")!.innerHTML).toBe("10") expect(counterRender).toBe(1) expect(observerRender).toBe(1) act(() => { ;(container.querySelector("#inc")! as any).click() }) expect(container.querySelector("span")!.innerHTML).toBe("11") expect(counterRender).toBe(1) expect(observerRender).toBe(2) act(() => { ;(container.querySelector("#incmultiplier")! as any).click() }) expect(container.querySelector("span")!.innerHTML).toBe("22") expect(counterRender).toBe(2) expect(observerRender).toBe(3) }) it("with observer()", () => { let counterRender = 0 const Counter = observer(({ multiplier }: { multiplier: number }) => { counterRender++ const store = useLocalStore( props => ({ count: 10, get multiplied() { return props.multiplier * this.count }, inc() { this.count += 1 } }), { multiplier } ) return ( <div> Multiplied count: <span>{store.multiplied}</span> <button id="inc" onClick={store.inc}> Increment </button> </div> ) }) function Parent() { const [multiplier, setMultiplier] = useState(1) return ( <div> <Counter multiplier={multiplier} /> <button id="incmultiplier" onClick={() => setMultiplier(m => m + 1)} /> </div> ) } const { container } = render(<Parent />) expect(container.querySelector("span")!.innerHTML).toBe("10") expect(counterRender).toBe(1) act(() => { ;(container.querySelector("#inc")! as any).click() }) expect(container.querySelector("span")!.innerHTML).toBe("11") expect(counterRender).toBe(2) act(() => { ;(container.querySelector("#incmultiplier")! as any).click() }) expect(container.querySelector("span")!.innerHTML).toBe("22") expect(counterRender).toBe(4) // One from props, second from updating source (setState during render) }) }) })
4,817
0
petrpan-code/mobxjs/mobx/packages/mobx-react-lite/__tests__
petrpan-code/mobxjs/mobx/packages/mobx-react-lite/__tests__/__snapshots__/observer.test.tsx.snap
// Jest Snapshot v1, https://goo.gl/fbAQLP exports[`changing state in render should fail 1`] = ` <div> <div> 4 </div> </div> `; exports[`changing state in render should fail 2`] = ` <div> <div> 4 </div> </div> `; exports[`issue 12 init state is correct 1`] = ` <div> <div> <span> coffee ! </span> <span> tea </span> </div> </div> `; exports[`issue 12 init state is correct 2`] = ` <div> <div> <span> coffee ! </span> <span> tea </span> </div> </div> `; exports[`issue 12 run transaction 1`] = ` <div> <div> <span> soup </span> </div> </div> `; exports[`issue 12 run transaction 2`] = ` <div> <div> <span> soup </span> </div> </div> `; exports[`issue 309 isObserverBatched is still defined and yields true by default 1`] = ` [MockFunction] { "calls": [ [ "[MobX] Deprecated", ], ], "results": [ { "type": "return", "value": undefined, }, ], } `; exports[`issue 309 isObserverBatched is still defined and yields true by default 2`] = ` [MockFunction] { "calls": [ [ "[MobX] Deprecated", ], ], "results": [ { "type": "return", "value": undefined, }, ], } `; exports[`observer(cmp, { forwardRef: true }) + useImperativeHandle 1`] = ` [MockFunction] { "calls": [ [ "[mobx-react-lite] \`observer(fn, { forwardRef: true })\` is deprecated, use \`observer(React.forwardRef(fn))\`", ], ], "results": [ { "type": "return", "value": undefined, }, ], } `; exports[`useImperativeHandle and forwardRef should work with useObserver 1`] = `[MockFunction]`;
4,818
0
petrpan-code/mobxjs/mobx/packages/mobx-react-lite/__tests__
petrpan-code/mobxjs/mobx/packages/mobx-react-lite/__tests__/__snapshots__/printDebugValue.test.ts.snap
// Jest Snapshot v1, https://goo.gl/fbAQLP exports[`printDebugValue 1`] = ` { "dependencies": [ { "name": "[email protected]", }, { "dependencies": [ { "name": "[email protected]", }, ], "name": "[email protected]", }, ], "name": "Autorun@2", } `; exports[`printDebugValue 2`] = ` { "name": "Autorun@2", } `;
4,819
0
petrpan-code/mobxjs/mobx/packages/mobx-react-lite/__tests__
petrpan-code/mobxjs/mobx/packages/mobx-react-lite/__tests__/__snapshots__/useAsObservableSource.deprecated.test.tsx.snap
// Jest Snapshot v1, https://goo.gl/fbAQLP exports[`base useAsObservableSource should work with <Observer> 1`] = ` [MockFunction] { "calls": [ [ "[mobx-react-lite] 'useAsObservableSource' is deprecated, please store the values directly in an observable, for example by using 'useLocalObservable', and sync future updates using 'useEffect' when needed. See the README for examples.", ], [ "[mobx-react-lite] 'useLocalStore' is deprecated, use 'useLocalObservable' instead.", ], ], "results": [ { "type": "return", "value": undefined, }, { "type": "return", "value": undefined, }, ], } `;
4,820
0
petrpan-code/mobxjs/mobx/packages/mobx-react-lite/__tests__
petrpan-code/mobxjs/mobx/packages/mobx-react-lite/__tests__/__snapshots__/useLocalStore.deprecated.test.tsx.snap
// Jest Snapshot v1, https://goo.gl/fbAQLP exports[`base useLocalStore should work 1`] = ` [MockFunction] { "calls": [ [ "[mobx-react-lite] 'useLocalStore' is deprecated, use 'useLocalObservable' instead.", ], ], "results": [ { "type": "return", "value": undefined, }, ], } `; exports[`is used to keep observable within component body with props and useObserver 1`] = ` [MockFunction] { "calls": [ [ "[mobx-react-lite] 'useAsObservableSource' is deprecated, please store the values directly in an observable, for example by using 'useLocalObservable', and sync future updates using 'useEffect' when needed. See the README for examples.", ], ], "results": [ { "type": "return", "value": undefined, }, ], } `;
4,852
0
petrpan-code/mobxjs/mobx/packages/mobx-react
petrpan-code/mobxjs/mobx/packages/mobx-react/__tests__/Provider.test.tsx
import React from "react" import { Provider } from "../src" import { render } from "@testing-library/react" import { MobXProviderContext } from "../src/Provider" import { withConsole } from "./utils/withConsole" describe("Provider", () => { it("should work in a simple case", () => { function A() { return ( <Provider foo="bar"> <MobXProviderContext.Consumer>{({ foo }) => foo}</MobXProviderContext.Consumer> </Provider> ) } const { container } = render(<A />) expect(container).toHaveTextContent("bar") }) it("should not provide the children prop", () => { function A() { return ( <Provider> <MobXProviderContext.Consumer> {stores => Reflect.has(stores, "children") ? "children was provided" : "children was not provided" } </MobXProviderContext.Consumer> </Provider> ) } const { container } = render(<A />) expect(container).toHaveTextContent("children was not provided") }) it("supports overriding stores", () => { function B() { return ( <MobXProviderContext.Consumer> {({ overridable, nonOverridable }) => `${overridable} ${nonOverridable}`} </MobXProviderContext.Consumer> ) } function A() { return ( <Provider overridable="original" nonOverridable="original"> <B /> <Provider overridable="overridden"> <B /> </Provider> </Provider> ) } const { container } = render(<A />) expect(container).toMatchInlineSnapshot(` <div> original original overridden original </div> `) }) it("should throw an error when changing stores", () => { function A({ foo }) { return ( <Provider foo={foo}> <MobXProviderContext.Consumer>{({ foo }) => foo}</MobXProviderContext.Consumer> </Provider> ) } const { rerender } = render(<A foo={1} />) withConsole(() => { expect(() => { rerender(<A foo={2} />) }).toThrow("The set of provided stores has changed.") }) }) })
4,853
0
petrpan-code/mobxjs/mobx/packages/mobx-react
petrpan-code/mobxjs/mobx/packages/mobx-react/__tests__/context.test.tsx
import React from "react" import { observable } from "mobx" import { Provider, observer, inject } from "../src" import { withConsole } from "./utils/withConsole" import { render, act } from "@testing-library/react" import { any } from "prop-types" test("no warnings in modern react", () => { const box = observable.box(3) const Child = inject("store")( observer( class Child extends React.Component<any, any> { render() { return ( <div> {this.props.store} + {box.get()} </div> ) } } ) ) class App extends React.Component { render() { return ( <div> <React.StrictMode> <Provider store="42"> <Child /> </Provider> </React.StrictMode> </div> ) } } const { container } = render(<App />) expect(container).toHaveTextContent("42 + 3") withConsole(["info", "warn", "error"], () => { act(() => { box.set(4) }) expect(container).toHaveTextContent("42 + 4") expect(console.info).not.toHaveBeenCalled() expect(console.warn).not.toHaveBeenCalled() expect(console.error).not.toHaveBeenCalled() }) }) test("getDerivedStateFromProps works #447", () => { class Main extends React.Component<any, any> { static getDerivedStateFromProps(nextProps, prevState) { return { count: prevState.count + 1 } } state = { count: 0 } render() { return ( <div> <h2>{`${this.state.count ? "One " : "No "}${this.props.thing}`}</h2> </div> ) } } const MainInjected = inject(({ store }: { store: { thing: number } }) => ({ thing: store.thing }))(Main) const store = { thing: 3 } const App = () => ( <Provider store={store}> <MainInjected /> </Provider> ) const { container } = render(<App />) expect(container).toHaveTextContent("One 3") }) test("no double runs for getDerivedStateFromProps", () => { let derived = 0 @observer class Main extends React.Component<any, any> { state = { activePropertyElementMap: {} } constructor(props) { // console.log("CONSTRUCTOR") super(props) } static getDerivedStateFromProps() { derived++ // console.log("PREVSTATE", nextProps) return null } render() { return <div>Test-content</div> } } // This results in //PREVSTATE //CONSTRUCTOR //PREVSTATE let MainInjected = inject(() => ({ componentProp: "def" }))(Main) // Uncomment the following line to see default behaviour (without inject) //CONSTRUCTOR //PREVSTATE //MainInjected = Main; const store = {} const App = () => ( <Provider store={store}> <MainInjected injectedProp={"abc"} /> </Provider> ) const { container } = render(<App />) expect(container).toHaveTextContent("Test-content") expect(derived).toBe(1) })
4,854
0
petrpan-code/mobxjs/mobx/packages/mobx-react
petrpan-code/mobxjs/mobx/packages/mobx-react/__tests__/disposeOnUnmount.test.tsx
import React from "react" import { disposeOnUnmount, observer } from "../src" import { render } from "@testing-library/react" import { MockedComponentClass } from "react-dom/test-utils" interface ClassC extends MockedComponentClass { methodA?: any methodB?: any methodC?: any methodD?: any } function testComponent(C: ClassC, afterMount?: Function, afterUnmount?: Function) { const ref = React.createRef<ClassC>() const { unmount } = render(<C ref={ref} />) let cref = ref.current expect(cref?.methodA).not.toHaveBeenCalled() expect(cref?.methodB).not.toHaveBeenCalled() if (afterMount) { afterMount(cref) } unmount() expect(cref?.methodA).toHaveBeenCalledTimes(1) expect(cref?.methodB).toHaveBeenCalledTimes(1) if (afterUnmount) { afterUnmount(cref) } } describe("without observer", () => { test("class without componentWillUnmount", async () => { class C extends React.Component { @disposeOnUnmount methodA = jest.fn() @disposeOnUnmount methodB = jest.fn() @disposeOnUnmount methodC = null @disposeOnUnmount methodD = undefined render() { return null } } testComponent(C) }) test("class with componentWillUnmount in the prototype", () => { let called = 0 class C extends React.Component { @disposeOnUnmount methodA = jest.fn() @disposeOnUnmount methodB = jest.fn() @disposeOnUnmount methodC = null @disposeOnUnmount methodD = undefined render() { return null } componentWillUnmount() { called++ } } testComponent( C, () => { expect(called).toBe(0) }, () => { expect(called).toBe(1) } ) }) test.skip("class with componentWillUnmount as an arrow function", () => { let called = 0 class C extends React.Component { @disposeOnUnmount methodA = jest.fn() @disposeOnUnmount methodB = jest.fn() @disposeOnUnmount methodC = null @disposeOnUnmount methodD = undefined render() { return null } componentWillUnmount = () => { called++ } } testComponent( C, () => { expect(called).toBe(0) }, () => { expect(called).toBe(1) } ) }) test("class without componentWillUnmount using non decorator version", () => { let methodC = jest.fn() let methodD = jest.fn() class C extends React.Component { render() { return null } methodA = disposeOnUnmount(this, jest.fn()) methodB = disposeOnUnmount(this, jest.fn()) constructor(props) { super(props) disposeOnUnmount(this, [methodC, methodD]) } } testComponent( C, () => { expect(methodC).not.toHaveBeenCalled() expect(methodD).not.toHaveBeenCalled() }, () => { expect(methodC).toHaveBeenCalledTimes(1) expect(methodD).toHaveBeenCalledTimes(1) } ) }) }) describe("with observer", () => { test("class without componentWillUnmount", () => { @observer class C extends React.Component { @disposeOnUnmount methodA = jest.fn() @disposeOnUnmount methodB = jest.fn() @disposeOnUnmount methodC = null @disposeOnUnmount methodD = undefined render() { return null } } testComponent(C) }) test("class with componentWillUnmount in the prototype", () => { let called = 0 @observer class C extends React.Component { @disposeOnUnmount methodA = jest.fn() @disposeOnUnmount methodB = jest.fn() @disposeOnUnmount methodC = null @disposeOnUnmount methodD = undefined render() { return null } componentWillUnmount() { called++ } } testComponent( C, () => { expect(called).toBe(0) }, () => { expect(called).toBe(1) } ) }) test.skip("class with componentWillUnmount as an arrow function", () => { let called = 0 @observer class C extends React.Component { @disposeOnUnmount methodA = jest.fn() @disposeOnUnmount methodB = jest.fn() @disposeOnUnmount methodC = null @disposeOnUnmount methodD = undefined render() { return null } componentWillUnmount = () => { called++ } } testComponent( C, () => { expect(called).toBe(0) }, () => { expect(called).toBe(1) } ) }) test("class without componentWillUnmount using non decorator version", () => { let methodC = jest.fn() let methodD = jest.fn() @observer class C extends React.Component { render() { return null } methodA = disposeOnUnmount(this, jest.fn()) methodB = disposeOnUnmount(this, jest.fn()) constructor(props) { super(props) disposeOnUnmount(this, [methodC, methodD]) } } testComponent( C, () => { expect(methodC).not.toHaveBeenCalled() expect(methodD).not.toHaveBeenCalled() }, () => { expect(methodC).toHaveBeenCalledTimes(1) expect(methodD).toHaveBeenCalledTimes(1) } ) }) }) it("componentDidMount should be different between components", () => { function doTest(withObserver) { const events: Array<string> = [] class A extends React.Component { didMount willUnmount componentDidMount() { this.didMount = "A" events.push("mountA") } componentWillUnmount() { this.willUnmount = "A" events.push("unmountA") } render() { return null } } class B extends React.Component { didMount willUnmount componentDidMount() { this.didMount = "B" events.push("mountB") } componentWillUnmount() { this.willUnmount = "B" events.push("unmountB") } render() { return null } } if (withObserver) { // @ts-ignore // eslint-disable-next-line no-class-assign A = observer(A) // @ts-ignore // eslint-disable-next-line no-class-assign B = observer(B) } const aRef = React.createRef<A>() const { rerender, unmount } = render(<A ref={aRef} />) const caRef = aRef.current expect(caRef?.didMount).toBe("A") expect(caRef?.willUnmount).toBeUndefined() expect(events).toEqual(["mountA"]) const bRef = React.createRef<B>() rerender(<B ref={bRef} />) const cbRef = bRef.current expect(caRef?.didMount).toBe("A") expect(caRef?.willUnmount).toBe("A") expect(cbRef?.didMount).toBe("B") expect(cbRef?.willUnmount).toBeUndefined() expect(events).toEqual(["mountA", "unmountA", "mountB"]) unmount() expect(caRef?.didMount).toBe("A") expect(caRef?.willUnmount).toBe("A") expect(cbRef?.didMount).toBe("B") expect(cbRef?.willUnmount).toBe("B") expect(events).toEqual(["mountA", "unmountA", "mountB", "unmountB"]) } doTest(true) doTest(false) }) test("base cWU should not be called if overridden", () => { let baseCalled = 0 let dCalled = 0 let oCalled = 0 class C extends React.Component { componentWillUnmount() { baseCalled++ } constructor(props) { super(props) this.componentWillUnmount = () => { oCalled++ } } render() { return null } @disposeOnUnmount fn() { dCalled++ } } const { unmount } = render(<C />) unmount() expect(dCalled).toBe(1) expect(oCalled).toBe(1) expect(baseCalled).toBe(0) }) test("should error on inheritance", () => { class C extends React.Component { render() { return null } } expect(() => { // eslint-disable-next-line no-unused-vars class B extends C { @disposeOnUnmount fn() {} } }).toThrow("disposeOnUnmount only supports direct subclasses") }) test("should error on inheritance - 2", () => { class C extends React.Component { render() { return null } } class B extends C { fn constructor(props) { super(props) expect(() => { this.fn = disposeOnUnmount(this, function () {}) }).toThrow("disposeOnUnmount only supports direct subclasses") } } render(<B />) }) describe("should work with arrays", () => { test("as a function", () => { class C extends React.Component { methodA = jest.fn() methodB = jest.fn() componentDidMount() { disposeOnUnmount(this, [this.methodA, this.methodB]) } render() { return null } } testComponent(C) }) test("as a decorator", () => { class C extends React.Component { methodA = jest.fn() methodB = jest.fn() @disposeOnUnmount disposers = [this.methodA, this.methodB] render() { return null } } testComponent(C) }) }) it("runDisposersOnUnmount only runs disposers from the declaring instance", () => { class A extends React.Component { @disposeOnUnmount a = jest.fn() b = jest.fn() constructor(props) { super(props) disposeOnUnmount(this, this.b) } render() { return null } } const ref1 = React.createRef<A>() const ref2 = React.createRef<A>() const { unmount } = render(<A ref={ref1} />) render(<A ref={ref2} />) const inst1 = ref1.current const inst2 = ref2.current unmount() expect(inst1?.a).toHaveBeenCalledTimes(1) expect(inst1?.b).toHaveBeenCalledTimes(1) expect(inst2?.a).toHaveBeenCalledTimes(0) expect(inst2?.b).toHaveBeenCalledTimes(0) })
4,856
0
petrpan-code/mobxjs/mobx/packages/mobx-react
petrpan-code/mobxjs/mobx/packages/mobx-react/__tests__/hooks.test.tsx
import React from "react" import { observer, Observer, useLocalStore, useAsObservableSource } from "../src" import { render, act } from "@testing-library/react" afterEach(() => { jest.useRealTimers() }) let consoleWarnMock: jest.SpyInstance | undefined afterEach(() => { consoleWarnMock?.mockRestore() }) test("computed properties react to props when using hooks", async () => { jest.useFakeTimers() consoleWarnMock = jest.spyOn(console, "warn").mockImplementation(() => {}) const seen: Array<string> = [] const Child = ({ x }) => { const props = useAsObservableSource({ x }) const store = useLocalStore(() => ({ get getPropX() { return props.x } })) return ( <Observer>{() => (seen.push(store.getPropX), (<div>{store.getPropX}</div>))}</Observer> ) } const Parent = () => { const [state, setState] = React.useState({ x: 0 }) seen.push("parent") React.useEffect(() => { setTimeout(() => { act(() => { setState({ x: 2 }) }) }) }, []) return <Child x={state.x} /> } const { container } = render(<Parent />) expect(container).toHaveTextContent("0") act(() => { jest.runAllTimers() }) expect(seen).toEqual(["parent", 0, "parent", 2]) expect(container).toHaveTextContent("2") expect(consoleWarnMock).toMatchSnapshot() }) test("computed properties result in double render when using observer instead of Observer", async () => { jest.useFakeTimers() const seen: Array<string> = [] const Child = observer(({ x }) => { const props = useAsObservableSource({ x }) const store = useLocalStore(() => ({ get getPropX() { return props.x } })) seen.push(store.getPropX) return <div>{store.getPropX}</div> }) const Parent = () => { const [state, setState] = React.useState({ x: 0 }) seen.push("parent") React.useEffect(() => { setTimeout(() => { act(() => { setState({ x: 2 }) }) }, 100) }, []) return <Child x={state.x} /> } const { container } = render(<Parent />) expect(container).toHaveTextContent("0") act(() => { jest.runAllTimers() }) expect(seen).toEqual([ "parent", 0, "parent", 2, // props changed 2 // observable source changed (setState during render) ]) expect(container).toHaveTextContent("2") })
4,857
0
petrpan-code/mobxjs/mobx/packages/mobx-react
petrpan-code/mobxjs/mobx/packages/mobx-react/__tests__/inject.test.tsx
import React from "react" import PropTypes from "prop-types" import { action, observable, makeObservable } from "mobx" import { observer, inject, Provider } from "../src" import { IValueMap } from "../src/types/IValueMap" import { render, act } from "@testing-library/react" import { withConsole } from "./utils/withConsole" import { IReactComponent } from "../src/types/IReactComponent" describe("inject based context", () => { test("basic context", () => { const C = inject("foo")( observer( class X extends React.Component<any, any> { render() { return ( <div> context: {this.props.foo} </div> ) } } ) ) const B = () => <C /> const A = () => ( <Provider foo="bar"> <B /> </Provider> ) const { container } = render(<A />) expect(container).toHaveTextContent("context:bar") }) test("props override context", () => { const C = inject("foo")( class T extends React.Component<any, any> { render() { return ( <div> context: {this.props.foo} </div> ) } } ) const B = () => <C foo={42} /> const A = class T extends React.Component<any, any> { render() { return ( <Provider foo="bar"> <B /> </Provider> ) } } const { container } = render(<A />) expect(container).toHaveTextContent("context:42") }) test("wraps displayName of original component", () => { const A: React.ComponentClass = inject("foo")( class ComponentA extends React.Component<any, any> { render() { return ( <div> context: {this.props.foo} </div> ) } } ) const B: React.ComponentClass = inject()( class ComponentB extends React.Component<any, any> { render() { return ( <div> context: {this.props.foo} </div> ) } } ) const C: React.ComponentClass = inject(() => ({}))( class ComponentC extends React.Component<any, any> { render() { return ( <div> context: {this.props.foo} </div> ) } } ) expect(A.displayName).toBe("inject-with-foo(ComponentA)") expect(B.displayName).toBe("inject(ComponentB)") expect(C.displayName).toBe("inject(ComponentC)") }) test("shouldn't change original displayName of component that uses forwardRef", () => { const FancyComp = React.forwardRef((_: any, ref: React.Ref<HTMLDivElement>) => { return <div ref={ref} /> }) FancyComp.displayName = "FancyComp" inject("bla")(FancyComp) expect(FancyComp.displayName).toBe("FancyComp") }) // FIXME: see other comments related to error catching in React // test does work as expected when running manually test("store should be available", () => { const C = inject("foo")( observer( class C extends React.Component<any, any> { render() { return ( <div> context: {this.props.foo} </div> ) } } ) ) const B = () => <C /> const A = class A extends React.Component<any, any> { render() { return ( <Provider baz={42}> <B /> </Provider> ) } } withConsole(() => { expect(() => render(<A />)).toThrow( /Store 'foo' is not available! Make sure it is provided by some Provider/ ) }) }) test("store is not required if prop is available", () => { const C = inject("foo")( observer( class C extends React.Component<any, any> { render() { return ( <div> context: {this.props.foo} </div> ) } } ) ) const B = () => <C foo="bar" /> const { container } = render(<B />) expect(container).toHaveTextContent("context:bar") }) test("inject merges (and overrides) props", () => { const C = inject(() => ({ a: 1 }))( observer( class C extends React.Component<any, any> { render() { expect(this.props).toEqual({ a: 1, b: 2 }) return null } } ) ) const B = () => <C a={2} b={2} /> render(<B />) }) test("custom storesToProps", () => { const C = inject((stores: IValueMap, props: any) => { expect(stores).toEqual({ foo: "bar" }) expect(props).toEqual({ baz: 42 }) return { zoom: stores.foo, baz: props.baz * 2 } })( observer( class C extends React.Component<any, any> { render() { return ( <div> context: {this.props.zoom} {this.props.baz} </div> ) } } ) ) const B = class B extends React.Component<any, any> { render() { return <C baz={42} /> } } const A = () => ( <Provider foo="bar"> <B /> </Provider> ) const { container } = render(<A />) expect(container).toHaveTextContent("context:bar84") }) test("inject forwards ref", () => { class FancyComp extends React.Component<any, any> { didRender render() { this.didRender = true return null } doSomething() {} } const ref = React.createRef<FancyComp>() render(<FancyComp ref={ref} />) expect(typeof ref.current?.doSomething).toBe("function") expect(ref.current?.didRender).toBe(true) const InjectedFancyComp = inject("bla")(FancyComp) const ref2 = React.createRef<FancyComp>() render( <Provider bla={42}> <InjectedFancyComp ref={ref2} /> </Provider> ) expect(typeof ref2.current?.doSomething).toBe("function") expect(ref2.current?.didRender).toBe(true) }) test("inject should work with components that use forwardRef", () => { const FancyComp = React.forwardRef((_: any, ref: React.Ref<HTMLDivElement>) => { return <div ref={ref} /> }) const InjectedFancyComp = inject("bla")(FancyComp) const ref = React.createRef<HTMLDivElement>() render( <Provider bla={42}> <InjectedFancyComp ref={ref} /> </Provider> ) expect(ref.current).not.toBeNull() expect(ref.current).toBeInstanceOf(HTMLDivElement) }) test("support static hoisting, wrappedComponent and ref forwarding", () => { class B extends React.Component<any, any> { static foo static bar testField render() { this.testField = 1 return null } } ;(B as React.ComponentClass).propTypes = { x: PropTypes.object } B.foo = 17 B.bar = {} const C = inject("booh")(B) expect(C.wrappedComponent).toBe(B) expect(B.foo).toBe(17) expect(C.foo).toBe(17) expect(C.bar === B.bar).toBeTruthy() expect(Object.keys(C.wrappedComponent.propTypes!)).toEqual(["x"]) const ref = React.createRef<B>() render(<C booh={42} ref={ref} />) expect(ref.current?.testField).toBe(1) }) test("propTypes and defaultProps are forwarded", () => { const msg: Array<string> = [] const baseError = console.error console.error = m => msg.push(m) const C: React.ComponentClass<any> = inject("foo")( class C extends React.Component<any, any> { render() { expect(this.props.y).toEqual(3) expect(this.props.x).toBeUndefined() return null } } ) C.propTypes = { x: PropTypes.func.isRequired, z: PropTypes.string.isRequired } // @ts-ignore C.wrappedComponent.propTypes = { a: PropTypes.func.isRequired } C.defaultProps = { y: 3 } const B = () => <C z="test" /> const A = () => ( <Provider foo="bar"> <B /> </Provider> ) render(<A />) expect(msg.length).toBe(2) // ! Somehow this got broken with upgraded deps and wasn't worth fixing it :) // expect(msg[0].split("\n")[0]).toBe( // "Warning: Failed prop type: The prop `x` is marked as required in `inject-with-foo(C)`, but its value is `undefined`." // ) // expect(msg[1].split("\n")[0]).toBe( // "Warning: Failed prop type: The prop `a` is marked as required in `C`, but its value is `undefined`." // ) console.error = baseError }) test("warning is not printed when attaching propTypes to injected component", () => { let msg = [] const baseWarn = console.warn console.warn = m => (msg = m) const C: React.ComponentClass = inject("foo")( class C extends React.Component<any, any> { render() { return ( <div> context: {this.props.foo} </div> ) } } ) C.propTypes = {} expect(msg.length).toBe(0) console.warn = baseWarn }) test("warning is not printed when attaching propTypes to wrappedComponent", () => { let msg = [] const baseWarn = console.warn console.warn = m => (msg = m) const C = inject("foo")( class C extends React.Component<any, any> { render() { return ( <div> context: {this.props.foo} </div> ) } } ) C.wrappedComponent.propTypes = {} expect(msg.length).toBe(0) console.warn = baseWarn }) test("using a custom injector is reactive", () => { const user = observable({ name: "Noa" }) const mapper = stores => ({ name: stores.user.name }) const DisplayName = props => <h1>{props.name}</h1> const User = inject(mapper)(DisplayName) const App = () => ( <Provider user={user}> <User /> </Provider> ) const { container } = render(<App />) expect(container).toHaveTextContent("Noa") act(() => { user.name = "Veria" }) expect(container).toHaveTextContent("Veria") }) test("using a custom injector is not too reactive", () => { let listRender = 0 let itemRender = 0 let injectRender = 0 function connect() { const args = arguments return (component: IReactComponent) => // @ts-ignore inject.apply(this, args)(observer(component)) } class State { @observable highlighted = null isHighlighted(item) { return this.highlighted == item } @action highlight = item => { this.highlighted = item } constructor() { makeObservable(this) } } const items = observable([ { title: "ItemA" }, { title: "ItemB" }, { title: "ItemC" }, { title: "ItemD" }, { title: "ItemE" }, { title: "ItemF" } ]) const state = new State() class ListComponent extends React.PureComponent<any> { render() { listRender++ const { items } = this.props return ( <ul> {items.map(item => ( <ItemComponent key={item.title} item={item} /> ))} </ul> ) } } // @ts-ignore @connect(({ state }, { item }) => { injectRender++ if (injectRender > 6) { // debugger; } return { // Using // highlighted: expr(() => state.isHighlighted(item)) // seems to fix the problem highlighted: state.isHighlighted(item), highlight: state.highlight } }) class ItemComponent extends React.PureComponent<any> { highlight = () => { const { item, highlight } = this.props highlight(item) } render() { itemRender++ const { highlighted, item } = this.props return ( <li className={"hl_" + item.title} onClick={this.highlight}> {item.title} {highlighted ? "(highlighted)" : ""}{" "} </li> ) } } const { container } = render( <Provider state={state}> <ListComponent items={items} /> </Provider> ) expect(listRender).toBe(1) expect(injectRender).toBe(6) expect(itemRender).toBe(6) act(() => { container .querySelectorAll(".hl_ItemB") .forEach((e: Element) => (e as HTMLElement).click()) }) expect(listRender).toBe(1) expect(injectRender).toBe(12) // ideally, 7 expect(itemRender).toBe(7) act(() => { container .querySelectorAll(".hl_ItemF") .forEach((e: Element) => (e as HTMLElement).click()) }) expect(listRender).toBe(1) expect(injectRender).toBe(18) // ideally, 9 expect(itemRender).toBe(9) }) }) test("#612 - mixed context types", () => { const SomeContext = React.createContext(true) class MainCompClass extends React.Component<any, any> { static contextType = SomeContext render() { let active = this.context return active ? this.props.value : "Inactive" } } const MainComp = inject((stores: any) => ({ value: stores.appState.value }))(MainCompClass) const appState = observable({ value: "Something" }) function App() { return ( <Provider appState={appState}> <SomeContext.Provider value={true}> <MainComp /> </SomeContext.Provider> </Provider> ) } render(<App />) })
4,858
0
petrpan-code/mobxjs/mobx/packages/mobx-react
petrpan-code/mobxjs/mobx/packages/mobx-react/__tests__/issue21.test.tsx
import React, { createElement } from "react" import { computed, isObservable, observable, reaction, transaction, IReactionDisposer, makeObservable } from "mobx" import { observer } from "../src" import _ from "lodash" import { act, render } from "@testing-library/react" let topRenderCount = 0 const wizardModel = observable( { steps: [ { title: "Size", active: true }, { title: "Fabric", active: false }, { title: "Finish", active: false } ], get activeStep() { return _.find(this.steps, "active") }, activateNextStep: function () { const nextStep = this.steps[_.findIndex(this.steps, "active") + 1] if (!nextStep) { return false } this.setActiveStep(nextStep) return true }, setActiveStep(modeToActivate) { const self = this transaction(() => { _.find(self.steps, "active").active = false modeToActivate.active = true }) } } as any, { activateNextStep: observable.ref } ) /** RENDERS **/ const Wizard = observer( class Wizard extends React.Component<any, any> { render() { return createElement( "div", null, <div> <h1>Active Step: </h1> <WizardStep step={this.props.model.activeStep} key="activeMode" tester /> </div>, <div> <h1>All Step: </h1> <p> Clicking on these steps will render the active step just once. This is what I expected. </p> <WizardStep step={this.props.model.steps} key="modeList" /> </div> ) } } ) const WizardStep = observer( class WizardStep extends React.Component<any, any> { renderCount = 0 componentWillUnmount() { // console.log("Unmounting!") } render() { // weird test hack: if (this.props.tester === true) { topRenderCount++ } return createElement( "div", { onClick: this.modeClickHandler }, "RenderCount: " + this.renderCount++ + " " + this.props.step.title + ": isActive:" + this.props.step.active ) } modeClickHandler = () => { var step = this.props.step wizardModel.setActiveStep(step) } } ) /** END RENDERERS **/ const changeStep = stepNumber => act(() => wizardModel.setActiveStep(wizardModel.steps[stepNumber])) test("verify issue 21", () => { render(<Wizard model={wizardModel} />) expect(topRenderCount).toBe(1) changeStep(0) expect(topRenderCount).toBe(2) changeStep(2) expect(topRenderCount).toBe(3) }) test("verify prop changes are picked up", () => { function createItem(subid, label) { const res = observable( { subid, id: 1, label: label, get text() { events.push(["compute", this.subid]) return ( this.id + "." + this.subid + "." + this.label + "." + data.items.indexOf(this as any) ) } }, {}, { proxy: false } ) res.subid = subid // non reactive return res } const data = observable({ items: [createItem(1, "hi")] }) const events: Array<any> = [] const Child = observer( class Child extends React.Component<any, any> { componentDidUpdate(prevProps) { events.push(["update", prevProps.item.subid, this.props.item.subid]) } render() { events.push(["render", this.props.item.subid, this.props.item.text]) return <span>{this.props.item.text}</span> } } ) const Parent = observer( class Parent extends React.Component<any, any> { render() { return ( <div onClick={changeStuff.bind(this)} id="testDiv"> {data.items.map(item => ( <Child key="fixed" item={item} /> ))} </div> ) } } ) const Wrapper = () => <Parent /> function changeStuff() { act(() => { transaction(() => { data.items[0].label = "hello" // schedules state change for Child data.items[0] = createItem(2, "test") // Child should still receive new prop! }) // @ts-ignore this.setState({}) // trigger update }) } const { container } = render(<Wrapper />) expect(events.sort()).toEqual( [ ["compute", 1], ["render", 1, "1.1.hi.0"] ].sort() ) events.splice(0) let testDiv = container.querySelector("#testDiv")! as HTMLElement testDiv.click() expect(events.sort()).toEqual( [ ["compute", 1], ["update", 1, 2], ["compute", 2], ["render", 2, "1.2.test.0"] ].sort() ) expect(container.textContent).toMatchInlineSnapshot(`"1.2.test.0"`) }) test("no re-render for shallow equal props", async () => { function createItem(subid, label) { const res = observable({ subid, id: 1, label: label }) res.subid = subid // non reactive return res } const data = observable({ items: [createItem(1, "hi")], parentValue: 0 }) const events: Array<Array<any>> = [] const Child = observer( class Child extends React.Component<any, any> { componentDidMount() { events.push(["mount"]) } componentDidUpdate(prevProps) { events.push(["update", prevProps.item.subid, this.props.item.subid]) } render() { events.push(["render", this.props.item.subid, this.props.item.label]) return <span>{this.props.item.label}</span> } } ) const Parent = observer( class Parent extends React.Component<any, any> { render() { // "object has become observable!" expect(isObservable(this.props.nonObservable)).toBeFalsy() events.push(["parent render", data.parentValue]) return ( <div onClick={changeStuff.bind(this)} id="testDiv"> {data.items.map(item => ( <Child key="fixed" item={item} value={5} /> ))} </div> ) } } ) const Wrapper = () => <Parent nonObservable={{}} /> function changeStuff() { act(() => { data.items[0].label = "hi" // no change. data.parentValue = 1 // rerender parent }) } const { container } = render(<Wrapper />) expect(events.sort()).toEqual([["parent render", 0], ["mount"], ["render", 1, "hi"]].sort()) events.splice(0) let testDiv = container.querySelector("#testDiv") as HTMLElement testDiv.click() expect(events.sort()).toEqual([["parent render", 1]].sort()) }) test("lifecycle callbacks called with correct arguments", () => { var Comp = observer( class Comp extends React.Component<any, any> { componentDidUpdate(prevProps) { expect(prevProps.counter).toBe(0) expect(this.props.counter).toBe(1) } render() { return ( <div> <span key="1">{[this.props.counter]}</span> <button key="2" id="testButton" onClick={this.props.onClick} /> </div> ) } } ) const Root = class T extends React.Component<any, any> { state = { counter: 0 } onButtonClick = () => { act(() => this.setState({ counter: (this.state.counter || 0) + 1 })) } render() { return <Comp counter={this.state.counter || 0} onClick={this.onButtonClick} /> } } const { container } = render(<Root />) let testButton = container.querySelector("#testButton") as HTMLElement testButton.click() })
4,859
0
petrpan-code/mobxjs/mobx/packages/mobx-react
petrpan-code/mobxjs/mobx/packages/mobx-react/__tests__/issue806.test.tsx
import React from "react" import { configure, observable } from "mobx" import { observer } from "../src" import { render } from "@testing-library/react" import { withConsole } from "./utils/withConsole" @observer class Issue806Component extends React.Component<any> { render() { return ( <span> {this.props.a} <Issue806Component2 propA={this.props.a} propB={this.props.b} /> </span> ) } } @observer class Issue806Component2 extends React.Component<any> { render() { return ( <span> {this.props.propA} - {this.props.propB} </span> ) } } test("verify issue 806", () => { configure({ observableRequiresReaction: true }) const x = observable({ a: 1 }) withConsole(["warn"], () => { render(<Issue806Component a={"a prop value"} b={"b prop value"} x={x} />) expect(console.warn).not.toHaveBeenCalled() }) // make sure observableRequiresReaction is still working outside component withConsole(["warn"], () => { x.a.toString() expect(console.warn).toBeCalledTimes(1) expect(console.warn).toHaveBeenCalledWith( "[mobx] Observable '[email protected]' being read outside a reactive context." ) }) })
4,860
0
petrpan-code/mobxjs/mobx/packages/mobx-react
petrpan-code/mobxjs/mobx/packages/mobx-react/__tests__/misc.test.tsx
import React from "react" import { extendObservable, observable } from "mobx" import { observer } from "../src" import { act, render } from "@testing-library/react" test("issue mobx 405", () => { function ExampleState() { // @ts-ignore extendObservable(this, { name: "test", get greetings() { return "Hello my name is " + this.name } }) } const ExampleView = observer( class T extends React.Component<any, any> { render() { return ( <div> <input type="text" onChange={e => (this.props.exampleState.name = e.target.value)} value={this.props.exampleState.name} /> <span>{this.props.exampleState.greetings}</span> </div> ) } } ) const exampleState = new ExampleState() const { container } = render(<ExampleView exampleState={exampleState} />) expect(container).toMatchInlineSnapshot(` <div> <div> <input type="text" value="test" /> <span> Hello my name is test </span> </div> </div> `) }) test("#85 Should handle state changing in constructors", () => { const a = observable.box(2) const Child = observer( class Child extends React.Component { constructor(p) { super(p) a.set(3) // one shouldn't do this! this.state = {} } render() { return ( <div> child: {a.get()} -{" "} </div> ) } } ) const ParentWrapper = observer(function Parent() { return ( <span> <Child /> parent: {a.get()} </span> ) }) const { container } = render(<ParentWrapper />) expect(container).toHaveTextContent("child:3 - parent:3") act(() => a.set(5)) expect(container).toHaveTextContent("child:5 - parent:5") act(() => a.set(7)) expect(container).toHaveTextContent("child:7 - parent:7") })
4,861
0
petrpan-code/mobxjs/mobx/packages/mobx-react
petrpan-code/mobxjs/mobx/packages/mobx-react/__tests__/observer.test.tsx
import React, { StrictMode, Suspense } from "react" import { inject, observer, Observer, enableStaticRendering } from "../src" import { render, act, waitFor } from "@testing-library/react" import { getObserverTree, _getGlobalState, _resetGlobalState, action, computed, observable, transaction, makeObservable, autorun, IReactionDisposer, reaction, configure } from "mobx" import { withConsole } from "./utils/withConsole" import { shallowEqual } from "../src/utils/utils" /** * some test suite is too tedious */ afterEach(() => { jest.useRealTimers() }) let consoleWarnMock: jest.SpyInstance | undefined afterEach(() => { consoleWarnMock?.mockRestore() }) /* use TestUtils.renderIntoDocument will re-mounted the component with different props some misunderstanding will be cause? */ describe("nestedRendering", () => { let store let todoItemRenderings const TodoItem = observer(function TodoItem(props) { todoItemRenderings++ return <li>|{props.todo.title}</li> }) let todoListRenderings const TodoList = observer( class TodoList extends React.Component { render() { todoListRenderings++ const todos = store.todos return ( <div> <span>{todos.length}</span> {todos.map((todo, idx) => ( <TodoItem key={idx} todo={todo} /> ))} </div> ) } } ) beforeEach(() => { todoItemRenderings = 0 todoListRenderings = 0 store = observable({ todos: [ { title: "a", completed: false } ] }) }) test("first rendering", () => { const { container } = render(<TodoList />) expect(todoListRenderings).toBe(1) expect(container.querySelectorAll("li").length).toBe(1) expect(container.querySelector("li")).toHaveTextContent("|a") expect(todoItemRenderings).toBe(1) }) test("second rendering with inner store changed", () => { render(<TodoList />) act(() => { store.todos[0].title += "a" }) expect(todoListRenderings).toBe(1) expect(todoItemRenderings).toBe(2) expect(getObserverTree(store, "todos").observers!.length).toBe(1) expect(getObserverTree(store.todos[0], "title").observers!.length).toBe(1) }) test("rerendering with outer store added", () => { const { container } = render(<TodoList />) act(() => { store.todos.push({ title: "b", completed: true }) }) expect(container.querySelectorAll("li").length).toBe(2) expect( Array.from(container.querySelectorAll("li")) .map((e: any) => e.innerHTML) .sort() ).toEqual(["|a", "|b"].sort()) expect(todoListRenderings).toBe(2) expect(todoItemRenderings).toBe(2) expect(getObserverTree(store.todos[1], "title").observers!.length).toBe(1) expect(getObserverTree(store.todos[1], "completed").observers).toBe(undefined) }) test("rerendering with outer store pop", () => { const { container } = render(<TodoList />) let oldTodo act(() => (oldTodo = store.todos.pop())) expect(todoListRenderings).toBe(2) expect(todoItemRenderings).toBe(1) expect(container.querySelectorAll("li").length).toBe(0) expect(getObserverTree(oldTodo, "title").observers).toBe(undefined) expect(getObserverTree(oldTodo, "completed").observers).toBe(undefined) }) }) describe("isObjectShallowModified detects when React will update the component", () => { const store = observable({ count: 0 }) let counterRenderings = 0 const Counter: React.FunctionComponent<any> = observer(function TodoItem() { counterRenderings++ return <div>{store.count}</div> }) test("does not assume React will update due to NaN prop", () => { render(<Counter value={NaN} />) act(() => { store.count++ }) expect(counterRenderings).toBe(2) }) }) describe("keep views alive", () => { let yCalcCount let data const TestComponent = observer(function testComponent() { return ( <div> {data.z} {data.y} </div> ) }) beforeEach(() => { yCalcCount = 0 data = observable({ x: 3, get y() { yCalcCount++ return this.x * 2 }, z: "hi" }) }) test("init state", () => { const { container } = render(<TestComponent />) expect(yCalcCount).toBe(1) expect(container).toHaveTextContent("hi6") }) test("rerender should not need a recomputation of data.y", () => { const { container } = render(<TestComponent />) act(() => { data.z = "hello" }) expect(yCalcCount).toBe(1) expect(container).toHaveTextContent("hello6") }) }) describe("does not views alive when using static rendering", () => { let renderCount let data const TestComponent = observer(function testComponent() { renderCount++ return <div>{data.z}</div> }) beforeAll(() => { enableStaticRendering(true) }) beforeEach(() => { renderCount = 0 data = observable({ z: "hi" }) }) afterAll(() => { enableStaticRendering(false) }) test("init state is correct", () => { const { container } = render(<TestComponent />) expect(renderCount).toBe(1) expect(container).toHaveTextContent("hi") }) test("no re-rendering on static rendering", () => { const { container } = render(<TestComponent />) act(() => { data.z = "hello" }) expect(getObserverTree(data, "z").observers).toBe(undefined) expect(renderCount).toBe(1) expect(container).toHaveTextContent("hi") }) }) test("issue 12", () => { const events: Array<any> = [] const data = observable({ selected: "coffee", items: [ { name: "coffee" }, { name: "tea" } ] }) /** Row Class */ class Row extends React.Component<any, any> { constructor(props) { super(props) } render() { events.push("row: " + this.props.item.name) return ( <span> {this.props.item.name} {data.selected === this.props.item.name ? "!" : ""} </span> ) } } /** table stateles component */ const Table = observer(function table() { events.push("table") JSON.stringify(data) return ( <div> {data.items.map(item => ( <Row key={item.name} item={item} /> ))} </div> ) }) const { container } = render(<Table />) expect(container).toMatchSnapshot() act(() => { transaction(() => { data.items[1].name = "boe" data.items.splice(0, 2, { name: "soup" }) data.selected = "tea" }) }) expect(container).toMatchSnapshot() expect(events).toEqual(["table", "row: coffee", "row: tea", "table", "row: soup"]) }) test("changing state in render should fail", () => { const data = observable.box(2) const Comp = observer(() => { if (data.get() === 3) { try { data.set(4) // wouldn't throw first time for lack of observers.. (could we tighten this?) } catch (err) { expect(err).toBeInstanceOf(Error) expect(err).toMatch( /Side effects like changing state are not allowed at this point/ ) } } return <div>{data.get()}</div> }) render(<Comp />) act(() => data.set(3)) _resetGlobalState() }) test("observer component can be injected", () => { const msg: Array<any> = [] const baseWarn = console.warn console.warn = m => msg.push(m) inject("foo")( observer( class T extends React.Component { render() { return null } } ) ) // N.B, the injected component will be observer since mobx-react 4.0! inject(() => ({}))( observer( class T extends React.Component { render() { return null } } ) ) expect(msg.length).toBe(0) console.warn = baseWarn }) test("correctly wraps display name of child component", () => { const A = observer( class ObserverClass extends React.Component { render() { return null } } ) const B: React.FunctionComponent<any> = observer(function StatelessObserver() { return null }) expect(A.name).toEqual("ObserverClass") expect((B as any).type.name).toEqual("StatelessObserver") expect((B as any).type.displayName).toEqual(undefined) }) describe("124 - react to changes in this.props via computed", () => { class T extends React.Component<any, any> { @computed get computedProp() { return this.props.x } render() { return ( <span> x: {this.computedProp} </span> ) } } const Comp = observer(T) class Parent extends React.Component { state = { v: 1 } render() { return ( <div onClick={() => this.setState({ v: 2 })}> <Comp x={this.state.v} /> </div> ) } } test("init state is correct", () => { const { container } = render(<Parent />) expect(container).toHaveTextContent("x:1") }) test("change after click", () => { const { container } = render(<Parent />) act(() => container.querySelector("div")!.click()) expect(container).toHaveTextContent("x:2") }) }) // Test on skip: since all reactions are now run in batched updates, the original issues can no longer be reproduced //this test case should be deprecated? test("should stop updating if error was thrown in render (#134)", () => { const data = observable.box(0) let renderingsCount = 0 let lastOwnRenderCount = 0 const errors: Array<any> = [] class Outer extends React.Component<any> { state = { hasError: false } render() { return this.state.hasError ? <div>Error!</div> : <div>{this.props.children}</div> } static getDerivedStateFromError() { return { hasError: true } } componentDidCatch(error, info) { errors.push(error.toString().split("\n")[0], info) } } const Comp = observer( class X extends React.Component { ownRenderCount = 0 render() { lastOwnRenderCount = ++this.ownRenderCount renderingsCount++ if (data.get() === 2) { throw new Error("Hello") } return <div /> } } ) render( <Outer> <Comp /> </Outer> ) // Check this // @ts-ignore expect(getObserverTree(data).observers!.length).toBe(1) act(() => data.set(1)) expect(renderingsCount).toBe(2) expect(lastOwnRenderCount).toBe(2) withConsole(() => { act(() => data.set(2)) }) // @ts-ignore expect(getObserverTree(data).observers).toBe(undefined) act(() => { data.set(3) data.set(4) data.set(2) data.set(5) }) // MWE: not sure if these numbers make sense. Nor whether it really matters expect(lastOwnRenderCount).toBe(6) expect(renderingsCount).toBe(6) }) describe("should render component even if setState called with exactly the same props", () => { let renderCount const Comp = observer( class T extends React.Component { onClick = () => { this.setState({}) } render() { renderCount++ return <div onClick={this.onClick} id="clickableDiv" /> } } ) beforeEach(() => { renderCount = 0 }) test("renderCount === 1", () => { render(<Comp />) expect(renderCount).toBe(1) }) test("after click once renderCount === 2", () => { const { container } = render(<Comp />) const clickableDiv = container.querySelector("#clickableDiv") as HTMLElement act(() => clickableDiv.click()) expect(renderCount).toBe(2) }) test("after click twice renderCount === 3", () => { const { container } = render(<Comp />) const clickableDiv = container.querySelector("#clickableDiv") as HTMLElement act(() => clickableDiv.click()) act(() => clickableDiv.click()) expect(renderCount).toBe(3) }) }) test("it rerenders correctly if some props are non-observables - 1", () => { let odata = observable({ x: 1 }) let data = { y: 1 } @observer class Comp extends React.Component<any, any> { @computed get computed() { // n.b: data.y would not rerender! shallowly new equal props are not stored return this.props.odata.x } render() { return ( <span onClick={stuff}> {this.props.odata.x}-{this.props.data.y}-{this.computed} </span> ) } } const Parent = observer( class Parent extends React.Component<any, any> { render() { // this.props.odata.x; return <Comp data={this.props.data} odata={this.props.odata} /> } } ) function stuff() { act(() => { data.y++ odata.x++ }) } const { container } = render(<Parent odata={odata} data={data} />) expect(container).toHaveTextContent("1-1-1") stuff() expect(container).toHaveTextContent("2-2-2") stuff() expect(container).toHaveTextContent("3-3-3") }) test("it rerenders correctly if some props are non-observables - 2", () => { let renderCount = 0 let odata = observable({ x: 1 }) @observer class Component extends React.PureComponent<any, any> { @computed get computed() { return this.props.data.y // should recompute, since props.data is changed } render() { renderCount++ return ( <span onClick={stuff}> {this.props.data.y}-{this.computed} </span> ) } } const Parent = observer(props => { let data = { y: props.odata.x } return <Component data={data} odata={props.odata} /> }) function stuff() { odata.x++ } const { container } = render(<Parent odata={odata} />) expect(renderCount).toBe(1) expect(container).toHaveTextContent("1-1") act(() => stuff()) expect(renderCount).toBe(2) expect(container).toHaveTextContent("2-2") act(() => stuff()) expect(renderCount).toBe(3) expect(container).toHaveTextContent("3-3") }) describe("Observer regions should react", () => { let data const Comp = () => ( <div> <Observer>{() => <span data-testid="inside-of-observer">{data.get()}</span>}</Observer> <span data-testid="outside-of-observer">{data.get()}</span> </div> ) beforeEach(() => { data = observable.box("hi") }) test("init state is correct", () => { const { queryByTestId } = render(<Comp />) expect(queryByTestId("inside-of-observer")).toHaveTextContent("hi") expect(queryByTestId("outside-of-observer")).toHaveTextContent("hi") }) test("set the data to hello", () => { const { queryByTestId } = render(<Comp />) act(() => data.set("hello")) expect(queryByTestId("inside-of-observer")).toHaveTextContent("hello") expect(queryByTestId("outside-of-observer")).toHaveTextContent("hi") }) }) test("Observer should not re-render on shallow equal new props", () => { let childRendering = 0 let parentRendering = 0 const data = { x: 1 } const odata = observable({ y: 1 }) const Child = observer(({ data }) => { childRendering++ return <span>{data.x}</span> }) const Parent = observer(() => { parentRendering++ odata.y /// depend return <Child data={data} /> }) const { container } = render(<Parent />) expect(parentRendering).toBe(1) expect(childRendering).toBe(1) expect(container).toHaveTextContent("1") act(() => { odata.y++ }) expect(parentRendering).toBe(2) expect(childRendering).toBe(1) expect(container).toHaveTextContent("1") }) test("parent / childs render in the right order", () => { // See: https://jsfiddle.net/gkaemmer/q1kv7hbL/13/ let events: Array<any> = [] class User { @observable name = "User's name" } class Store { @observable user: User | null = new User() @action logout() { this.user = null } constructor() { makeObservable(this) } } function tryLogout() { try { // ReactDOM.unstable_batchedUpdates(() => { store.logout() expect(true).toBeTruthy() // }); } catch (e) { // t.fail(e) } } const store = new Store() const Parent = observer(() => { events.push("parent") if (!store.user) return <span>Not logged in.</span> return ( <div> <Child /> <button onClick={tryLogout}>Logout</button> </div> ) }) const Child = observer(() => { events.push("child") return <span>Logged in as: {store.user?.name}</span> }) render(<Parent />) act(() => tryLogout()) expect(events).toEqual(["parent", "child", "parent"]) }) describe("use Observer inject and render sugar should work ", () => { test("use render without inject should be correct", () => { const Comp = () => ( <div> <Observer render={() => <span>{123}</span>} /> </div> ) const { container } = render(<Comp />) expect(container).toHaveTextContent("123") }) test("use children without inject should be correct", () => { const Comp = () => ( <div> <Observer>{() => <span>{123}</span>}</Observer> </div> ) const { container } = render(<Comp />) expect(container).toHaveTextContent("123") }) test("show error when using children and render at same time ", () => { const msg: Array<any> = [] const baseError = console.error console.error = m => msg.push(m) const Comp = () => ( <div> <Observer render={() => <span>{123}</span>}>{() => <span>{123}</span>}</Observer> </div> ) render(<Comp />) expect(msg.length).toBe(1) console.error = baseError }) }) test("use PureComponent", () => { const msg: Array<any> = [] const baseWarn = console.warn console.warn = m => msg.push(m) try { observer( class X extends React.PureComponent { render() { return <div /> } } ) expect(msg).toEqual([]) } finally { console.warn = baseWarn } }) test("static on function components are hoisted", () => { const Comp = () => <div /> Comp.foo = 3 const Comp2 = observer(Comp) expect(Comp2.foo).toBe(3) }) test("computed properties react to props", () => { jest.useFakeTimers() const seen: Array<any> = [] @observer class Child extends React.Component<any, any> { @computed get getPropX() { return this.props.x } render() { seen.push(this.getPropX) return <div>{this.getPropX}</div> } } class Parent extends React.Component { state = { x: 0 } render() { seen.push("parent") return <Child x={this.state.x} /> } componentDidMount() { setTimeout(() => this.setState({ x: 2 }), 100) } } const { container } = render(<Parent />) expect(container).toHaveTextContent("0") act(() => { jest.runAllTimers() }) expect(container).toHaveTextContent("2") expect(seen).toEqual(["parent", 0, "parent", 2]) }) test("#692 - componentDidUpdate is triggered", () => { jest.useFakeTimers() let cDUCount = 0 @observer class Test extends React.Component<any, any> { @observable counter = 0 @action inc = () => this.counter++ constructor(props) { super(props) makeObservable(this) setTimeout(() => this.inc(), 300) } render() { return <p>{this.counter}</p> } componentDidUpdate() { cDUCount++ } } render(<Test />) expect(cDUCount).toBe(0) act(() => { jest.runAllTimers() }) expect(cDUCount).toBe(1) }) // Not possible to properly test error catching (see ErrorCatcher) test.skip("#709 - applying observer on React.memo component", () => { const WithMemo = React.memo(() => { return null }) const Observed = observer(WithMemo) // @ts-ignore // eslint-disable-next-line no-undef render(<Observed />, { wrapper: ErrorCatcher }) }) test("Redeclaring an existing observer component as an observer should throw", () => { @observer class AlreadyObserver extends React.Component<any, any> { render() { return <div /> } } expect(() => observer(AlreadyObserver)).toThrowErrorMatchingSnapshot() }) test("Missing render should throw", () => { class Component extends React.Component<any, any> { render = function () { return <div /> } } expect(() => observer(Component)).toThrow() }) test("class observer supports re-mounting #3395", () => { const state = observable.box(1) let mountCounter = 0 @observer class TestCmp extends React.Component<any> { componentDidMount() { mountCounter++ } render() { return state.get() } } const app = ( <StrictMode> <TestCmp /> </StrictMode> ) const { unmount, container } = render(app) expect(mountCounter).toBe(2) expect(container).toHaveTextContent("1") act(() => { state.set(2) }) expect(mountCounter).toBe(2) expect(container).toHaveTextContent("2") unmount() }) test("SSR works #3448", () => { consoleWarnMock = jest.spyOn(console, "warn").mockImplementation(() => {}) @observer class TestCmp extends React.Component<any> { render() { return ":)" } } const app = <TestCmp /> enableStaticRendering(true) const { unmount, container } = render(app) expect(container).toHaveTextContent(":)") unmount() enableStaticRendering(false) expect(consoleWarnMock).toMatchSnapshot() }) test("#3492 should not cause warning by calling forceUpdate on uncommited components", async () => { consoleWarnMock = jest.spyOn(console, "warn").mockImplementation(() => {}) const o = observable({ x: 0 }) let aConstructorCount = 0 let aMountCount = 0 let aRenderCount = 0 @observer class A extends React.Component<any> { constructor(props) { super(props) aConstructorCount++ } componentDidMount(): void { aMountCount++ } render() { aRenderCount++ return ( <Suspense fallback="fallback"> <LazyB /> {o.x} </Suspense> ) } } class B extends React.Component { render() { return "B" } } const LazyA = React.lazy(() => Promise.resolve({ default: A })) const LazyB = React.lazy(() => Promise.resolve({ default: B })) function App() { return ( <Suspense fallback="fallback"> <LazyA /> </Suspense> ) } const { unmount, container } = render(<App />) expect(container).toHaveTextContent("fallback") await waitFor(() => expect(container).toHaveTextContent("B0")) act(() => { o.x++ }) expect(container).toHaveTextContent("B1") // React throws away the first instance, therefore the mismatch expect(aConstructorCount).toBe(2) expect(aMountCount).toBe(1) expect(aRenderCount).toBe(3) unmount() expect(consoleWarnMock).toMatchSnapshot() }) ;["props", "state", "context"].forEach(key => { test(`using ${key} in computed throws`, () => { // React prints errors even if we catch em const consoleErrorSpy = jest.spyOn(console, "error").mockImplementation(() => {}) const TestCmp = observer( class TestCmp extends React.Component { render() { computed(() => this[key]).get() return "" } } ) expect(() => render(<TestCmp />)).toThrowError( new RegExp(`^\\[mobx-react\\] Cannot read "TestCmp.${key}" in a reactive context`) ) consoleErrorSpy.mockRestore() }) test(`using ${key} in autorun throws`, () => { // React prints errors even if we catch em const consoleErrorSpy = jest.spyOn(console, "error").mockImplementation(() => {}) let caughtError const TestCmp = observer( class TestCmp extends React.Component { disposeAutorun: IReactionDisposer | undefined componentDidMount(): void { this.disposeAutorun = autorun(() => this[key], { onError: error => (caughtError = error) }) } componentWillUnmount(): void { this.disposeAutorun?.() } render() { return "" } } ) render(<TestCmp />) expect(caughtError?.message).toMatch( new RegExp(`^\\[mobx-react\\] Cannot read "TestCmp.${key}" in a reactive context`) ) consoleErrorSpy.mockRestore() }) }) test(`Component react's to observable changes in componenDidMount #3691`, () => { const o = observable.box(0) const TestCmp = observer( class TestCmp extends React.Component { componentDidMount(): void { o.set(o.get() + 1) } render() { return o.get() } } ) const { container, unmount } = render(<TestCmp />) expect(container).toHaveTextContent("1") unmount() }) test(`Observable changes in componenWillUnmount don't cause any warnings or errors`, () => { const consoleErrorSpy = jest.spyOn(console, "error").mockImplementation(() => {}) const consoleWarnSpy = jest.spyOn(console, "warn").mockImplementation(() => {}) const o = observable.box(0) const TestCmp = observer( class TestCmp extends React.Component { componentWillUnmount(): void { o.set(o.get() + 1) } render() { return o.get() } } ) const { container, unmount } = render(<TestCmp />) expect(container).toHaveTextContent("0") unmount() expect(consoleErrorSpy).not.toBeCalled() expect(consoleWarnSpy).not.toBeCalled() consoleErrorSpy.mockRestore() consoleWarnSpy.mockRestore() }) test(`Observable prop workaround`, () => { configure({ enforceActions: "observed" }) const propValues: Array<any> = [] const TestCmp = observer( class TestCmp extends React.Component<{ prop: number }> { disposeReaction: IReactionDisposer | undefined observableProp: number get computed() { return this.observableProp + 100 } constructor(props) { super(props) // Synchronize our observableProp with the actual prop on the first render. this.observableProp = this.props.prop makeObservable(this, { observableProp: observable, computed: computed, // Mutates observable therefore must be action componentDidUpdate: action }) } componentDidMount(): void { // Reactions/autoruns must be created in componenDidMount (not in constructor). this.disposeReaction = reaction( () => this.observableProp, prop => propValues.push(prop), { fireImmediately: true } ) } componentDidUpdate(): void { // Synchronize our observableProp with the actual prop on every update. this.observableProp = this.props.prop } componentWillUnmount(): void { this.disposeReaction?.() } render() { return this.computed } } ) const { container, unmount, rerender } = render(<TestCmp prop={1} />) expect(container).toHaveTextContent("101") rerender(<TestCmp prop={2} />) expect(container).toHaveTextContent("102") rerender(<TestCmp prop={3} />) expect(container).toHaveTextContent("103") rerender(<TestCmp prop={4} />) expect(container).toHaveTextContent("104") expect(propValues).toEqual([1, 2, 3, 4]) unmount() }) test(`Observable props/state/context workaround`, () => { configure({ enforceActions: "observed" }) const reactionResults: Array<string> = [] const ContextType = React.createContext(0) const TestCmp = observer( class TestCmp extends React.Component<any, any> { static contextType = ContextType disposeReaction: IReactionDisposer | undefined observableProps: any observableState: any observableContext: any constructor(props, context) { super(props, context) this.state = { x: 0 } this.observableState = this.state this.observableProps = this.props this.observableContext = this.context makeObservable(this, { observableProps: observable, observableState: observable, observableContext: observable, computed: computed, componentDidUpdate: action }) } get computed() { return `${this.observableProps?.x}${this.observableState?.x}${this.observableContext}` } componentDidMount(): void { this.disposeReaction = reaction( () => this.computed, prop => reactionResults.push(prop), { fireImmediately: true } ) } componentDidUpdate(): void { // Props are different object with every update if (!shallowEqual(this.observableProps, this.props)) { this.observableProps = this.props } if (!shallowEqual(this.observableState, this.state)) { this.observableState = this.state } if (!shallowEqual(this.observableContext, this.context)) { this.observableContext = this.context } } componentWillUnmount(): void { this.disposeReaction?.() } render() { return ( <span id="updateState" onClick={() => this.setState(state => ({ x: state.x + 1 }))} > {this.computed} </span> ) } } ) const App = () => { const [context, setContext] = React.useState(0) const [prop, setProp] = React.useState(0) return ( <ContextType.Provider value={context}> <span id="updateContext" onClick={() => setContext(val => val + 1)}></span> <span id="updateProp" onClick={() => setProp(val => val + 1)}></span> <TestCmp x={prop}></TestCmp> </ContextType.Provider> ) } const { container, unmount } = render(<App />) const updateProp = () => act(() => (container.querySelector("#updateProp") as HTMLElement).click()) const updateState = () => act(() => (container.querySelector("#updateState") as HTMLElement).click()) const updateContext = () => act(() => (container.querySelector("#updateContext") as HTMLElement).click()) expect(container).toHaveTextContent("000") updateProp() expect(container).toHaveTextContent("100") updateState() expect(container).toHaveTextContent("110") updateContext() expect(container).toHaveTextContent("111") expect(reactionResults).toEqual(["000", "100", "110", "111"]) unmount() }) test("Class observer can react to changes made before mount #3730", () => { const o = observable.box(0) @observer class Child extends React.Component { componentDidMount(): void { o.set(1) } render() { return "" } } @observer class Parent extends React.Component { render() { return ( <span> {o.get()} <Child /> </span> ) } } const { container, unmount } = render(<Parent />) expect(container).toHaveTextContent("1") unmount() })
4,862
0
petrpan-code/mobxjs/mobx/packages/mobx-react
petrpan-code/mobxjs/mobx/packages/mobx-react/__tests__/propTypes.test.ts
import PropTypes from "prop-types" import { PropTypes as MRPropTypes } from "../src" import { observable } from "mobx" // Cause `checkPropTypes` caches errors and doesn't print them twice.... // https://github.com/facebook/prop-types/issues/91 let testComponentId = 0 function typeCheckFail(declaration, value, message) { const baseError = console.error let error = "" console.error = msg => { error = msg } const props = { testProp: value } const propTypes = { testProp: declaration } const compId = "testComponent" + ++testComponentId PropTypes.checkPropTypes(propTypes, props, "prop", compId) error = error.replace(compId, "testComponent") expect(error).toBe("Warning: Failed prop type: " + message) console.error = baseError } function typeCheckFailRequiredValues(declaration) { const baseError = console.error let error = "" console.error = msg => { error = msg } const propTypes = { testProp: declaration } const specifiedButIsNullMsg = /but its value is `null`\./ const unspecifiedMsg = /but its value is `undefined`\./ const props1 = { testProp: null } PropTypes.checkPropTypes(propTypes, props1, "testProp", "testComponent" + ++testComponentId) expect(specifiedButIsNullMsg.test(error)).toBeTruthy() error = "" const props2 = { testProp: undefined } PropTypes.checkPropTypes(propTypes, props2, "testProp", "testComponent" + ++testComponentId) expect(unspecifiedMsg.test(error)).toBeTruthy() error = "" const props3 = {} PropTypes.checkPropTypes(propTypes, props3, "testProp", "testComponent" + ++testComponentId) expect(unspecifiedMsg.test(error)).toBeTruthy() console.error = baseError } function typeCheckPass(declaration: any, value?: any) { const props = { testProp: value } const error = PropTypes.checkPropTypes( { testProp: declaration }, props, "testProp", "testComponent" + ++testComponentId ) expect(error).toBeUndefined() } test("Valid values", () => { typeCheckPass(MRPropTypes.observableArray, observable([])) typeCheckPass(MRPropTypes.observableArrayOf(PropTypes.string), observable([""])) typeCheckPass(MRPropTypes.arrayOrObservableArray, observable([])) typeCheckPass(MRPropTypes.arrayOrObservableArray, []) typeCheckPass(MRPropTypes.arrayOrObservableArrayOf(PropTypes.string), observable([""])) typeCheckPass(MRPropTypes.arrayOrObservableArrayOf(PropTypes.string), [""]) typeCheckPass(MRPropTypes.observableObject, observable({})) typeCheckPass(MRPropTypes.objectOrObservableObject, {}) typeCheckPass(MRPropTypes.objectOrObservableObject, observable({})) typeCheckPass(MRPropTypes.observableMap, observable(observable.map({}, { deep: false }))) }) test("should be implicitly optional and not warn", () => { typeCheckPass(MRPropTypes.observableArray) typeCheckPass(MRPropTypes.observableArrayOf(PropTypes.string)) typeCheckPass(MRPropTypes.arrayOrObservableArray) typeCheckPass(MRPropTypes.arrayOrObservableArrayOf(PropTypes.string)) typeCheckPass(MRPropTypes.observableObject) typeCheckPass(MRPropTypes.objectOrObservableObject) typeCheckPass(MRPropTypes.observableMap) }) test("should warn for missing required values, function (test)", () => { typeCheckFailRequiredValues(MRPropTypes.observableArray.isRequired) typeCheckFailRequiredValues(MRPropTypes.observableArrayOf(PropTypes.string).isRequired) typeCheckFailRequiredValues(MRPropTypes.arrayOrObservableArray.isRequired) typeCheckFailRequiredValues(MRPropTypes.arrayOrObservableArrayOf(PropTypes.string).isRequired) typeCheckFailRequiredValues(MRPropTypes.observableObject.isRequired) typeCheckFailRequiredValues(MRPropTypes.objectOrObservableObject.isRequired) typeCheckFailRequiredValues(MRPropTypes.observableMap.isRequired) }) test("should fail date and regexp correctly", () => { typeCheckFail( MRPropTypes.observableObject, new Date(), "Invalid prop `testProp` of type `date` supplied to " + "`testComponent`, expected `mobx.ObservableObject`." ) typeCheckFail( MRPropTypes.observableArray, /please/, "Invalid prop `testProp` of type `regexp` supplied to " + "`testComponent`, expected `mobx.ObservableArray`." ) }) test("observableArray", () => { typeCheckFail( MRPropTypes.observableArray, [], "Invalid prop `testProp` of type `array` supplied to " + "`testComponent`, expected `mobx.ObservableArray`." ) typeCheckFail( MRPropTypes.observableArray, "", "Invalid prop `testProp` of type `string` supplied to " + "`testComponent`, expected `mobx.ObservableArray`." ) }) test("arrayOrObservableArray", () => { typeCheckFail( MRPropTypes.arrayOrObservableArray, "", "Invalid prop `testProp` of type `string` supplied to " + "`testComponent`, expected `mobx.ObservableArray` or javascript `array`." ) }) test("observableObject", () => { typeCheckFail( MRPropTypes.observableObject, {}, "Invalid prop `testProp` of type `object` supplied to " + "`testComponent`, expected `mobx.ObservableObject`." ) typeCheckFail( MRPropTypes.observableObject, "", "Invalid prop `testProp` of type `string` supplied to " + "`testComponent`, expected `mobx.ObservableObject`." ) }) test("objectOrObservableObject", () => { typeCheckFail( MRPropTypes.objectOrObservableObject, "", "Invalid prop `testProp` of type `string` supplied to " + "`testComponent`, expected `mobx.ObservableObject` or javascript `object`." ) }) test("observableMap", () => { typeCheckFail( MRPropTypes.observableMap, {}, "Invalid prop `testProp` of type `object` supplied to " + "`testComponent`, expected `mobx.ObservableMap`." ) }) test("observableArrayOf", () => { typeCheckFail( MRPropTypes.observableArrayOf(PropTypes.string), 2, "Invalid prop `testProp` of type `number` supplied to " + "`testComponent`, expected `mobx.ObservableArray`." ) typeCheckFail( MRPropTypes.observableArrayOf(PropTypes.string), observable([2]), "Invalid prop `testProp[0]` of type `number` supplied to " + "`testComponent`, expected `string`." ) typeCheckFail( MRPropTypes.observableArrayOf({ foo: (MRPropTypes as any).string } as any), { foo: "bar" }, "Property `testProp` of component `testComponent` has invalid PropType notation." ) }) test("arrayOrObservableArrayOf", () => { typeCheckFail( MRPropTypes.arrayOrObservableArrayOf(PropTypes.string), 2, "Invalid prop `testProp` of type `number` supplied to " + "`testComponent`, expected `mobx.ObservableArray` or javascript `array`." ) typeCheckFail( MRPropTypes.arrayOrObservableArrayOf(PropTypes.string), observable([2]), "Invalid prop `testProp[0]` of type `number` supplied to " + "`testComponent`, expected `string`." ) typeCheckFail( MRPropTypes.arrayOrObservableArrayOf(PropTypes.string), [2], "Invalid prop `testProp[0]` of type `number` supplied to " + "`testComponent`, expected `string`." ) // TODO: typeCheckFail( MRPropTypes.arrayOrObservableArrayOf({ foo: (MRPropTypes as any).string } as any), { foo: "bar" }, "Property `testProp` of component `testComponent` has invalid PropType notation." ) })
4,863
0
petrpan-code/mobxjs/mobx/packages/mobx-react
petrpan-code/mobxjs/mobx/packages/mobx-react/__tests__/stateless.test.tsx
import React from "react" import PropTypes from "prop-types" import { observer, PropTypes as MRPropTypes } from "../src" import { render, act } from "@testing-library/react" import { observable } from "mobx" const StatelessComp = ({ testProp }) => <div>result: {testProp}</div> StatelessComp.propTypes = { testProp: PropTypes.string } StatelessComp.defaultProps = { testProp: "default value for prop testProp" } describe("stateless component with propTypes", () => { const StatelessCompObserver: React.FunctionComponent<any> = observer(StatelessComp) test("default property value should be propagated", () => { expect(StatelessComp.defaultProps.testProp).toBe("default value for prop testProp") expect(StatelessCompObserver.defaultProps!.testProp).toBe("default value for prop testProp") }) const originalConsoleError = console.error let beenWarned = false console.error = () => (beenWarned = true) // eslint-disable-next-line no-unused-vars const wrapper = <StatelessCompObserver testProp={10} /> console.error = originalConsoleError test("an error should be logged with a property type warning", () => { expect(beenWarned).toBeTruthy() }) test("render test correct", async () => { const { container } = render(<StatelessCompObserver testProp="hello world" />) expect(container.textContent).toBe("result: hello world") }) }) test("stateless component with context support", () => { const C = React.createContext<any>({}) const StateLessCompWithContext = () => ( <C.Consumer>{value => <div>context: {value.testContext}</div>}</C.Consumer> ) const StateLessCompWithContextObserver = observer(StateLessCompWithContext) const ContextProvider = () => ( <C.Provider value={{ testContext: "hello world" }}> <StateLessCompWithContextObserver /> </C.Provider> ) const { container } = render(<ContextProvider />) expect(container.textContent).toBe("context: hello world") }) test("component with observable propTypes", () => { class Comp extends React.Component { render() { return null } static propTypes = { a1: MRPropTypes.observableArray, a2: MRPropTypes.arrayOrObservableArray } } const originalConsoleError = console.error const warnings: Array<any> = [] console.error = msg => warnings.push(msg) // eslint-disable-next-line no-unused-vars const firstWrapper = <Comp a1={[]} a2={[]} /> expect(warnings.length).toBe(1) // eslint-disable-next-line no-unused-vars const secondWrapper = <Comp a1={observable([])} a2={observable([])} /> expect(warnings.length).toBe(1) console.error = originalConsoleError }) describe("stateless component with forwardRef", () => { const a = observable({ x: 1 }) const ForwardRefCompObserver: React.ForwardRefExoticComponent<any> = observer( React.forwardRef(({ testProp }, ref) => { return ( <div> result: {testProp}, {ref ? "got ref" : "no ref"}, a.x: {a.x} </div> ) }) ) test("render test correct", () => { const { container } = render( <ForwardRefCompObserver testProp="hello world" ref={React.createRef()} /> ) expect(container).toMatchSnapshot() }) test("is reactive", () => { const { container } = render( <ForwardRefCompObserver testProp="hello world" ref={React.createRef()} /> ) act(() => { a.x++ }) expect(container).toMatchSnapshot() }) })
4,865
0
petrpan-code/mobxjs/mobx/packages/mobx-react
petrpan-code/mobxjs/mobx/packages/mobx-react/__tests__/transactions.test.tsx
import React from "react" import { autorun, computed, observable, transaction } from "mobx" import { observer } from "../src" import { render, act } from "@testing-library/react" test("mobx issue 50", async () => { const foo = { a: observable.box(true), b: observable.box(false), c: computed(function () { // console.log("evaluate c") return foo.b.get() }) } function flipStuff() { transaction(() => { foo.a.set(!foo.a.get()) foo.b.set(!foo.b.get()) }) } let asText = "" autorun(() => (asText = [foo.a.get(), foo.b.get(), foo.c.get()].join(":"))) const Test = observer( class Test extends React.Component { render() { return <div id="x">{[foo.a.get(), foo.b.get(), foo.c.get()].join(",")}</div> } } ) render(<Test />) // Flip a and b. This will change c. act(() => flipStuff()) expect(asText).toBe("false:true:true") expect(document.getElementById("x")!.innerHTML).toBe("false,true,true") }) test("ReactDOM.render should respect transaction", () => { const a = observable.box(2) const loaded = observable.box(false) const valuesSeen: Array<number> = [] const Component = observer(() => { valuesSeen.push(a.get()) if (loaded.get()) return <div>{a.get()}</div> else return <div>loading</div> }) const { container } = render(<Component />) act(() => transaction(() => { a.set(3) a.set(4) loaded.set(true) }) ) expect(container.textContent).toBe("4") expect(valuesSeen.sort()).toEqual([2, 4].sort()) })
4,867
0
petrpan-code/mobxjs/mobx/packages/mobx-react/__tests__
petrpan-code/mobxjs/mobx/packages/mobx-react/__tests__/__snapshots__/hooks.test.tsx.snap
// Jest Snapshot v1, https://goo.gl/fbAQLP exports[`computed properties react to props when using hooks 1`] = ` [MockFunction] { "calls": [ [ "[mobx-react-lite] 'useAsObservableSource' is deprecated, please store the values directly in an observable, for example by using 'useLocalObservable', and sync future updates using 'useEffect' when needed. See the README for examples.", ], [ "[mobx-react-lite] 'useLocalStore' is deprecated, use 'useLocalObservable' instead.", ], ], "results": [ { "type": "return", "value": undefined, }, { "type": "return", "value": undefined, }, ], } `;
4,868
0
petrpan-code/mobxjs/mobx/packages/mobx-react/__tests__
petrpan-code/mobxjs/mobx/packages/mobx-react/__tests__/__snapshots__/observer.test.tsx.snap
// Jest Snapshot v1, https://goo.gl/fbAQLP exports[`#3492 should not cause warning by calling forceUpdate on uncommited components 1`] = `[MockFunction]`; exports[`Redeclaring an existing observer component as an observer should throw 1`] = `"The provided component class (AlreadyObserver) has already been declared as an observer component."`; exports[`SSR works #3448 1`] = `[MockFunction]`; exports[`issue 12 1`] = ` <div> <div> <span> coffee ! </span> <span> tea </span> </div> </div> `; exports[`issue 12 2`] = ` <div> <div> <span> soup </span> </div> </div> `;
4,869
0
petrpan-code/mobxjs/mobx/packages/mobx-react/__tests__
petrpan-code/mobxjs/mobx/packages/mobx-react/__tests__/__snapshots__/stateless.test.tsx.snap
// Jest Snapshot v1, https://goo.gl/fbAQLP exports[`stateless component with forwardRef is reactive 1`] = ` <div> <div> result: hello world , got ref , a.x: 2 </div> </div> `; exports[`stateless component with forwardRef render test correct 1`] = ` <div> <div> result: hello world , got ref , a.x: 1 </div> </div> `;
5,096
0
petrpan-code/mobxjs/mobx-react
petrpan-code/mobxjs/mobx-react/test/Provider.test.tsx
import React from "react" import { Provider } from "../src" import { render } from "@testing-library/react" import { MobXProviderContext } from "../src/Provider" import { withConsole } from "./utils/withConsole" describe("Provider", () => { it("should work in a simple case", () => { function A() { return ( <Provider foo="bar"> <MobXProviderContext.Consumer>{({ foo }) => foo}</MobXProviderContext.Consumer> </Provider> ) } const { container } = render(<A />) expect(container).toHaveTextContent("bar") }) it("should not provide the children prop", () => { function A() { return ( <Provider> <MobXProviderContext.Consumer> {stores => Reflect.has(stores, "children") ? "children was provided" : "children was not provided" } </MobXProviderContext.Consumer> </Provider> ) } const { container } = render(<A />) expect(container).toHaveTextContent("children was not provided") }) it("supports overriding stores", () => { function B() { return ( <MobXProviderContext.Consumer> {({ overridable, nonOverridable }) => `${overridable} ${nonOverridable}`} </MobXProviderContext.Consumer> ) } function A() { return ( <Provider overridable="original" nonOverridable="original"> <B /> <Provider overridable="overriden"> <B /> </Provider> </Provider> ) } const { container } = render(<A />) expect(container).toMatchInlineSnapshot(` <div> original original overriden original </div> `) }) it("should throw an error when changing stores", () => { function A({ foo }) { return ( <Provider foo={foo}> <MobXProviderContext.Consumer>{({ foo }) => foo}</MobXProviderContext.Consumer> </Provider> ) } const { rerender } = render(<A foo={1} />) withConsole(() => { expect(() => { rerender(<A foo={2} />) }).toThrow("The set of provided stores has changed.") }) }) })
5,098
0
petrpan-code/mobxjs/mobx-react
petrpan-code/mobxjs/mobx-react/test/context.test.tsx
import React from "react" import { observable } from "mobx" import { Provider, observer, inject } from "../src" import { withConsole } from "./utils/withConsole" import { render, act } from "@testing-library/react" import { any } from "prop-types" test("no warnings in modern react", () => { const box = observable.box(3) const Child = inject("store")( observer( class Child extends React.Component<any, any> { render() { return ( <div> {this.props.store} + {box.get()} </div> ) } } ) ) class App extends React.Component { render() { return ( <div> <React.StrictMode> <Provider store="42"> <Child /> </Provider> </React.StrictMode> </div> ) } } const { container } = render(<App />) expect(container).toHaveTextContent("42 + 3") withConsole(["info", "warn", "error"], () => { act(() => { box.set(4) }) expect(container).toHaveTextContent("42 + 4") expect(console.info).not.toHaveBeenCalled() expect(console.warn).not.toHaveBeenCalled() expect(console.error).not.toHaveBeenCalled() }) }) test("getDerivedStateFromProps works #447", () => { class Main extends React.Component<any, any> { static getDerivedStateFromProps(nextProps, prevState) { return { count: prevState.count + 1 } } state = { count: 0 } render() { return ( <div> <h2>{`${this.state.count ? "One " : "No "}${this.props.thing}`}</h2> </div> ) } } const MainInjected = inject(({ store }) => ({ thing: store.thing }))(Main) const store = { thing: 3 } const App = () => ( <Provider store={store}> <MainInjected /> </Provider> ) const { container } = render(<App />) expect(container).toHaveTextContent("One 3") }) test("no double runs for getDerivedStateFromProps", () => { let derived = 0 @observer class Main extends React.Component<any, any> { state = { activePropertyElementMap: {} } constructor(props) { // console.log("CONSTRUCTOR") super(props) } static getDerivedStateFromProps() { derived++ // console.log("PREVSTATE", nextProps) return null } render() { return <div>Test-content</div> } } // This results in //PREVSTATE //CONSTRUCTOR //PREVSTATE let MainInjected = inject(() => ({ componentProp: "def" }))(Main) // Uncomment the following line to see default behaviour (without inject) //CONSTRUCTOR //PREVSTATE //MainInjected = Main; const store = {} const App = () => ( <Provider store={store}> <MainInjected injectedProp={"abc"} /> </Provider> ) const { container } = render(<App />) expect(container).toHaveTextContent("Test-content") expect(derived).toBe(1) })
5,099
0
petrpan-code/mobxjs/mobx-react
petrpan-code/mobxjs/mobx-react/test/disposeOnUnmount.test.tsx
import React from "react" import { disposeOnUnmount, observer } from "../src" import { render } from "@testing-library/react" import { MockedComponentClass } from "react-dom/test-utils" interface ClassC extends MockedComponentClass { methodA?: any methodB?: any methodC?: any methodD?: any } function testComponent(C: ClassC, afterMount?: Function, afterUnmount?: Function) { const ref = React.createRef<ClassC>() const { unmount } = render(<C ref={ref} />) let cref = ref.current expect(cref?.methodA).not.toHaveBeenCalled() expect(cref?.methodB).not.toHaveBeenCalled() if (afterMount) { afterMount(cref) } unmount() expect(cref?.methodA).toHaveBeenCalledTimes(1) expect(cref?.methodB).toHaveBeenCalledTimes(1) if (afterUnmount) { afterUnmount(cref) } } describe("without observer", () => { test("class without componentWillUnmount", async () => { class C extends React.Component { @disposeOnUnmount methodA = jest.fn() @disposeOnUnmount methodB = jest.fn() @disposeOnUnmount methodC = null @disposeOnUnmount methodD = undefined render() { return null } } testComponent(C) }) test("class with componentWillUnmount in the prototype", () => { let called = 0 class C extends React.Component { @disposeOnUnmount methodA = jest.fn() @disposeOnUnmount methodB = jest.fn() @disposeOnUnmount methodC = null @disposeOnUnmount methodD = undefined render() { return null } componentWillUnmount() { called++ } } testComponent( C, () => { expect(called).toBe(0) }, () => { expect(called).toBe(1) } ) }) test("class with componentWillUnmount as an arrow function", () => { let called = 0 class C extends React.Component { @disposeOnUnmount methodA = jest.fn() @disposeOnUnmount methodB = jest.fn() @disposeOnUnmount methodC = null @disposeOnUnmount methodD = undefined render() { return null } componentWillUnmount = () => { called++ } } testComponent( C, () => { expect(called).toBe(0) }, () => { expect(called).toBe(1) } ) }) test("class without componentWillUnmount using non decorator version", () => { let methodC = jest.fn() let methodD = jest.fn() class C extends React.Component { render() { return null } methodA = disposeOnUnmount(this, jest.fn()) methodB = disposeOnUnmount(this, jest.fn()) constructor(props) { super(props) disposeOnUnmount(this, [methodC, methodD]) } } testComponent( C, () => { expect(methodC).not.toHaveBeenCalled() expect(methodD).not.toHaveBeenCalled() }, () => { expect(methodC).toHaveBeenCalledTimes(1) expect(methodD).toHaveBeenCalledTimes(1) } ) }) }) describe("with observer", () => { test("class without componentWillUnmount", () => { @observer class C extends React.Component { @disposeOnUnmount methodA = jest.fn() @disposeOnUnmount methodB = jest.fn() @disposeOnUnmount methodC = null @disposeOnUnmount methodD = undefined render() { return null } } testComponent(C) }) test("class with componentWillUnmount in the prototype", () => { let called = 0 @observer class C extends React.Component { @disposeOnUnmount methodA = jest.fn() @disposeOnUnmount methodB = jest.fn() @disposeOnUnmount methodC = null @disposeOnUnmount methodD = undefined render() { return null } componentWillUnmount() { called++ } } testComponent( C, () => { expect(called).toBe(0) }, () => { expect(called).toBe(1) } ) }) test("class with componentWillUnmount as an arrow function", () => { let called = 0 @observer class C extends React.Component { @disposeOnUnmount methodA = jest.fn() @disposeOnUnmount methodB = jest.fn() @disposeOnUnmount methodC = null @disposeOnUnmount methodD = undefined render() { return null } componentWillUnmount = () => { called++ } } testComponent( C, () => { expect(called).toBe(0) }, () => { expect(called).toBe(1) } ) }) test("class without componentWillUnmount using non decorator version", () => { let methodC = jest.fn() let methodD = jest.fn() @observer class C extends React.Component { render() { return null } methodA = disposeOnUnmount(this, jest.fn()) methodB = disposeOnUnmount(this, jest.fn()) constructor(props) { super(props) disposeOnUnmount(this, [methodC, methodD]) } } testComponent( C, () => { expect(methodC).not.toHaveBeenCalled() expect(methodD).not.toHaveBeenCalled() }, () => { expect(methodC).toHaveBeenCalledTimes(1) expect(methodD).toHaveBeenCalledTimes(1) } ) }) }) it("componentDidMount should be different between components", () => { function doTest(withObserver) { const events: Array<string> = [] class A extends React.Component { didMount willUnmount componentDidMount() { this.didMount = "A" events.push("mountA") } componentWillUnmount() { this.willUnmount = "A" events.push("unmountA") } render() { return null } } class B extends React.Component { didMount willUnmount componentDidMount() { this.didMount = "B" events.push("mountB") } componentWillUnmount() { this.willUnmount = "B" events.push("unmountB") } render() { return null } } if (withObserver) { // @ts-ignore // eslint-disable-next-line no-class-assign A = observer(A) // @ts-ignore // eslint-disable-next-line no-class-assign B = observer(B) } const aRef = React.createRef<A>() const { rerender, unmount } = render(<A ref={aRef} />) const caRef = aRef.current expect(caRef?.didMount).toBe("A") expect(caRef?.willUnmount).toBeUndefined() expect(events).toEqual(["mountA"]) const bRef = React.createRef<B>() rerender(<B ref={bRef} />) const cbRef = bRef.current expect(caRef?.didMount).toBe("A") expect(caRef?.willUnmount).toBe("A") expect(cbRef?.didMount).toBe("B") expect(cbRef?.willUnmount).toBeUndefined() expect(events).toEqual(["mountA", "unmountA", "mountB"]) unmount() expect(caRef?.didMount).toBe("A") expect(caRef?.willUnmount).toBe("A") expect(cbRef?.didMount).toBe("B") expect(cbRef?.willUnmount).toBe("B") expect(events).toEqual(["mountA", "unmountA", "mountB", "unmountB"]) } doTest(true) doTest(false) }) test("base cWU should not be called if overriden", () => { let baseCalled = 0 let dCalled = 0 let oCalled = 0 class C extends React.Component { componentWillUnmount() { baseCalled++ } constructor(props) { super(props) this.componentWillUnmount = () => { oCalled++ } } render() { return null } @disposeOnUnmount fn() { dCalled++ } } const { unmount } = render(<C />) unmount() expect(dCalled).toBe(1) expect(oCalled).toBe(1) expect(baseCalled).toBe(0) }) test("should error on inheritance", () => { class C extends React.Component { render() { return null } } expect(() => { // eslint-disable-next-line no-unused-vars class B extends C { @disposeOnUnmount fn() {} } }).toThrow("disposeOnUnmount only supports direct subclasses") }) test("should error on inheritance - 2", () => { class C extends React.Component { render() { return null } } class B extends C { fn constructor(props) { super(props) expect(() => { this.fn = disposeOnUnmount(this, function() {}) }).toThrow("disposeOnUnmount only supports direct subclasses") } } render(<B />) }) describe("should work with arrays", () => { test("as a function", () => { class C extends React.Component { methodA = jest.fn() methodB = jest.fn() componentDidMount() { disposeOnUnmount(this, [this.methodA, this.methodB]) } render() { return null } } testComponent(C) }) test("as a decorator", () => { class C extends React.Component { methodA = jest.fn() methodB = jest.fn() @disposeOnUnmount disposers = [this.methodA, this.methodB] render() { return null } } testComponent(C) }) }) it("runDisposersOnUnmount only runs disposers from the declaring instance", () => { class A extends React.Component { @disposeOnUnmount a = jest.fn() b = jest.fn() constructor(props) { super(props) disposeOnUnmount(this, this.b) } render() { return null } } const ref1 = React.createRef<A>() const ref2 = React.createRef<A>() const { unmount } = render(<A ref={ref1} />) render(<A ref={ref2} />) const inst1 = ref1.current const inst2 = ref2.current unmount() expect(inst1?.a).toHaveBeenCalledTimes(1) expect(inst1?.b).toHaveBeenCalledTimes(1) expect(inst2?.a).toHaveBeenCalledTimes(0) expect(inst2?.b).toHaveBeenCalledTimes(0) })
5,100
0
petrpan-code/mobxjs/mobx-react
petrpan-code/mobxjs/mobx-react/test/hooks.test.tsx
import React from "react" import { observer, Observer, useLocalStore, useAsObservableSource } from "../src" import { render, act } from "@testing-library/react" afterEach(() => { jest.useRealTimers() }) test("computed properties react to props when using hooks", async () => { jest.useFakeTimers() const seen: Array<string> = [] const Child = ({ x }) => { const props = useAsObservableSource({ x }) const store = useLocalStore(() => ({ get getPropX() { return props.x } })) return ( <Observer>{() => (seen.push(store.getPropX), (<div>{store.getPropX}</div>))}</Observer> ) } const Parent = () => { const [state, setState] = React.useState({ x: 0 }) seen.push("parent") React.useEffect(() => { setTimeout(() => { act(() => { setState({ x: 2 }) }) }) }, []) return <Child x={state.x} /> } const { container } = render(<Parent />) expect(container).toHaveTextContent("0") jest.runAllTimers() expect(seen).toEqual(["parent", 0, "parent", 2]) expect(container).toHaveTextContent("2") }) test("computed properties result in double render when using observer instead of Observer", async () => { jest.useFakeTimers() const seen: Array<string> = [] const Child = observer(({ x }) => { const props = useAsObservableSource({ x }) const store = useLocalStore(() => ({ get getPropX() { return props.x } })) seen.push(store.getPropX) return <div>{store.getPropX}</div> }) const Parent = () => { const [state, setState] = React.useState({ x: 0 }) seen.push("parent") React.useEffect(() => { setTimeout(() => { act(() => { setState({ x: 2 }) }) }, 100) }, []) return <Child x={state.x} /> } const { container } = render(<Parent />) expect(container).toHaveTextContent("0") jest.runAllTimers() expect(seen).toEqual([ "parent", 0, "parent", 2, 2 // should contain "2" only once! But with hooks, one update is scheduled based the fact that props change, the other because the observable source changed. ]) expect(container).toHaveTextContent("2") })
5,101
0
petrpan-code/mobxjs/mobx-react
petrpan-code/mobxjs/mobx-react/test/inject.test.tsx
import React from "react" import PropTypes from "prop-types" import { action, observable, makeObservable } from "mobx" import { observer, inject, Provider } from "../src" import { IValueMap } from "../src/types/IValueMap" import { render, act } from "@testing-library/react" import { withConsole } from "./utils/withConsole" import { IReactComponent } from "../src/types/IReactComponent" describe("inject based context", () => { test("basic context", () => { const C = inject("foo")( observer( class X extends React.Component<any, any> { render() { return ( <div> context: {this.props.foo} </div> ) } } ) ) const B = () => <C /> const A = () => ( <Provider foo="bar"> <B /> </Provider> ) const { container } = render(<A />) expect(container).toHaveTextContent("context:bar") }) test("props override context", () => { const C = inject("foo")( class T extends React.Component<any, any> { render() { return ( <div> context: {this.props.foo} </div> ) } } ) const B = () => <C foo={42} /> const A = class T extends React.Component<any, any> { render() { return ( <Provider foo="bar"> <B /> </Provider> ) } } const { container } = render(<A />) expect(container).toHaveTextContent("context:42") }) test("wraps displayName of original component", () => { const A: React.ComponentClass = inject("foo")( class ComponentA extends React.Component<any, any> { render() { return ( <div> context: {this.props.foo} </div> ) } } ) const B: React.ComponentClass = inject()( class ComponentB extends React.Component<any, any> { render() { return ( <div> context: {this.props.foo} </div> ) } } ) const C: React.ComponentClass = inject(() => ({}))( class ComponentC extends React.Component<any, any> { render() { return ( <div> context: {this.props.foo} </div> ) } } ) expect(A.displayName).toBe("inject-with-foo(ComponentA)") expect(B.displayName).toBe("inject(ComponentB)") expect(C.displayName).toBe("inject(ComponentC)") }) // FIXME: see other comments related to error catching in React // test does work as expected when running manually test("store should be available", () => { const C = inject("foo")( observer( class C extends React.Component<any, any> { render() { return ( <div> context: {this.props.foo} </div> ) } } ) ) const B = () => <C /> const A = class A extends React.Component<any, any> { render() { return ( <Provider baz={42}> <B /> </Provider> ) } } withConsole(() => { expect(() => render(<A />)).toThrow( /Store 'foo' is not available! Make sure it is provided by some Provider/ ) }) }) test("store is not required if prop is available", () => { const C = inject("foo")( observer( class C extends React.Component<any, any> { render() { return ( <div> context: {this.props.foo} </div> ) } } ) ) const B = () => <C foo="bar" /> const { container } = render(<B />) expect(container).toHaveTextContent("context:bar") }) test("inject merges (and overrides) props", () => { const C = inject(() => ({ a: 1 }))( observer( class C extends React.Component<any, any> { render() { expect(this.props).toEqual({ a: 1, b: 2 }) return null } } ) ) const B = () => <C a={2} b={2} /> render(<B />) }) test("custom storesToProps", () => { const C = inject((stores: IValueMap, props: any) => { expect(stores).toEqual({ foo: "bar" }) expect(props).toEqual({ baz: 42 }) return { zoom: stores.foo, baz: props.baz * 2 } })( observer( class C extends React.Component<any, any> { render() { return ( <div> context: {this.props.zoom} {this.props.baz} </div> ) } } ) ) const B = class B extends React.Component<any, any> { render() { return <C baz={42} /> } } const A = () => ( <Provider foo="bar"> <B /> </Provider> ) const { container } = render(<A />) expect(container).toHaveTextContent("context:bar84") }) test("inject forwards ref", () => { class FancyComp extends React.Component<any, any> { didRender render() { this.didRender = true return null } doSomething() {} } const ref = React.createRef<FancyComp>() render(<FancyComp ref={ref} />) expect(typeof ref.current?.doSomething).toBe("function") expect(ref.current?.didRender).toBe(true) const InjectedFancyComp = inject("bla")(FancyComp) const ref2 = React.createRef<FancyComp>() render( <Provider bla={42}> <InjectedFancyComp ref={ref2} /> </Provider> ) expect(typeof ref2.current?.doSomething).toBe("function") expect(ref2.current?.didRender).toBe(true) }) test("inject should work with components that use forwardRef", () => { const FancyComp = React.forwardRef((_: any, ref: React.Ref<HTMLDivElement>) => { return <div ref={ref} /> }) const InjectedFancyComp = inject("bla")(FancyComp) const ref = React.createRef<HTMLDivElement>() render( <Provider bla={42}> <InjectedFancyComp ref={ref} /> </Provider> ) expect(ref.current).not.toBeNull() expect(ref.current).toBeInstanceOf(HTMLDivElement) }) test("support static hoisting, wrappedComponent and ref forwarding", () => { class B extends React.Component<any, any> { static foo static bar testField render() { this.testField = 1 return null } } ;(B as React.ComponentClass).propTypes = { x: PropTypes.object } B.foo = 17 B.bar = {} const C = inject("booh")(B) expect(C.wrappedComponent).toBe(B) expect(B.foo).toBe(17) expect(C.foo).toBe(17) expect(C.bar === B.bar).toBeTruthy() expect(Object.keys(C.wrappedComponent.propTypes!)).toEqual(["x"]) const ref = React.createRef<B>() render(<C booh={42} ref={ref} />) expect(ref.current?.testField).toBe(1) }) test("propTypes and defaultProps are forwarded", () => { const msg: Array<string> = [] const baseError = console.error console.error = m => msg.push(m) const C: React.ComponentClass<any> = inject("foo")( class C extends React.Component<any, any> { render() { expect(this.props.y).toEqual(3) expect(this.props.x).toBeUndefined() return null } } ) C.propTypes = { x: PropTypes.func.isRequired, z: PropTypes.string.isRequired } // @ts-ignore C.wrappedComponent.propTypes = { a: PropTypes.func.isRequired } C.defaultProps = { y: 3 } const B = () => <C z="test" /> const A = () => ( <Provider foo="bar"> <B /> </Provider> ) render(<A />) expect(msg.length).toBe(2) expect(msg[0].split("\n")[0]).toBe( "Warning: Failed prop type: The prop `x` is marked as required in `inject-with-foo(C)`, but its value is `undefined`." ) expect(msg[1].split("\n")[0]).toBe( "Warning: Failed prop type: The prop `a` is marked as required in `C`, but its value is `undefined`." ) console.error = baseError }) test("warning is not printed when attaching propTypes to injected component", () => { let msg = [] const baseWarn = console.warn console.warn = m => (msg = m) const C: React.ComponentClass = inject("foo")( class C extends React.Component<any, any> { render() { return ( <div> context: {this.props.foo} </div> ) } } ) C.propTypes = {} expect(msg.length).toBe(0) console.warn = baseWarn }) test("warning is not printed when attaching propTypes to wrappedComponent", () => { let msg = [] const baseWarn = console.warn console.warn = m => (msg = m) const C = inject("foo")( class C extends React.Component<any, any> { render() { return ( <div> context: {this.props.foo} </div> ) } } ) C.wrappedComponent.propTypes = {} expect(msg.length).toBe(0) console.warn = baseWarn }) test("using a custom injector is reactive", () => { const user = observable({ name: "Noa" }) const mapper = stores => ({ name: stores.user.name }) const DisplayName = props => <h1>{props.name}</h1> const User = inject(mapper)(DisplayName) const App = () => ( <Provider user={user}> <User /> </Provider> ) const { container } = render(<App />) expect(container).toHaveTextContent("Noa") act(() => { user.name = "Veria" }) expect(container).toHaveTextContent("Veria") }) test("using a custom injector is not too reactive", () => { let listRender = 0 let itemRender = 0 let injectRender = 0 function connect() { const args = arguments return (component: IReactComponent) => // @ts-ignore inject.apply(this, args)(observer(component)) } class State { @observable highlighted = null isHighlighted(item) { return this.highlighted == item } @action highlight = item => { this.highlighted = item } constructor() { makeObservable(this) } } const items = observable([ { title: "ItemA" }, { title: "ItemB" }, { title: "ItemC" }, { title: "ItemD" }, { title: "ItemE" }, { title: "ItemF" } ]) const state = new State() class ListComponent extends React.PureComponent<any> { render() { listRender++ const { items } = this.props return ( <ul> {items.map(item => ( <ItemComponent key={item.title} item={item} /> ))} </ul> ) } } // @ts-ignore @connect(({ state }, { item }) => { injectRender++ if (injectRender > 6) { // debugger; } return { // Using // highlighted: expr(() => state.isHighlighted(item)) // seems to fix the problem highlighted: state.isHighlighted(item), highlight: state.highlight } }) class ItemComponent extends React.PureComponent<any> { highlight = () => { const { item, highlight } = this.props highlight(item) } render() { itemRender++ const { highlighted, item } = this.props return ( <li className={"hl_" + item.title} onClick={this.highlight}> {item.title} {highlighted ? "(highlighted)" : ""}{" "} </li> ) } } const { container } = render( <Provider state={state}> <ListComponent items={items} /> </Provider> ) expect(listRender).toBe(1) expect(injectRender).toBe(6) expect(itemRender).toBe(6) container.querySelectorAll(".hl_ItemB").forEach((e: Element) => (e as HTMLElement).click()) expect(listRender).toBe(1) expect(injectRender).toBe(12) // ideally, 7 expect(itemRender).toBe(7) container.querySelectorAll(".hl_ItemF").forEach((e: Element) => (e as HTMLElement).click()) expect(listRender).toBe(1) expect(injectRender).toBe(18) // ideally, 9 expect(itemRender).toBe(9) }) }) test("#612 - mixed context types", () => { const SomeContext = React.createContext(true) class MainCompClass extends React.Component<any, any> { static contextType = SomeContext render() { let active = this.context return active ? this.props.value : "Inactive" } } const MainComp = inject((stores: any) => ({ value: stores.appState.value }))(MainCompClass) const appState = observable({ value: "Something" }) function App() { return ( <Provider appState={appState}> <SomeContext.Provider value={true}> <MainComp /> </SomeContext.Provider> </Provider> ) } render(<App />) })
5,102
0
petrpan-code/mobxjs/mobx-react
petrpan-code/mobxjs/mobx-react/test/issue21.test.tsx
import React, { createElement } from "react" import { computed, isObservable, observable, reaction, transaction, IReactionDisposer, makeObservable } from "mobx" import { observer } from "../src" import _ from "lodash" import { render } from "@testing-library/react" let topRenderCount = 0 const wizardModel = observable( { steps: [ { title: "Size", active: true }, { title: "Fabric", active: false }, { title: "Finish", active: false } ], get activeStep() { return _.find(this.steps, "active") }, activateNextStep: function() { const nextStep = this.steps[_.findIndex(this.steps, "active") + 1] if (!nextStep) { return false } this.setActiveStep(nextStep) return true }, setActiveStep(modeToActivate) { const self = this transaction(() => { _.find(self.steps, "active").active = false modeToActivate.active = true }) } } as any, { activateNextStep: observable.ref } ) /** RENDERS **/ const Wizard = observer( class Wizard extends React.Component<any, any> { render() { return createElement( "div", null, <div> <h1>Active Step: </h1> <WizardStep step={this.props.model.activeStep} key="activeMode" tester /> </div>, <div> <h1>All Step: </h1> <p> Clicking on these steps will render the active step just once. This is what I expected. </p> <WizardStep step={this.props.model.steps} key="modeList" /> </div> ) } } ) const WizardStep = observer( class WizardStep extends React.Component<any, any> { renderCount = 0 componentWillUnmount() { // console.log("Unmounting!") } render() { // weird test hack: if (this.props.tester === true) { topRenderCount++ } return createElement( "div", { onClick: this.modeClickHandler }, "RenderCount: " + this.renderCount++ + " " + this.props.step.title + ": isActive:" + this.props.step.active ) } modeClickHandler = () => { var step = this.props.step wizardModel.setActiveStep(step) } } ) /** END RENDERERS **/ const changeStep = stepNumber => wizardModel.setActiveStep(wizardModel.steps[stepNumber]) test("verify issue 21", () => { render(<Wizard model={wizardModel} />) expect(topRenderCount).toBe(1) changeStep(0) expect(topRenderCount).toBe(2) changeStep(2) expect(topRenderCount).toBe(3) }) test("verify prop changes are picked up", () => { function createItem(subid, label) { const res = observable( { subid, id: 1, label: label, get text() { events.push(["compute", this.subid]) return ( this.id + "." + this.subid + "." + this.label + "." + data.items.indexOf(this as any) ) } }, {}, { proxy: false } ) res.subid = subid // non reactive return res } const data = observable({ items: [createItem(1, "hi")] }) const events: Array<any> = [] const Child = observer( class Child extends React.Component<any, any> { componentDidUpdate(prevProps) { events.push(["update", prevProps.item.subid, this.props.item.subid]) } render() { events.push(["render", this.props.item.subid, this.props.item.text]) return <span>{this.props.item.text}</span> } } ) const Parent = observer( class Parent extends React.Component<any, any> { render() { return ( <div onClick={changeStuff.bind(this)} id="testDiv"> {data.items.map(item => ( <Child key="fixed" item={item} /> ))} </div> ) } } ) const Wrapper = () => <Parent /> function changeStuff() { transaction(() => { data.items[0].label = "hello" // schedules state change for Child data.items[0] = createItem(2, "test") // Child should still receive new prop! }) // @ts-ignore this.setState({}) // trigger update } const { container } = render(<Wrapper />) expect(events.sort()).toEqual( [ ["compute", 1], ["render", 1, "1.1.hi.0"] ].sort() ) events.splice(0) let testDiv = container.querySelector("#testDiv")! as HTMLElement testDiv.click() expect(events.sort()).toEqual( [ ["compute", 1], ["update", 1, 2], ["compute", 2], ["render", 2, "1.2.test.0"] ].sort() ) }) test("verify props is reactive", () => { function createItem(subid, label) { const res = observable( { subid, id: 1, label: label, get text() { events.push(["compute", this.subid]) return ( this.id + "." + this.subid + "." + this.label + "." + data.items.indexOf(this as any) ) } }, {}, { proxy: false } ) res.subid = subid // non reactive return res } const data = observable({ items: [createItem(1, "hi")] }) const events: Array<any> = [] class Child extends React.Component<any, any> { constructor(p) { super(p) makeObservable(this) } @computed get computedLabel() { events.push(["computed label", this.props.item.subid]) return this.props.item.label } componentDidMount() { events.push(["mount"]) } componentDidUpdate(prevProps) { events.push(["update", prevProps.item.subid, this.props.item.subid]) } render() { events.push(["render", this.props.item.subid, this.props.item.text, this.computedLabel]) return ( <span> {this.props.item.text} {this.computedLabel} </span> ) } } const ChildAsObserver = observer(Child) const Parent = observer( class Parent extends React.Component<any, any> { render() { return ( <div onClick={changeStuff.bind(this)} id="testDiv"> {data.items.map(item => ( <ChildAsObserver key="fixed" item={item} /> ))} </div> ) } } ) const Wrapper = () => <Parent /> function changeStuff() { transaction(() => { // components start rendeirng a new item, but computed is still based on old value data.items = [createItem(2, "test")] }) } const { container } = render(<Wrapper />) expect(events.sort()).toEqual( [["mount"], ["compute", 1], ["computed label", 1], ["render", 1, "1.1.hi.0", "hi"]].sort() ) events.splice(0) let testDiv = container.querySelector("#testDiv") as HTMLElement testDiv.click() expect(events.sort()).toEqual( [ ["compute", 1], ["update", 1, 2], ["compute", 2], ["computed label", 2], ["render", 2, "1.2.test.0", "test"] ].sort() ) }) test("no re-render for shallow equal props", async () => { function createItem(subid, label) { const res = observable({ subid, id: 1, label: label }) res.subid = subid // non reactive return res } const data = observable({ items: [createItem(1, "hi")], parentValue: 0 }) const events: Array<Array<any>> = [] const Child = observer( class Child extends React.Component<any, any> { componentDidMount() { events.push(["mount"]) } componentDidUpdate(prevProps) { events.push(["update", prevProps.item.subid, this.props.item.subid]) } render() { events.push(["render", this.props.item.subid, this.props.item.label]) return <span>{this.props.item.label}</span> } } ) const Parent = observer( class Parent extends React.Component<any, any> { render() { // "object has become observable!" expect(isObservable(this.props.nonObservable)).toBeFalsy() events.push(["parent render", data.parentValue]) return ( <div onClick={changeStuff.bind(this)} id="testDiv"> {data.items.map(item => ( <Child key="fixed" item={item} value={5} /> ))} </div> ) } } ) const Wrapper = () => <Parent nonObservable={{}} /> function changeStuff() { data.items[0].label = "hi" // no change. data.parentValue = 1 // rerender parent } const { container } = render(<Wrapper />) expect(events.sort()).toEqual([["parent render", 0], ["mount"], ["render", 1, "hi"]].sort()) events.splice(0) let testDiv = container.querySelector("#testDiv") as HTMLElement testDiv.click() expect(events.sort()).toEqual([["parent render", 1]].sort()) }) test("lifecycle callbacks called with correct arguments", () => { var Comp = observer( class Comp extends React.Component<any, any> { componentDidUpdate(prevProps) { expect(prevProps.counter).toBe(0) expect(this.props.counter).toBe(1) } render() { return ( <div> <span key="1">{[this.props.counter]}</span> <button key="2" id="testButton" onClick={this.props.onClick} /> </div> ) } } ) const Root = class T extends React.Component<any, any> { state = { counter: 0 } onButtonClick = () => { this.setState({ counter: (this.state.counter || 0) + 1 }) } render() { return <Comp counter={this.state.counter || 0} onClick={this.onButtonClick} /> } } const { container } = render(<Root />) let testButton = container.querySelector("#testButton") as HTMLElement testButton.click() }) test("verify props are reactive in constructor", () => { const propValues: Array<any> = [] let constructorCallsCount = 0 const Component = observer( class Component extends React.Component<any, any> { disposer: IReactionDisposer constructor(props, context) { super(props, context) constructorCallsCount++ this.disposer = reaction( () => this.props.prop, prop => propValues.push(prop), { fireImmediately: true } ) } componentWillUnmount() { this.disposer() } render() { return <div /> } } ) const { rerender } = render(<Component prop="1" />) rerender(<Component prop="2" />) rerender(<Component prop="3" />) rerender(<Component prop="4" />) expect(constructorCallsCount).toEqual(1) expect(propValues).toEqual(["1", "2", "3", "4"]) })
5,103
0
petrpan-code/mobxjs/mobx-react
petrpan-code/mobxjs/mobx-react/test/issue806.test.tsx
import React from "react" import { configure, observable } from "mobx" import { observer } from "../src" import { render } from "@testing-library/react" import { withConsole } from "./utils/withConsole" @observer class Issue806Component extends React.Component<any> { render() { return ( <span> {this.props.a} <Issue806Component2 propA={this.props.a} propB={this.props.b} /> </span> ) } } @observer class Issue806Component2 extends React.Component<any> { render() { return ( <span> {this.props.propA} - {this.props.propB} </span> ) } } test("verify issue 806", () => { configure({ observableRequiresReaction: true }) const x = observable({ a: 1 }) withConsole(["warn"], () => { render(<Issue806Component a={"a prop value"} b={"b prop value"} x={x} />) expect(console.warn).not.toHaveBeenCalled() }) // make sure observableRequiresReaction is still working outside component withConsole(["warn"], () => { x.a.toString() expect(console.warn).toBeCalledTimes(1) expect(console.warn).toHaveBeenCalledWith( "[mobx] Observable [email protected] being read outside a reactive context" ) }) })
5,104
0
petrpan-code/mobxjs/mobx-react
petrpan-code/mobxjs/mobx-react/test/misc.test.tsx
import React from "react" import { extendObservable, observable } from "mobx" import { observer } from "../src" import { render } from "@testing-library/react" test("issue mobx 405", () => { function ExampleState() { // @ts-ignore extendObservable(this, { name: "test", get greetings() { return "Hello my name is " + this.name } }) } const ExampleView = observer( class T extends React.Component<any, any> { render() { return ( <div> <input type="text" onChange={e => (this.props.exampleState.name = e.target.value)} value={this.props.exampleState.name} /> <span>{this.props.exampleState.greetings}</span> </div> ) } } ) const exampleState = new ExampleState() const { container } = render(<ExampleView exampleState={exampleState} />) expect(container).toMatchInlineSnapshot(` <div> <div> <input type="text" value="test" /> <span> Hello my name is test </span> </div> </div> `) }) test("#85 Should handle state changing in constructors", () => { const a = observable.box(2) const Child = observer( class Child extends React.Component { constructor(p) { super(p) a.set(3) // one shouldn't do this! this.state = {} } render() { return ( <div> child: {a.get()} -{" "} </div> ) } } ) const ParentWrapper = observer(function Parent() { return ( <span> <Child /> parent: {a.get()} </span> ) }) const { container } = render(<ParentWrapper />) expect(container).toHaveTextContent("child:3 - parent:3") a.set(5) expect(container).toHaveTextContent("child:5 - parent:5") a.set(7) expect(container).toHaveTextContent("child:7 - parent:7") })
5,105
0
petrpan-code/mobxjs/mobx-react
petrpan-code/mobxjs/mobx-react/test/observer.test.tsx
import React from "react" import { inject, observer, Observer, enableStaticRendering } from "../src" import { render, act } from "@testing-library/react" import { getObserverTree, _resetGlobalState, action, computed, observable, transaction, makeObservable } from "mobx" import { withConsole } from "./utils/withConsole" /** * some test suite is too tedious */ afterEach(() => { jest.useRealTimers() }) /* use TestUtils.renderIntoDocument will re-mounted the component with different props some misunderstanding will be cause? */ describe("nestedRendering", () => { let store let todoItemRenderings const TodoItem = observer(function TodoItem(props) { todoItemRenderings++ return <li>|{props.todo.title}</li> }) let todoListRenderings const TodoList = observer( class TodoList extends React.Component { render() { todoListRenderings++ const todos = store.todos return ( <div> <span>{todos.length}</span> {todos.map((todo, idx) => ( <TodoItem key={idx} todo={todo} /> ))} </div> ) } } ) beforeEach(() => { todoItemRenderings = 0 todoListRenderings = 0 store = observable({ todos: [ { title: "a", completed: false } ] }) }) test("first rendering", () => { const { container } = render(<TodoList />) expect(todoListRenderings).toBe(1) expect(container.querySelectorAll("li").length).toBe(1) expect(container.querySelector("li")).toHaveTextContent("|a") expect(todoItemRenderings).toBe(1) }) test("second rendering with inner store changed", () => { render(<TodoList />) store.todos[0].title += "a" expect(todoListRenderings).toBe(1) expect(todoItemRenderings).toBe(2) expect(getObserverTree(store, "todos").observers!.length).toBe(1) expect(getObserverTree(store.todos[0], "title").observers!.length).toBe(1) }) test("rerendering with outer store added", () => { const { container } = render(<TodoList />) store.todos.push({ title: "b", completed: true }) expect(container.querySelectorAll("li").length).toBe(2) expect( Array.from(container.querySelectorAll("li")) .map((e: any) => e.innerHTML) .sort() ).toEqual(["|a", "|b"].sort()) expect(todoListRenderings).toBe(2) expect(todoItemRenderings).toBe(2) expect(getObserverTree(store.todos[1], "title").observers!.length).toBe(1) expect(getObserverTree(store.todos[1], "completed").observers).toBe(undefined) }) test("rerendering with outer store pop", () => { const { container } = render(<TodoList />) const oldTodo = store.todos.pop() expect(todoListRenderings).toBe(2) expect(todoItemRenderings).toBe(1) expect(container.querySelectorAll("li").length).toBe(0) expect(getObserverTree(oldTodo, "title").observers).toBe(undefined) expect(getObserverTree(oldTodo, "completed").observers).toBe(undefined) }) }) describe("isObjectShallowModified detects when React will update the component", () => { const store = observable({ count: 0 }) let counterRenderings = 0 const Counter: React.FunctionComponent<any> = observer(function TodoItem() { counterRenderings++ return <div>{store.count}</div> }) test("does not assume React will update due to NaN prop", () => { render(<Counter value={NaN} />) store.count++ expect(counterRenderings).toBe(2) }) }) describe("keep views alive", () => { let yCalcCount let data const TestComponent = observer(function testComponent() { return ( <div> {data.z} {data.y} </div> ) }) beforeEach(() => { yCalcCount = 0 data = observable({ x: 3, get y() { yCalcCount++ return this.x * 2 }, z: "hi" }) }) test("init state", () => { const { container } = render(<TestComponent />) expect(yCalcCount).toBe(1) expect(container).toHaveTextContent("hi6") }) test("rerender should not need a recomputation of data.y", () => { const { container } = render(<TestComponent />) data.z = "hello" expect(yCalcCount).toBe(1) expect(container).toHaveTextContent("hello6") }) }) describe("does not views alive when using static rendering", () => { let renderCount let data const TestComponent = observer(function testComponent() { renderCount++ return <div>{data.z}</div> }) beforeAll(() => { enableStaticRendering(true) }) beforeEach(() => { renderCount = 0 data = observable({ z: "hi" }) }) afterAll(() => { enableStaticRendering(false) }) test("init state is correct", () => { const { container } = render(<TestComponent />) expect(renderCount).toBe(1) expect(container).toHaveTextContent("hi") }) test("no re-rendering on static rendering", () => { const { container } = render(<TestComponent />) data.z = "hello" expect(getObserverTree(data, "z").observers).toBe(undefined) expect(renderCount).toBe(1) expect(container).toHaveTextContent("hi") }) }) test("issue 12", () => { const events: Array<any> = [] const data = observable({ selected: "coffee", items: [ { name: "coffee" }, { name: "tea" } ] }) /** Row Class */ class Row extends React.Component<any, any> { constructor(props) { super(props) } render() { events.push("row: " + this.props.item.name) return ( <span> {this.props.item.name} {data.selected === this.props.item.name ? "!" : ""} </span> ) } } /** table stateles component */ const Table = observer(function table() { events.push("table") JSON.stringify(data) return ( <div> {data.items.map(item => ( <Row key={item.name} item={item} /> ))} </div> ) }) const { container } = render(<Table />) expect(container).toMatchSnapshot() act(() => { transaction(() => { data.items[1].name = "boe" data.items.splice(0, 2, { name: "soup" }) data.selected = "tea" }) }) expect(container).toMatchSnapshot() expect(events).toEqual(["table", "row: coffee", "row: tea", "table", "row: soup"]) }) test("changing state in render should fail", () => { const data = observable.box(2) const Comp = observer(() => { if (data.get() === 3) { try { data.set(4) // wouldn't throw first time for lack of observers.. (could we tighten this?) } catch (err) { expect( /Side effects like changing state are not allowed at this point/.test(err) ).toBeTruthy() } } return <div>{data.get()}</div> }) render(<Comp />) data.set(3) _resetGlobalState() }) test("observer component can be injected", () => { const msg: Array<any> = [] const baseWarn = console.warn console.warn = m => msg.push(m) inject("foo")( observer( class T extends React.Component { render() { return null } } ) ) // N.B, the injected component will be observer since mobx-react 4.0! inject(() => {})( observer( class T extends React.Component { render() { return null } } ) ) expect(msg.length).toBe(0) console.warn = baseWarn }) test("correctly wraps display name of child component", () => { const A = observer( class ObserverClass extends React.Component { render() { return null } } ) const B: React.FunctionComponent<any> = observer(function StatelessObserver() { return null }) expect(A.name).toEqual("ObserverClass") expect(B.displayName).toEqual("StatelessObserver") }) describe("124 - react to changes in this.props via computed", () => { class T extends React.Component<any, any> { @computed get computedProp() { return this.props.x } render() { return ( <span> x: {this.computedProp} </span> ) } } const Comp = observer(T) class Parent extends React.Component { state = { v: 1 } render() { return ( <div onClick={() => this.setState({ v: 2 })}> <Comp x={this.state.v} /> </div> ) } } test("init state is correct", () => { const { container } = render(<Parent />) expect(container).toHaveTextContent("x:1") }) test("change after click", () => { const { container } = render(<Parent />) container.querySelector("div")!.click() expect(container).toHaveTextContent("x:2") }) }) // Test on skip: since all reactions are now run in batched updates, the original issues can no longer be reproduced //this test case should be deprecated? test("should stop updating if error was thrown in render (#134)", () => { const data = observable.box(0) let renderingsCount = 0 let lastOwnRenderCount = 0 const errors: Array<any> = [] class Outer extends React.Component { state = { hasError: false } render() { return this.state.hasError ? <div>Error!</div> : <div>{this.props.children}</div> } static getDerivedStateFromError() { return { hasError: true } } componentDidCatch(error, info) { errors.push(error.toString().split("\n")[0], info) } } const Comp = observer( class X extends React.Component { ownRenderCount = 0 render() { lastOwnRenderCount = ++this.ownRenderCount renderingsCount++ if (data.get() === 2) { throw new Error("Hello") } return <div /> } } ) render( <Outer> <Comp /> </Outer> ) // Check this // @ts-ignore expect(getObserverTree(data).observers!.length).toBe(1) data.set(1) expect(renderingsCount).toBe(2) expect(lastOwnRenderCount).toBe(2) withConsole(() => { data.set(2) }) // @ts-ignore expect(getObserverTree(data).observers).toBe(undefined) data.set(3) data.set(4) data.set(2) data.set(5) expect(errors).toMatchSnapshot() expect(lastOwnRenderCount).toBe(4) expect(renderingsCount).toBe(4) }) describe("should render component even if setState called with exactly the same props", () => { let renderCount const Comp = observer( class T extends React.Component { onClick = () => { this.setState({}) } render() { renderCount++ return <div onClick={this.onClick} id="clickableDiv" /> } } ) beforeEach(() => { renderCount = 0 }) test("renderCount === 1", () => { render(<Comp />) expect(renderCount).toBe(1) }) test("after click once renderCount === 2", () => { const { container } = render(<Comp />) const clickableDiv = container.querySelector("#clickableDiv") as HTMLElement clickableDiv.click() expect(renderCount).toBe(2) }) test("after click twice renderCount === 3", () => { const { container } = render(<Comp />) const clickableDiv = container.querySelector("#clickableDiv") as HTMLElement clickableDiv.click() clickableDiv.click() expect(renderCount).toBe(3) }) }) test("it rerenders correctly if some props are non-observables - 1", () => { let odata = observable({ x: 1 }) let data = { y: 1 } @observer class Comp extends React.Component<any, any> { @computed get computed() { // n.b: data.y would not rerender! shallowly new equal props are not stored return this.props.odata.x } render() { return ( <span onClick={stuff}> {this.props.odata.x}-{this.props.data.y}-{this.computed} </span> ) } } const Parent = observer( class Parent extends React.Component<any, any> { render() { // this.props.odata.x; return <Comp data={this.props.data} odata={this.props.odata} /> } } ) function stuff() { act(() => { data.y++ odata.x++ }) } const { container } = render(<Parent odata={odata} data={data} />) expect(container).toHaveTextContent("1-1-1") stuff() expect(container).toHaveTextContent("2-2-2") stuff() expect(container).toHaveTextContent("3-3-3") }) test("it rerenders correctly if some props are non-observables - 2", () => { let renderCount = 0 let odata = observable({ x: 1 }) @observer class Component extends React.PureComponent<any, any> { @computed get computed() { return this.props.data.y // should recompute, since props.data is changed } render() { renderCount++ return ( <span onClick={stuff}> {this.props.data.y}-{this.computed} </span> ) } } const Parent = observer(props => { let data = { y: props.odata.x } return <Component data={data} odata={props.odata} /> }) function stuff() { odata.x++ } const { container } = render(<Parent odata={odata} />) expect(renderCount).toBe(1) expect(container).toHaveTextContent("1-1") act(() => stuff()) expect(renderCount).toBe(2) expect(container).toHaveTextContent("2-2") act(() => stuff()) expect(renderCount).toBe(3) expect(container).toHaveTextContent("3-3") }) describe("Observer regions should react", () => { let data const Comp = () => ( <div> <Observer>{() => <span data-testid="inside-of-observer">{data.get()}</span>}</Observer> <span data-testid="outside-of-observer">{data.get()}</span> </div> ) beforeEach(() => { data = observable.box("hi") }) test("init state is correct", () => { const { queryByTestId } = render(<Comp />) expect(queryByTestId("inside-of-observer")).toHaveTextContent("hi") expect(queryByTestId("outside-of-observer")).toHaveTextContent("hi") }) test("set the data to hello", () => { const { queryByTestId } = render(<Comp />) data.set("hello") expect(queryByTestId("inside-of-observer")).toHaveTextContent("hello") expect(queryByTestId("outside-of-observer")).toHaveTextContent("hi") }) }) test("Observer should not re-render on shallow equal new props", () => { let childRendering = 0 let parentRendering = 0 const data = { x: 1 } const odata = observable({ y: 1 }) const Child = observer(({ data }) => { childRendering++ return <span>{data.x}</span> }) const Parent = observer(() => { parentRendering++ odata.y /// depend return <Child data={data} /> }) const { container } = render(<Parent />) expect(parentRendering).toBe(1) expect(childRendering).toBe(1) expect(container).toHaveTextContent("1") act(() => { odata.y++ }) expect(parentRendering).toBe(2) expect(childRendering).toBe(1) expect(container).toHaveTextContent("1") }) test("parent / childs render in the right order", () => { // See: https://jsfiddle.net/gkaemmer/q1kv7hbL/13/ let events: Array<any> = [] class User { @observable name = "User's name" } class Store { @observable user: User | null = new User() @action logout() { this.user = null } constructor() { makeObservable(this) } } function tryLogout() { try { // ReactDOM.unstable_batchedUpdates(() => { store.logout() expect(true).toBeTruthy() // }); } catch (e) { // t.fail(e) } } const store = new Store() const Parent = observer(() => { events.push("parent") if (!store.user) return <span>Not logged in.</span> return ( <div> <Child /> <button onClick={tryLogout}>Logout</button> </div> ) }) const Child = observer(() => { events.push("child") return <span>Logged in as: {store.user?.name}</span> }) render(<Parent />) tryLogout() expect(events).toEqual(["parent", "child", "parent"]) }) describe("use Observer inject and render sugar should work ", () => { test("use render without inject should be correct", () => { const Comp = () => ( <div> <Observer render={() => <span>{123}</span>} /> </div> ) const { container } = render(<Comp />) expect(container).toHaveTextContent("123") }) test("use children without inject should be correct", () => { const Comp = () => ( <div> <Observer>{() => <span>{123}</span>}</Observer> </div> ) const { container } = render(<Comp />) expect(container).toHaveTextContent("123") }) test("show error when using children and render at same time ", () => { const msg: Array<any> = [] const baseError = console.error console.error = m => msg.push(m) const Comp = () => ( <div> <Observer render={() => <span>{123}</span>}>{() => <span>{123}</span>}</Observer> </div> ) render(<Comp />) expect(msg.length).toBe(1) console.error = baseError }) }) test("use PureComponent", () => { const msg: Array<any> = [] const baseWarn = console.warn console.warn = m => msg.push(m) try { observer( class X extends React.PureComponent { return() { return <div /> } } ) expect(msg).toEqual([]) } finally { console.warn = baseWarn } }) test("static on function components are hoisted", () => { const Comp = () => <div /> Comp.foo = 3 const Comp2 = observer(Comp) expect(Comp2.foo).toBe(3) }) test("computed properties react to props", () => { jest.useFakeTimers() const seen: Array<any> = [] @observer class Child extends React.Component<any, any> { @computed get getPropX() { return this.props.x } render() { seen.push(this.getPropX) return <div>{this.getPropX}</div> } } class Parent extends React.Component { state = { x: 0 } render() { seen.push("parent") return <Child x={this.state.x} /> } componentDidMount() { setTimeout(() => this.setState({ x: 2 }), 100) } } const { container } = render(<Parent />) expect(container).toHaveTextContent("0") jest.runAllTimers() expect(container).toHaveTextContent("2") expect(seen).toEqual(["parent", 0, "parent", 2]) }) test("#692 - componentDidUpdate is triggered", () => { jest.useFakeTimers() let cDUCount = 0 @observer class Test extends React.Component<any, any> { @observable counter = 0 @action inc = () => this.counter++ constructor(props) { super(props) makeObservable(this) setTimeout(() => this.inc(), 300) } render() { return <p>{this.counter}</p> } componentDidUpdate() { cDUCount++ } } render(<Test />) expect(cDUCount).toBe(0) jest.runAllTimers() expect(cDUCount).toBe(1) }) // Not possible to properly test error catching (see ErrorCatcher) test.skip("#709 - applying observer on React.memo component", () => { const WithMemo = React.memo(() => { return null }) const Observed = observer(WithMemo) // @ts-ignore // eslint-disable-next-line no-undef render(<Observed />, { wrapper: ErrorCatcher }) }) test("#797 - replacing this.render should trigger a warning", () => { const warn = jest.spyOn(global.console, "warn") @observer class Component extends React.Component { render() { return <div /> } swapRenderFunc() { this.render = () => { return <span /> } } } const compRef = React.createRef<Component>() const { unmount } = render(<Component ref={compRef} />) compRef.current?.swapRenderFunc() unmount() expect(warn).toHaveBeenCalled() }) test("Redeclaring an existing observer component as an observer should log a warning", () => { const warn = jest.spyOn(global.console, "warn") @observer class AlreadyObserver extends React.Component<any, any> { render() { return <div /> } } observer(AlreadyObserver) expect(warn).toHaveBeenCalled() })
5,106
0
petrpan-code/mobxjs/mobx-react
petrpan-code/mobxjs/mobx-react/test/propTypes.test.ts
import PropTypes from "prop-types" import { PropTypes as MRPropTypes } from "../src" import { observable } from "mobx" // Cause `checkPropTypes` caches errors and doesn't print them twice.... // https://github.com/facebook/prop-types/issues/91 let testComponentId = 0 function typeCheckFail(declaration, value, message) { const baseError = console.error let error = "" console.error = msg => { error = msg } const props = { testProp: value } const propTypes = { testProp: declaration } const compId = "testComponent" + ++testComponentId PropTypes.checkPropTypes(propTypes, props, "prop", compId) error = error.replace(compId, "testComponent") expect(error).toBe("Warning: Failed prop type: " + message) console.error = baseError } function typeCheckFailRequiredValues(declaration) { const baseError = console.error let error = "" console.error = msg => { error = msg } const propTypes = { testProp: declaration } const specifiedButIsNullMsg = /but its value is `null`\./ const unspecifiedMsg = /but its value is `undefined`\./ const props1 = { testProp: null } PropTypes.checkPropTypes(propTypes, props1, "testProp", "testComponent" + ++testComponentId) expect(specifiedButIsNullMsg.test(error)).toBeTruthy() error = "" const props2 = { testProp: undefined } PropTypes.checkPropTypes(propTypes, props2, "testProp", "testComponent" + ++testComponentId) expect(unspecifiedMsg.test(error)).toBeTruthy() error = "" const props3 = {} PropTypes.checkPropTypes(propTypes, props3, "testProp", "testComponent" + ++testComponentId) expect(unspecifiedMsg.test(error)).toBeTruthy() console.error = baseError } function typeCheckPass(declaration: any, value?: any) { const props = { testProp: value } const error = PropTypes.checkPropTypes( { testProp: declaration }, props, "testProp", "testComponent" + ++testComponentId ) expect(error).toBeUndefined() } test("Valid values", () => { typeCheckPass(MRPropTypes.observableArray, observable([])) typeCheckPass(MRPropTypes.observableArrayOf(PropTypes.string), observable([""])) typeCheckPass(MRPropTypes.arrayOrObservableArray, observable([])) typeCheckPass(MRPropTypes.arrayOrObservableArray, []) typeCheckPass(MRPropTypes.arrayOrObservableArrayOf(PropTypes.string), observable([""])) typeCheckPass(MRPropTypes.arrayOrObservableArrayOf(PropTypes.string), [""]) typeCheckPass(MRPropTypes.observableObject, observable({})) typeCheckPass(MRPropTypes.objectOrObservableObject, {}) typeCheckPass(MRPropTypes.objectOrObservableObject, observable({})) typeCheckPass(MRPropTypes.observableMap, observable(observable.map({}, { deep: false }))) }) test("should be implicitly optional and not warn", () => { typeCheckPass(MRPropTypes.observableArray) typeCheckPass(MRPropTypes.observableArrayOf(PropTypes.string)) typeCheckPass(MRPropTypes.arrayOrObservableArray) typeCheckPass(MRPropTypes.arrayOrObservableArrayOf(PropTypes.string)) typeCheckPass(MRPropTypes.observableObject) typeCheckPass(MRPropTypes.objectOrObservableObject) typeCheckPass(MRPropTypes.observableMap) }) test("should warn for missing required values, function (test)", () => { typeCheckFailRequiredValues(MRPropTypes.observableArray.isRequired) typeCheckFailRequiredValues(MRPropTypes.observableArrayOf(PropTypes.string).isRequired) typeCheckFailRequiredValues(MRPropTypes.arrayOrObservableArray.isRequired) typeCheckFailRequiredValues(MRPropTypes.arrayOrObservableArrayOf(PropTypes.string).isRequired) typeCheckFailRequiredValues(MRPropTypes.observableObject.isRequired) typeCheckFailRequiredValues(MRPropTypes.objectOrObservableObject.isRequired) typeCheckFailRequiredValues(MRPropTypes.observableMap.isRequired) }) test("should fail date and regexp correctly", () => { typeCheckFail( MRPropTypes.observableObject, new Date(), "Invalid prop `testProp` of type `date` supplied to " + "`testComponent`, expected `mobx.ObservableObject`." ) typeCheckFail( MRPropTypes.observableArray, /please/, "Invalid prop `testProp` of type `regexp` supplied to " + "`testComponent`, expected `mobx.ObservableArray`." ) }) test("observableArray", () => { typeCheckFail( MRPropTypes.observableArray, [], "Invalid prop `testProp` of type `array` supplied to " + "`testComponent`, expected `mobx.ObservableArray`." ) typeCheckFail( MRPropTypes.observableArray, "", "Invalid prop `testProp` of type `string` supplied to " + "`testComponent`, expected `mobx.ObservableArray`." ) }) test("arrayOrObservableArray", () => { typeCheckFail( MRPropTypes.arrayOrObservableArray, "", "Invalid prop `testProp` of type `string` supplied to " + "`testComponent`, expected `mobx.ObservableArray` or javascript `array`." ) }) test("observableObject", () => { typeCheckFail( MRPropTypes.observableObject, {}, "Invalid prop `testProp` of type `object` supplied to " + "`testComponent`, expected `mobx.ObservableObject`." ) typeCheckFail( MRPropTypes.observableObject, "", "Invalid prop `testProp` of type `string` supplied to " + "`testComponent`, expected `mobx.ObservableObject`." ) }) test("objectOrObservableObject", () => { typeCheckFail( MRPropTypes.objectOrObservableObject, "", "Invalid prop `testProp` of type `string` supplied to " + "`testComponent`, expected `mobx.ObservableObject` or javascript `object`." ) }) test("observableMap", () => { typeCheckFail( MRPropTypes.observableMap, {}, "Invalid prop `testProp` of type `object` supplied to " + "`testComponent`, expected `mobx.ObservableMap`." ) }) test("observableArrayOf", () => { typeCheckFail( MRPropTypes.observableArrayOf(PropTypes.string), 2, "Invalid prop `testProp` of type `number` supplied to " + "`testComponent`, expected `mobx.ObservableArray`." ) typeCheckFail( MRPropTypes.observableArrayOf(PropTypes.string), observable([2]), "Invalid prop `testProp[0]` of type `number` supplied to " + "`testComponent`, expected `string`." ) typeCheckFail( MRPropTypes.observableArrayOf({ foo: (MRPropTypes as any).string } as any), { foo: "bar" }, "Property `testProp` of component `testComponent` has invalid PropType notation." ) }) test("arrayOrObservableArrayOf", () => { typeCheckFail( MRPropTypes.arrayOrObservableArrayOf(PropTypes.string), 2, "Invalid prop `testProp` of type `number` supplied to " + "`testComponent`, expected `mobx.ObservableArray` or javascript `array`." ) typeCheckFail( MRPropTypes.arrayOrObservableArrayOf(PropTypes.string), observable([2]), "Invalid prop `testProp[0]` of type `number` supplied to " + "`testComponent`, expected `string`." ) typeCheckFail( MRPropTypes.arrayOrObservableArrayOf(PropTypes.string), [2], "Invalid prop `testProp[0]` of type `number` supplied to " + "`testComponent`, expected `string`." ) // TODO: typeCheckFail( MRPropTypes.arrayOrObservableArrayOf({ foo: (MRPropTypes as any).string } as any), { foo: "bar" }, "Property `testProp` of component `testComponent` has invalid PropType notation." ) })
5,107
0
petrpan-code/mobxjs/mobx-react
petrpan-code/mobxjs/mobx-react/test/stateless.test.tsx
import React from "react" import PropTypes from "prop-types" import { observer, PropTypes as MRPropTypes } from "../src" import { render, act } from "@testing-library/react" import { observable } from "mobx" const StatelessComp = ({ testProp }) => <div>result: {testProp}</div> StatelessComp.propTypes = { testProp: PropTypes.string } StatelessComp.defaultProps = { testProp: "default value for prop testProp" } describe("stateless component with propTypes", () => { const StatelessCompObserver: React.FunctionComponent<any> = observer(StatelessComp) test("default property value should be propagated", () => { expect(StatelessComp.defaultProps.testProp).toBe("default value for prop testProp") expect(StatelessCompObserver.defaultProps!.testProp).toBe("default value for prop testProp") }) const originalConsoleError = console.error let beenWarned = false console.error = () => (beenWarned = true) // eslint-disable-next-line no-unused-vars const wrapper = <StatelessCompObserver testProp={10} /> console.error = originalConsoleError test("an error should be logged with a property type warning", () => { expect(beenWarned).toBeTruthy() }) test("render test correct", async () => { const { container } = render(<StatelessCompObserver testProp="hello world" />) expect(container.textContent).toBe("result: hello world") }) }) test("stateless component with context support", () => { const C = React.createContext<any>({}) const StateLessCompWithContext = () => ( <C.Consumer>{value => <div>context: {value.testContext}</div>}</C.Consumer> ) const StateLessCompWithContextObserver = observer(StateLessCompWithContext) const ContextProvider = () => ( <C.Provider value={{ testContext: "hello world" }}> <StateLessCompWithContextObserver /> </C.Provider> ) const { container } = render(<ContextProvider />) expect(container.textContent).toBe("context: hello world") }) test("component with observable propTypes", () => { class Comp extends React.Component { render() { return null } static propTypes = { a1: MRPropTypes.observableArray, a2: MRPropTypes.arrayOrObservableArray } } const originalConsoleError = console.error const warnings: Array<any> = [] console.error = msg => warnings.push(msg) // eslint-disable-next-line no-unused-vars const firstWrapper = <Comp a1={[]} a2={[]} /> expect(warnings.length).toBe(1) // eslint-disable-next-line no-unused-vars const secondWrapper = <Comp a1={observable([])} a2={observable([])} /> expect(warnings.length).toBe(1) console.error = originalConsoleError }) describe("stateless component with forwardRef", () => { const a = observable({ x: 1 }) const ForwardRefCompObserver: React.ForwardRefExoticComponent<any> = observer( React.forwardRef(({ testProp }, ref) => { return ( <div> result: {testProp}, {ref ? "got ref" : "no ref"}, a.x: {a.x} </div> ) }) ) test("render test correct", () => { const { container } = render( <ForwardRefCompObserver testProp="hello world" ref={React.createRef()} /> ) expect(container).toMatchSnapshot() }) test("is reactive", () => { const { container } = render( <ForwardRefCompObserver testProp="hello world" ref={React.createRef()} /> ) act(() => { a.x++ }) expect(container).toMatchSnapshot() }) })
5,108
0
petrpan-code/mobxjs/mobx-react
petrpan-code/mobxjs/mobx-react/test/symbol.test.tsx
import React from "react" import { observer } from "../src" import { render } from "@testing-library/react" import { newSymbol } from "../src/utils/utils" // eslint-disable-next-line no-undef delete global.Symbol test("work without Symbol", () => { const Component1 = observer( class extends React.Component { render() { return null } } ) render(<Component1 />) }) test("cache newSymbol created Symbols", () => { const symbol1 = newSymbol("name") const symbol2 = newSymbol("name") expect(symbol1).toEqual(symbol2) })
5,109
0
petrpan-code/mobxjs/mobx-react
petrpan-code/mobxjs/mobx-react/test/transactions.test.tsx
import React from "react" import { autorun, computed, observable, transaction } from "mobx" import { observer } from "../src" import { render } from "@testing-library/react" test("mobx issue 50", async () => { const foo = { a: observable.box(true), b: observable.box(false), c: computed(function() { // console.log("evaluate c") return foo.b.get() }) } function flipStuff() { transaction(() => { foo.a.set(!foo.a.get()) foo.b.set(!foo.b.get()) }) } let asText = "" autorun(() => (asText = [foo.a.get(), foo.b.get(), foo.c.get()].join(":"))) const Test = observer( class Test extends React.Component { render() { return <div id="x">{[foo.a.get(), foo.b.get(), foo.c.get()].join(",")}</div> } } ) render(<Test />) // Flip a and b. This will change c. flipStuff() expect(asText).toBe("false:true:true") expect(document.getElementById("x")!.innerHTML).toBe("false,true,true") }) test("ReactDOM.render should respect transaction", () => { const a = observable.box(2) const loaded = observable.box(false) const valuesSeen: Array<number> = [] const Component = observer(() => { valuesSeen.push(a.get()) if (loaded.get()) return <div>{a.get()}</div> else return <div>loading</div> }) const { container } = render(<Component />) transaction(() => { a.set(3) a.set(4) loaded.set(true) }) expect(container.textContent).toBe("4") expect(valuesSeen.sort()).toEqual([2, 4].sort()) }) test("ReactDOM.render in transaction should succeed", () => { const a = observable.box(2) const loaded = observable.box(false) const valuesSeen: Array<number> = [] const Component = observer(() => { valuesSeen.push(a.get()) if (loaded.get()) return <div>{a.get()}</div> else return <div>loading</div> }) let container transaction(() => { a.set(3) container = render(<Component />).container a.set(4) loaded.set(true) }) expect(container.textContent).toBe("4") expect(valuesSeen.sort()).toEqual([3, 4].sort()) })
5,110
0
petrpan-code/mobxjs/mobx-react
petrpan-code/mobxjs/mobx-react/test/tsconfig.json
{ "version": "1.7.5", "compilerOptions": { "esModuleInterop": true, "experimentalDecorators": true, "jsx": "react", "lib": ["es6", "dom"], "module": "commonjs", "noEmit": true, "noUnusedParameters": true, "noImplicitAny": false, "rootDir": "../../", "strict": true, "target": "es5", }, "exclude": [ ] }
5,111
0
petrpan-code/mobxjs/mobx-react/test
petrpan-code/mobxjs/mobx-react/test/__snapshots__/observer.test.tsx.snap
// Jest Snapshot v1, https://goo.gl/fbAQLP exports[`issue 12 1`] = ` <div> <div> <span> coffee ! </span> <span> tea </span> </div> </div> `; exports[`issue 12 2`] = ` <div> <div> <span> soup </span> </div> </div> `; exports[`should stop updating if error was thrown in render (#134) 1`] = ` Array [ "Error: Hello", Object { "componentStack": " in X in div (created by Outer) in Outer", }, ] `;
5,112
0
petrpan-code/mobxjs/mobx-react/test
petrpan-code/mobxjs/mobx-react/test/__snapshots__/stateless.test.tsx.snap
// Jest Snapshot v1, https://goo.gl/fbAQLP exports[`stateless component with forwardRef is reactive 1`] = ` <div> <div> result: hello world , got ref , a.x: 2 </div> </div> `; exports[`stateless component with forwardRef render test correct 1`] = ` <div> <div> result: hello world , got ref , a.x: 1 </div> </div> `;
5,252
0
petrpan-code/vadimdemedes/ink/examples
petrpan-code/vadimdemedes/ink/examples/jest/test.tsx
import React from 'react'; import {Box, Text} from '../../src/index.js'; const getBackgroundForStatus = (status: string): string | undefined => { switch (status) { case 'runs': { return 'yellow'; } case 'pass': { return 'green'; } case 'fail': { return 'red'; } default: { return undefined; } } }; type Props = { readonly status: string; readonly path: string; }; function Test({status, path}: Props) { return ( <Box> <Text color="black" backgroundColor={getBackgroundForStatus(status)}> {` ${status.toUpperCase()} `} </Text> <Box marginLeft={1}> <Text dimColor>{path.split('/')[0]}/</Text> <Text bold color="white"> {path.split('/')[1]} </Text> </Box> </Box> ); } export default Test;
5,336
0
petrpan-code/vadimdemedes/ink
petrpan-code/vadimdemedes/ink/test/tsconfig.json
{ "extends": "../tsconfig.json", "include": ["."] }
5,395
0
petrpan-code/doczjs/docz/core/docz-core
petrpan-code/doczjs/docz/core/docz-core/__tests__/config.test.ts
import * as path from 'path' import { setArgs } from '../src/config/argv' import { getBaseConfig } from '../src/config/docz' import { getThemesDir } from '../src/config/paths' import yargs from 'yargs' describe('config.argv & config.docz', () => { test('works', () => { const { argv } = setArgs(yargs) // expect(argv).toMatchInlineSnapshot(`undefined`) //@ts-ignore getBaseConfig(argv, {}) // expect(c) }) }) describe('getThemeDir', () => { test('returns src/ for default config', () => { const { argv } = setArgs(yargs) //@ts-ignore const config = getBaseConfig(argv, {}) expect(getThemesDir(config)).toBe(path.join(config.root, '/src')) }) test('returns correct path for custom themesDir entry', () => { const { argv } = setArgs(yargs) //@ts-ignore const config = getBaseConfig(argv, { themesDir: 'theme' }) expect(getThemesDir(config)).toBe(path.join(config.root, '/theme')) }) test('custom themesDir entries with trailing slashes are handled correctly', () => { const { argv } = setArgs(yargs) //@ts-ignore const config = getBaseConfig(argv, { themesDir: 'theme/' }) expect(getThemesDir(config)).toBe(path.join(config.root, '/theme')) }) })
5,396
0
petrpan-code/doczjs/docz/core/docz-core
petrpan-code/doczjs/docz/core/docz-core/__tests__/entries.test.ts
import { Entries } from '../src/lib/Entries' import { getTestConfig } from '../src/test-utils' describe('Entries', () => { test('get entries', async () => { const config = getTestConfig() const entries = new Entries(config) expect(entries).toBeTruthy() }) })
5,397
0
petrpan-code/doczjs/docz/core/docz-core
petrpan-code/doczjs/docz/core/docz-core/__tests__/props.test.ts
import * as fs from 'fs-extra' import { getPattern, initial } from '../src/states/props' import { readCacheFile } from '../src/utils/docgen/typescript' import { getTestConfig, mockedParams } from '../src/test-utils' describe('props', () => { beforeEach(() => { if (fs.existsSync('./.docz/.cache/propsParser.json')) { fs.unlinkSync('./.docz/.cache/propsParser.json') } }) describe('typescript', () => { test('should set props from typescript files', async () => { const config = getTestConfig() const pattern = getPattern(config) const data = initial(config, pattern) const params = mockedParams() await data(params) expect(params.getState().props.length).toBeGreaterThan(0) }) test('should set correct key on parsed typescript files', async () => { const config = getTestConfig() const pattern = getPattern(config) const data = initial(config, pattern) const params = mockedParams() await data(params) const expectedFirstPropName = '__fixtures__/Label.tsx' const firstProp = params.getState().props[0] expect(firstProp.key).toEqual(expectedFirstPropName) expect(firstProp.value).toBeTruthy() }) }) describe('javascript', () => { test('should set correct key on parsed javascript files', async () => { const config = getTestConfig({ typescript: undefined }) const pattern = getPattern(config) const data = initial(config, pattern) const params = mockedParams() await data(params) const expectedFirstPropName = '__fixtures__/Label.jsx' const firstProp = params.getState().props[0] expect(firstProp.key).toEqual(expectedFirstPropName) expect(firstProp.value).toBeTruthy() }) test('should set props from javascript files', async () => { const config = getTestConfig({ typescript: undefined }) const pattern = getPattern(config) const data = initial(config, pattern) const params = mockedParams() await data(params) expect(params.getState().props.length).toBeGreaterThan(0) }) test('should have props on javascript files', async () => { const config = getTestConfig({ typescript: undefined }) const pattern = getPattern(config) const data = initial(config, pattern) const params = mockedParams() await data(params) const firstProp = params.getState().props[0] expect(firstProp.value[0].props).toBeTruthy() }) }) describe('cache', () => { test('should have empty cache on start', async () => { const cache = readCacheFile() expect(cache).toBeNull() }) test('should set cache on loading props', async () => { const cache = readCacheFile() expect(cache).toBeNull() const config = getTestConfig() const pattern = getPattern(config) const data = initial(config, pattern) const params = mockedParams() await data(params) expect(readCacheFile()).not.toBeNull() }) }) })
5,398
0
petrpan-code/doczjs/docz/core/docz-core
petrpan-code/doczjs/docz/core/docz-core/__tests__/states.test.ts
import * as states from '../src/states/index' import { createConfigStateInput } from '../src/test-utils/data-bank' import { getBaseConfig } from '../src/config/docz' import * as paths from '../src/config/paths' import { Entries } from '../src/lib/Entries' import { setArgs } from '../src/config/argv' describe('states', () => { test('exports', () => { expect(states).toBeDefined() expect(typeof states.config).toEqual('function') expect(typeof states.entries).toEqual('function') expect(typeof states.props).toEqual('function') }) }) describe('states.config', () => { test('config returns valid state', () => { const state = states.config({}) expect(typeof state.close).toEqual('function') expect(typeof state.start).toEqual('function') expect(state.id).toEqual('config') state.close() }) test('config state writes config to state when started', async () => { const config = createConfigStateInput() const setState = jest.fn() const getState = jest.fn() const state = states.config(config) await state.start({ getState, setState }) delete config.paths delete config.src expect(setState).toBeCalledWith('config', expect.objectContaining(config)) state.close() }) }) describe('states.entries', () => { test('entries returns start-able state', async () => { const yargs = { argv: {}, option: jest.fn().mockImplementation((key, value) => { yargs.argv[value.alias ? value.alias : key] = value.default return yargs }), } const { argv } = setArgs(yargs) //@ts-ignore const config = { ...getBaseConfig(argv), paths } const entries = new Entries(config) const state = states.entries(entries, config) const setState = jest.fn() const getState = jest.fn() await state.start({ getState, setState }) expect(getState).toBeCalledWith() // expect(setState).toBeCalledWith('entries', []) state.close() }) })
5,473
0
petrpan-code/doczjs/docz/core/docz-utils
petrpan-code/doczjs/docz/core/docz-utils/__tests__/jsx.test.ts
import { removeTags } from '../src/jsx' describe('removeTags', () => { test('removes outer JSX tag', () => { expect( removeTags(` <Playground> <div>Some text</div> <p>Other text</p> </Playground> `) ).toMatchInlineSnapshot(` " <div>Some text</div> <p>Other text</p> " `) }) test('works when the closing tag is repeated in a comment', () => { expect( removeTags(` <Playground> {/* </Playground> */} <div>Some text</div> </Playground> `) ).toMatchInlineSnapshot(` " {/* </Playground> */} <div>Some text</div> " `) }) })
5,589
0
petrpan-code/doczjs/docz/core/rehype-docz
petrpan-code/doczjs/docz/core/rehype-docz/src/index.test.ts
import mdx from '@mdx-js/mdx' import remarkDocz from 'remark-docz' import plugin from './' const content = ` import { Playground } from 'docz' <Playground> {() => { const foo = 'foo' return ( <div>{foo}</div> ) }} </Playground> ` test('adding custom props on <Playground>', async () => { const result = await mdx(content, { remarkPlugins: [remarkDocz], rehypePlugins: [[plugin, { root: __dirname }]], }) expect(result).toMatch('__position={0}') expect(result).toMatchSnapshot() expect(result).toMatchSnapshot() })
5,592
0
petrpan-code/doczjs/docz/core/rehype-docz/src
petrpan-code/doczjs/docz/core/rehype-docz/src/__snapshots__/index.test.ts.snap
// Jest Snapshot v1, https://goo.gl/fbAQLP exports[`adding custom props on <Playground> 1`] = ` "/* @jsx mdx */ import { Playground } from 'docz' const makeShortcode = name => function MDXDefaultShortcode(props) { console.warn(\\"Component \\" + name + \\" was not imported, exported, or provided by MDXProvider as global scope\\") return <div {...props}/> }; const layoutProps = { }; const MDXLayout = \\"wrapper\\" export default function MDXContent({ components, ...props }) { return <MDXLayout {...layoutProps} {...props} components={components} mdxType=\\"MDXLayout\\"> <Playground __position={0} __code={'() => {\\\\n const foo = \\\\'foo\\\\'\\\\n return <div>{foo}</div>\\\\n}'} __scope={{ props, Playground }} mdxType=\\"Playground\\"> {() => { const foo = 'foo'; return <div>{foo}</div>; }} </Playground> </MDXLayout>; } ; MDXContent.isMDXComponent = true;" `; exports[`adding custom props on <Playground> 2`] = ` "/* @jsx mdx */ import { Playground } from 'docz' const makeShortcode = name => function MDXDefaultShortcode(props) { console.warn(\\"Component \\" + name + \\" was not imported, exported, or provided by MDXProvider as global scope\\") return <div {...props}/> }; const layoutProps = { }; const MDXLayout = \\"wrapper\\" export default function MDXContent({ components, ...props }) { return <MDXLayout {...layoutProps} {...props} components={components} mdxType=\\"MDXLayout\\"> <Playground __position={0} __code={'() => {\\\\n const foo = \\\\'foo\\\\'\\\\n return <div>{foo}</div>\\\\n}'} __scope={{ props, Playground }} mdxType=\\"Playground\\"> {() => { const foo = 'foo'; return <div>{foo}</div>; }} </Playground> </MDXLayout>; } ; MDXContent.isMDXComponent = true;" `;
5,603
0
petrpan-code/doczjs/docz/core/remark-docz
petrpan-code/doczjs/docz/core/remark-docz/src/index.test.ts
import mdx from '@mdx-js/mdx' import plugin from './' const content = ` import { Playground } from 'docz' <Playground> {() => { const foo = 'foo' return ( <div>{foo}</div> ) }} </Playground> ` test('rendering children as function', async () => { const result = await mdx(content, { remarkPlugins: [plugin] }) expect(result).toMatchSnapshot() })
5,606
0
petrpan-code/doczjs/docz/core/remark-docz/src
petrpan-code/doczjs/docz/core/remark-docz/src/__snapshots__/index.test.ts.snap
// Jest Snapshot v1, https://goo.gl/fbAQLP exports[`rendering children as function 1`] = ` "/* @jsx mdx */ import { Playground } from 'docz' const makeShortcode = name => function MDXDefaultShortcode(props) { console.warn(\\"Component \\" + name + \\" was not imported, exported, or provided by MDXProvider as global scope\\") return <div {...props}/> }; const layoutProps = { }; const MDXLayout = \\"wrapper\\" export default function MDXContent({ components, ...props }) { return <MDXLayout {...layoutProps} {...props} components={components} mdxType=\\"MDXLayout\\"> <Playground mdxType=\\"Playground\\"> {() => { const foo = 'foo'; return <div>{foo}</div>; }} </Playground> </MDXLayout>; } ; MDXContent.isMDXComponent = true;" `;
5,629
0
petrpan-code/doczjs/docz/examples/create-react-app-ts
petrpan-code/doczjs/docz/examples/create-react-app-ts/src/App.test.tsx
import React from 'react'; import { render } from '@testing-library/react'; import App from './App'; test('renders learn react link', () => { const { getByText } = render(<App />); const linkElement = getByText(/learn react/i); expect(linkElement).toBeInTheDocument(); });
5,962
0
petrpan-code/doczjs/docz/other-packages/e2e-tests
petrpan-code/doczjs/docz/other-packages/e2e-tests/__tests__/test.ts
import { Selector } from 'testcafe' const getByTestId = async (testId: string) => { return await Selector(`[data-testid=${testId}]`) } fixture`Renders a valid app`.page`http://localhost:3000/` test('Renders the right layout and nav', async t => { const layout = await getByTestId('layout') await t.expect(layout.exists).eql(true) const header = await getByTestId('header') await t.expect(header.exists).eql(true) const sidebar = await getByTestId('sidebar') await t.expect(sidebar.exists).eql(true) const logo = await getByTestId('logo') await t.expect(logo.exists).eql(true) const navGroup = await getByTestId('nav-group') await t.expect(navGroup.exists).eql(true) await t.navigateTo('/src-components-alert') const playground = await getByTestId('playground') await t.expect(playground.count).eql(2) const livePreview = await getByTestId('live-preview') await t.expect(livePreview.count).eql(2) const liveEditor = await getByTestId('live-editor') await t.expect(liveEditor.count).eql(2) }) test('Render props', async t => { await t.navigateTo('/src-components-alert') const prop = await getByTestId('prop') await t.expect(prop.exists).eql(true) await t.expect(prop.count).eql(1) })
6,076
0
petrpan-code/reduxjs/react-redux
petrpan-code/reduxjs/react-redux/test/tsconfig.test.json
{ "compilerOptions": { "allowSyntheticDefaultImports": true, "esModuleInterop": true, "module": "esnext", "moduleResolution": "node", "emitDeclarationOnly": false, "declaration": false, "strict": true, "noEmit": true, "target": "es2018", "jsx": "react", "baseUrl": ".", "skipLibCheck": true, "noImplicitReturns": false, "experimentalDecorators": true, } }