level_0
int64
0
10k
index
int64
0
0
repo_id
stringlengths
22
152
file_path
stringlengths
41
203
content
stringlengths
11
11.5M
1,292
0
petrpan-code/facebook/docusaurus/packages/docusaurus-plugin-content-docs/src/sidebars/__tests__
petrpan-code/facebook/docusaurus/packages/docusaurus-plugin-content-docs/src/sidebars/__tests__/__snapshots__/index.test.ts.snap
// Jest Snapshot v1, https://goo.gl/fbAQLP exports[`loadSidebars loads sidebars with index-only categories 1`] = ` { "docs": [ { "collapsed": true, "collapsible": true, "items": [ { "id": "tutorials/tutorial-basics", "label": "tutorial-basics", "type": "doc", }, ], "label": "Tutorials", "link": undefined, "type": "category", }, { "id": "tutorials/tutorial-basics", "label": "index-only", "type": "doc", }, ], } `; exports[`loadSidebars loads sidebars with interspersed draft items 1`] = ` { "sidebar": [ { "id": "not-draft", "label": "index not draft", "type": "doc", }, { "collapsed": true, "collapsible": true, "items": [ { "id": "not-draft", "type": "doc", }, ], "label": "subitem not draft", "link": undefined, "type": "category", }, ], } `; exports[`loadSidebars sidebars link 1`] = ` { "docs": [ { "collapsed": true, "collapsible": true, "items": [ { "href": "https://github.com", "label": "category", "type": "link", }, ], "label": "Test", "link": undefined, "type": "category", }, ], } `; exports[`loadSidebars sidebars with category.collapsed property 1`] = ` { "docs": [ { "collapsed": true, "collapsible": true, "items": [ { "collapsed": false, "collapsible": true, "items": [ { "id": "doc1", "type": "doc", }, ], "label": "Introduction", "link": undefined, "type": "category", }, ], "label": "Test", "link": undefined, "type": "category", }, { "collapsed": true, "collapsible": true, "items": [ { "collapsed": false, "collapsible": true, "items": [ { "id": "doc2", "type": "doc", }, ], "label": "Powering MDX", "link": undefined, "type": "category", }, ], "label": "Reference", "link": undefined, "type": "category", }, ], } `; exports[`loadSidebars sidebars with category.collapsed property at first level 1`] = ` { "docs": [ { "collapsed": false, "collapsible": true, "items": [ { "id": "doc1", "type": "doc", }, ], "label": "Introduction", "link": undefined, "type": "category", }, { "collapsed": false, "collapsible": true, "items": [ { "id": "doc2", "type": "doc", }, ], "label": "Powering MDX", "link": undefined, "type": "category", }, ], } `; exports[`loadSidebars sidebars with deep level of category 1`] = ` { "docs": [ { "collapsed": true, "collapsible": true, "items": [ { "id": "a", "type": "doc", }, { "collapsed": true, "collapsible": true, "items": [ { "collapsed": true, "collapsible": true, "items": [ { "id": "c", "type": "doc", }, { "collapsed": true, "collapsible": true, "items": [ { "id": "d", "type": "doc", }, { "collapsed": true, "collapsible": true, "items": [ { "id": "e", "type": "doc", }, ], "label": "deeper more more", "link": undefined, "type": "category", }, ], "label": "level 4", "link": undefined, "type": "category", }, ], "label": "level 3", "link": undefined, "type": "category", }, { "id": "f", "type": "doc", }, ], "label": "level 2", "link": undefined, "type": "category", }, ], "label": "level 1", "link": undefined, "type": "category", }, ], } `; exports[`loadSidebars sidebars with first level not a category 1`] = ` { "docs": [ { "collapsed": true, "collapsible": true, "items": [ { "id": "greeting", "type": "doc", }, ], "label": "Getting Started", "link": undefined, "type": "category", }, { "id": "api", "type": "doc", }, ], } `; exports[`loadSidebars sidebars with known sidebar item type 1`] = ` { "docs": [ { "collapsed": true, "collapsible": true, "items": [ { "id": "foo/bar", "type": "doc", }, { "id": "foo/baz", "type": "doc", }, { "href": "https://github.com", "label": "GitHub", "type": "link", }, { "id": "hello", "type": "ref", }, ], "label": "Test", "link": undefined, "type": "category", }, { "collapsed": true, "collapsible": true, "items": [ { "id": "hello", "type": "doc", }, ], "label": "Guides", "link": undefined, "type": "category", }, ], } `; exports[`loadSidebars sidebars with some draft items 1`] = ` { "docs": [ { "collapsed": true, "collapsible": true, "items": [ { "id": "foo/bar", "type": "doc", }, { "href": "https://github.com", "label": "GitHub", "type": "link", }, ], "label": "Test", "link": undefined, "type": "category", }, ], } `; exports[`loadSidebars undefined path 1`] = ` { "defaultSidebar": [ { "collapsed": true, "collapsible": true, "items": [ { "id": "bar", "type": "doc", }, ], "label": "foo", "link": undefined, "type": "category", }, ], } `;
1,293
0
petrpan-code/facebook/docusaurus/packages/docusaurus-plugin-content-docs/src/sidebars/__tests__
petrpan-code/facebook/docusaurus/packages/docusaurus-plugin-content-docs/src/sidebars/__tests__/__snapshots__/normalization.test.ts.snap
// Jest Snapshot v1, https://goo.gl/fbAQLP exports[`normalization adds a translatable marker for labels defined in sidebars.js 1`] = ` { "sidebar": [ { "id": "google", "label": "Google", "translatable": true, "type": "doc", }, { "items": [ { "id": "doc1", "type": "doc", }, { "id": "doc2", "type": "doc", }, ], "label": "Category 1", "type": "category", }, { "items": [ { "id": "doc3", "type": "doc", }, { "id": "doc4", "type": "doc", }, { "id": "msft", "label": "Microsoft", "translatable": true, "type": "ref", }, ], "label": "Category 2", "type": "category", }, ], } `; exports[`normalization normalizes shorthands 1`] = ` { "sidebar": [ { "items": [ { "id": "doc1", "type": "doc", }, { "id": "doc2", "type": "doc", }, ], "label": "Category", "type": "category", }, { "items": [ { "items": [ { "id": "doc3", "type": "doc", }, { "id": "doc4", "type": "doc", }, ], "label": "Subcategory 1", "type": "category", }, { "items": [ { "id": "doc5", "type": "doc", }, { "id": "doc6", "type": "doc", }, ], "label": "Subcategory 2", "type": "category", }, ], "label": "Category 2", "type": "category", }, ], } `; exports[`normalization normalizes shorthands 2`] = ` { "sidebar": [ { "href": "https://google.com", "label": "Google", "type": "link", }, { "items": [ { "id": "doc1", "type": "doc", }, { "id": "doc2", "type": "doc", }, ], "label": "Category 1", "type": "category", }, { "items": [ { "id": "doc3", "type": "doc", }, { "id": "doc4", "type": "doc", }, ], "label": "Category 2", "type": "category", }, ], } `;
1,294
0
petrpan-code/facebook/docusaurus/packages/docusaurus-plugin-content-docs/src/sidebars/__tests__
petrpan-code/facebook/docusaurus/packages/docusaurus-plugin-content-docs/src/sidebars/__tests__/__snapshots__/postProcessor.test.ts.snap
// Jest Snapshot v1, https://goo.gl/fbAQLP exports[`postProcess corrects collapsed state inconsistencies 1`] = ` { "sidebar": [ { "collapsed": false, "collapsible": false, "items": [ { "id": "foo", "type": "doc", }, ], "label": "Category", "link": undefined, "type": "category", }, ], } `; exports[`postProcess corrects collapsed state inconsistencies 2`] = ` { "sidebar": [ { "collapsed": false, "collapsible": false, "items": [ { "id": "foo", "type": "doc", }, ], "label": "Category", "link": undefined, "type": "category", }, ], } `; exports[`postProcess corrects collapsed state inconsistencies 3`] = ` { "sidebar": [ { "collapsed": false, "collapsible": false, "items": [ { "id": "foo", "type": "doc", }, ], "label": "Category", "link": undefined, "type": "category", }, ], } `; exports[`postProcess filters draft items 1`] = ` { "sidebar": [ { "id": "another", "label": "Category", "type": "doc", }, ], } `; exports[`postProcess transforms category without subitems 1`] = ` { "sidebar": [ { "id": "doc ID", "label": "Category 2", "type": "doc", }, ], } `;
1,298
0
petrpan-code/facebook/docusaurus/packages/docusaurus-plugin-content-docs/src/versions
petrpan-code/facebook/docusaurus/packages/docusaurus-plugin-content-docs/src/versions/__tests__/index.test.ts
/** * Copyright (c) Facebook, Inc. and its affiliates. * * This source code is licensed under the MIT license found in the * LICENSE file in the root directory of this source tree. */ import {jest} from '@jest/globals'; import path from 'path'; import {DEFAULT_PLUGIN_ID} from '@docusaurus/utils'; import {readVersionsMetadata} from '../index'; import {DEFAULT_OPTIONS} from '../../options'; import type {I18n, LoadContext} from '@docusaurus/types'; import type { PluginOptions, VersionMetadata, } from '@docusaurus/plugin-content-docs'; const DefaultI18N: I18n = { path: 'i18n', currentLocale: 'en', locales: ['en'], defaultLocale: 'en', localeConfigs: {}, }; describe('readVersionsMetadata', () => { describe('simple site', () => { async function loadSite() { const simpleSiteDir = path.resolve( path.join(__dirname, '../../__tests__/__fixtures__', 'simple-site'), ); const defaultOptions: PluginOptions = { id: DEFAULT_PLUGIN_ID, ...DEFAULT_OPTIONS, }; const defaultContext = { siteDir: simpleSiteDir, baseUrl: '/', i18n: DefaultI18N, localizationDir: path.join(simpleSiteDir, 'i18n/en'), } as LoadContext; const vCurrent: VersionMetadata = { contentPath: path.join(simpleSiteDir, 'docs'), contentPathLocalized: path.join( simpleSiteDir, 'i18n/en/docusaurus-plugin-content-docs/current', ), isLast: true, routePriority: -1, sidebarFilePath: undefined, tagsPath: '/docs/tags', label: 'Next', versionName: 'current', path: '/docs', banner: null, badge: false, noIndex: false, className: 'docs-version-current', }; return {simpleSiteDir, defaultOptions, defaultContext, vCurrent}; } it('works', async () => { const {defaultOptions, defaultContext, vCurrent} = await loadSite(); const versionsMetadata = await readVersionsMetadata({ options: defaultOptions, context: defaultContext, }); expect(versionsMetadata).toEqual([vCurrent]); }); it('works with base url', async () => { const {defaultOptions, defaultContext, vCurrent} = await loadSite(); const versionsMetadata = await readVersionsMetadata({ options: defaultOptions, context: { ...defaultContext, baseUrl: '/myBaseUrl', }, }); expect(versionsMetadata).toEqual([ { ...vCurrent, path: '/myBaseUrl/docs', tagsPath: '/myBaseUrl/docs/tags', }, ]); }); it('works with current version config', async () => { const {defaultOptions, defaultContext, vCurrent} = await loadSite(); const versionsMetadata = await readVersionsMetadata({ options: { ...defaultOptions, versions: { current: { label: 'current-label', path: 'current-path', }, }, }, context: { ...defaultContext, baseUrl: '/myBaseUrl', }, }); expect(versionsMetadata).toEqual([ { ...vCurrent, path: '/myBaseUrl/docs/current-path', label: 'current-label', routePriority: undefined, sidebarFilePath: undefined, tagsPath: '/myBaseUrl/docs/current-path/tags', editUrl: undefined, editUrlLocalized: undefined, }, ]); }); it('throws with unknown lastVersion', async () => { const {defaultOptions, defaultContext} = await loadSite(); await expect( readVersionsMetadata({ options: {...defaultOptions, lastVersion: 'unknownVersionName'}, context: defaultContext, }), ).rejects.toThrowErrorMatchingInlineSnapshot( `"Docs option lastVersion: unknownVersionName is invalid. Available version names are: current"`, ); }); it('throws with unknown version configurations', async () => { const {defaultOptions, defaultContext} = await loadSite(); await expect( readVersionsMetadata({ options: { ...defaultOptions, versions: { current: {label: 'current'}, unknownVersionName1: {label: 'unknownVersionName1'}, unknownVersionName2: {label: 'unknownVersionName2'}, }, }, context: defaultContext, }), ).rejects.toThrowErrorMatchingInlineSnapshot( `"Invalid docs option "versions": unknown versions (unknownVersionName1,unknownVersionName2) found. Available version names are: current"`, ); }); it('throws with disableVersioning while single version', async () => { const {defaultOptions, defaultContext} = await loadSite(); await expect( readVersionsMetadata({ options: {...defaultOptions, disableVersioning: true}, context: defaultContext, }), ).rejects.toThrowErrorMatchingInlineSnapshot( `"Docs: using "disableVersioning: true" option on a non-versioned site does not make sense."`, ); }); it('throws without including current version', async () => { const {defaultOptions, defaultContext} = await loadSite(); await expect( readVersionsMetadata({ options: {...defaultOptions, includeCurrentVersion: false}, context: defaultContext, }), ).rejects.toThrowErrorMatchingInlineSnapshot( `"It is not possible to use docs without any version. No version is included because you have requested to not include <PROJECT_ROOT>/docs through "includeCurrentVersion: false", while the versions file is empty/non-existent."`, ); }); }); describe('versioned site, pluginId=default', () => { async function loadSite() { const versionedSiteDir = path.resolve( path.join(__dirname, '../../__tests__/__fixtures__', 'versioned-site'), ); const defaultOptions: PluginOptions = { id: DEFAULT_PLUGIN_ID, ...DEFAULT_OPTIONS, sidebarPath: path.join(versionedSiteDir, 'sidebars.json'), }; const defaultContext = { siteDir: versionedSiteDir, baseUrl: '/', i18n: DefaultI18N, localizationDir: path.join(versionedSiteDir, 'i18n/en'), } as LoadContext; const vCurrent: VersionMetadata = { contentPath: path.join(versionedSiteDir, 'docs'), contentPathLocalized: path.join( versionedSiteDir, 'i18n/en/docusaurus-plugin-content-docs/current', ), isLast: false, routePriority: undefined, sidebarFilePath: path.join(versionedSiteDir, 'sidebars.json'), tagsPath: '/docs/next/tags', label: 'Next', versionName: 'current', path: '/docs/next', banner: 'unreleased', badge: true, noIndex: false, className: 'docs-version-current', }; const v101: VersionMetadata = { contentPath: path.join( versionedSiteDir, 'versioned_docs/version-1.0.1', ), contentPathLocalized: path.join( versionedSiteDir, 'i18n/en/docusaurus-plugin-content-docs/version-1.0.1', ), isLast: true, routePriority: -1, sidebarFilePath: path.join( versionedSiteDir, 'versioned_sidebars/version-1.0.1-sidebars.json', ), tagsPath: '/docs/tags', label: '1.0.1', versionName: '1.0.1', path: '/docs', banner: null, badge: true, noIndex: false, className: 'docs-version-1.0.1', }; const v100: VersionMetadata = { contentPath: path.join( versionedSiteDir, 'versioned_docs/version-1.0.0', ), contentPathLocalized: path.join( versionedSiteDir, 'i18n/en/docusaurus-plugin-content-docs/version-1.0.0', ), isLast: false, routePriority: undefined, sidebarFilePath: path.join( versionedSiteDir, 'versioned_sidebars/version-1.0.0-sidebars.json', ), tagsPath: '/docs/1.0.0/tags', label: '1.0.0', versionName: '1.0.0', path: '/docs/1.0.0', banner: 'unmaintained', badge: true, noIndex: false, className: 'docs-version-1.0.0', }; const vWithSlugs: VersionMetadata = { contentPath: path.join( versionedSiteDir, 'versioned_docs/version-withSlugs', ), contentPathLocalized: path.join( versionedSiteDir, 'i18n/en/docusaurus-plugin-content-docs/version-withSlugs', ), isLast: false, routePriority: undefined, sidebarFilePath: path.join( versionedSiteDir, 'versioned_sidebars/version-withSlugs-sidebars.json', ), tagsPath: '/docs/withSlugs/tags', label: 'withSlugs', versionName: 'withSlugs', path: '/docs/withSlugs', banner: 'unmaintained', badge: true, noIndex: false, className: 'docs-version-withSlugs', }; return { versionedSiteDir, defaultOptions, defaultContext, vCurrent, v101, v100, vWithSlugs, }; } it('works', async () => { const {defaultOptions, defaultContext, vCurrent, v101, v100, vWithSlugs} = await loadSite(); const versionsMetadata = await readVersionsMetadata({ options: defaultOptions, context: defaultContext, }); expect(versionsMetadata).toEqual([vCurrent, v101, v100, vWithSlugs]); }); it('works with includeCurrentVersion=false', async () => { const {defaultOptions, defaultContext, v101, v100, vWithSlugs} = await loadSite(); const versionsMetadata = await readVersionsMetadata({ options: {...defaultOptions, includeCurrentVersion: false}, context: defaultContext, }); expect(versionsMetadata).toEqual([ // vCurrent removed v101, v100, vWithSlugs, ]); }); it('works with version options', async () => { const {defaultOptions, defaultContext, vCurrent, v101, v100, vWithSlugs} = await loadSite(); const versionsMetadata = await readVersionsMetadata({ options: { ...defaultOptions, lastVersion: '1.0.0', versions: { current: { path: 'current-path', banner: 'unmaintained', badge: false, className: 'custom-current-className', }, '1.0.0': { label: '1.0.0-label', banner: 'unreleased', }, }, }, context: defaultContext, }); expect(versionsMetadata).toEqual([ { ...vCurrent, tagsPath: '/docs/current-path/tags', path: '/docs/current-path', banner: 'unmaintained', badge: false, className: 'custom-current-className', }, { ...v101, isLast: false, routePriority: undefined, tagsPath: '/docs/1.0.1/tags', path: '/docs/1.0.1', banner: 'unreleased', }, { ...v100, isLast: true, routePriority: -1, tagsPath: '/docs/tags', label: '1.0.0-label', path: '/docs', banner: 'unreleased', }, vWithSlugs, ]); }); it('works with editUrl', async () => { const {defaultOptions, defaultContext, vCurrent, v101, v100, vWithSlugs} = await loadSite(); const versionsMetadata = await readVersionsMetadata({ options: { ...defaultOptions, editUrl: 'https://github.com/facebook/docusaurus/edit/main/website/', }, context: defaultContext, }); expect(versionsMetadata).toEqual([ { ...vCurrent, editUrl: 'https://github.com/facebook/docusaurus/edit/main/website/docs', editUrlLocalized: 'https://github.com/facebook/docusaurus/edit/main/website/i18n/en/docusaurus-plugin-content-docs/current', }, { ...v101, editUrl: 'https://github.com/facebook/docusaurus/edit/main/website/versioned_docs/version-1.0.1', editUrlLocalized: 'https://github.com/facebook/docusaurus/edit/main/website/i18n/en/docusaurus-plugin-content-docs/version-1.0.1', }, { ...v100, editUrl: 'https://github.com/facebook/docusaurus/edit/main/website/versioned_docs/version-1.0.0', editUrlLocalized: 'https://github.com/facebook/docusaurus/edit/main/website/i18n/en/docusaurus-plugin-content-docs/version-1.0.0', }, { ...vWithSlugs, editUrl: 'https://github.com/facebook/docusaurus/edit/main/website/versioned_docs/version-withSlugs', editUrlLocalized: 'https://github.com/facebook/docusaurus/edit/main/website/i18n/en/docusaurus-plugin-content-docs/version-withSlugs', }, ]); }); it('works with editUrl and editCurrentVersion=true', async () => { const {defaultOptions, defaultContext, vCurrent, v101, v100, vWithSlugs} = await loadSite(); const versionsMetadata = await readVersionsMetadata({ options: { ...defaultOptions, editUrl: 'https://github.com/facebook/docusaurus/edit/main/website/', editCurrentVersion: true, }, context: defaultContext, }); expect(versionsMetadata).toEqual([ { ...vCurrent, editUrl: 'https://github.com/facebook/docusaurus/edit/main/website/docs', editUrlLocalized: 'https://github.com/facebook/docusaurus/edit/main/website/i18n/en/docusaurus-plugin-content-docs/current', }, { ...v101, editUrl: 'https://github.com/facebook/docusaurus/edit/main/website/docs', editUrlLocalized: 'https://github.com/facebook/docusaurus/edit/main/website/i18n/en/docusaurus-plugin-content-docs/current', }, { ...v100, editUrl: 'https://github.com/facebook/docusaurus/edit/main/website/docs', editUrlLocalized: 'https://github.com/facebook/docusaurus/edit/main/website/i18n/en/docusaurus-plugin-content-docs/current', }, { ...vWithSlugs, editUrl: 'https://github.com/facebook/docusaurus/edit/main/website/docs', editUrlLocalized: 'https://github.com/facebook/docusaurus/edit/main/website/i18n/en/docusaurus-plugin-content-docs/current', }, ]); }); it('works with onlyIncludeVersions option', async () => { const {defaultOptions, defaultContext, v101, vWithSlugs} = await loadSite(); const versionsMetadata = await readVersionsMetadata({ options: { ...defaultOptions, // Order reversed on purpose: should not have any impact onlyIncludeVersions: [vWithSlugs.versionName, v101.versionName], }, context: defaultContext, }); expect(versionsMetadata).toEqual([v101, vWithSlugs]); }); it('works with disableVersioning', async () => { const {defaultOptions, defaultContext, vCurrent} = await loadSite(); const versionsMetadata = await readVersionsMetadata({ options: {...defaultOptions, disableVersioning: true}, context: defaultContext, }); expect(versionsMetadata).toEqual([ { ...vCurrent, isLast: true, routePriority: -1, tagsPath: '/docs/tags', path: '/docs', banner: null, badge: false, }, ]); }); it('throws with all versions disabled', async () => { const {defaultOptions, defaultContext} = await loadSite(); await expect( readVersionsMetadata({ options: { ...defaultOptions, includeCurrentVersion: false, disableVersioning: true, }, context: defaultContext, }), ).rejects.toThrowErrorMatchingInlineSnapshot( `"It is not possible to use docs without any version. No version is included because you have requested to not include <PROJECT_ROOT>/docs through "includeCurrentVersion: false", while versioning is disabled with "disableVersioning: true"."`, ); }); it('throws with empty onlyIncludeVersions', async () => { const {defaultOptions, defaultContext} = await loadSite(); await expect( readVersionsMetadata({ options: { ...defaultOptions, onlyIncludeVersions: [], }, context: defaultContext, }), ).rejects.toThrowErrorMatchingInlineSnapshot( `"Invalid docs option "onlyIncludeVersions": an empty array is not allowed, at least one version is needed."`, ); }); it('throws with unknown versions in onlyIncludeVersions', async () => { const {defaultOptions, defaultContext} = await loadSite(); await expect( readVersionsMetadata({ options: { ...defaultOptions, onlyIncludeVersions: ['unknownVersion1', 'unknownVersion2'], }, context: defaultContext, }), ).rejects.toThrowErrorMatchingInlineSnapshot( `"Invalid docs option "onlyIncludeVersions": unknown versions (unknownVersion1,unknownVersion2) found. Available version names are: current, 1.0.1, 1.0.0, withSlugs"`, ); }); it('throws with lastVersion not in onlyIncludeVersions', async () => { const {defaultOptions, defaultContext} = await loadSite(); await expect( readVersionsMetadata({ options: { ...defaultOptions, lastVersion: '1.0.1', onlyIncludeVersions: ['current', '1.0.0'], }, context: defaultContext, }), ).rejects.toThrowErrorMatchingInlineSnapshot( `"Invalid docs option "lastVersion": if you use both the "onlyIncludeVersions" and "lastVersion" options, then "lastVersion" must be present in the provided "onlyIncludeVersions" array."`, ); }); it('throws with invalid versions.json file', async () => { const {defaultOptions, defaultContext} = await loadSite(); const jsonMock = jest.spyOn(JSON, 'parse'); jsonMock.mockImplementationOnce(() => ({ invalid: 'json', })); await expect( readVersionsMetadata({ options: defaultOptions, context: defaultContext, }), ).rejects.toThrowErrorMatchingInlineSnapshot( `"The versions file should contain an array of version names! Found content: {"invalid":"json"}"`, ); jsonMock.mockImplementationOnce(() => [1.1]); await expect( readVersionsMetadata({ options: defaultOptions, context: defaultContext, }), ).rejects.toThrowErrorMatchingInlineSnapshot( `"Versions should be strings. Found type "number" for version 1.1."`, ); jsonMock.mockImplementationOnce(() => [' ']); await expect( readVersionsMetadata({ options: defaultOptions, context: defaultContext, }), ).rejects.toThrowErrorMatchingInlineSnapshot( `"Invalid version name " ": version name must contain at least one non-whitespace character."`, ); jsonMock.mockRestore(); }); }); describe('versioned site, pluginId=community', () => { async function loadSite() { const versionedSiteDir = path.resolve( path.join(__dirname, '../../__tests__/__fixtures__', 'versioned-site'), ); const defaultOptions: PluginOptions = { ...DEFAULT_OPTIONS, id: 'community', path: 'community', routeBasePath: 'communityBasePath', sidebarPath: path.join(versionedSiteDir, 'sidebars.json'), }; const defaultContext = { siteDir: versionedSiteDir, baseUrl: '/', i18n: DefaultI18N, localizationDir: path.join(versionedSiteDir, 'i18n/en'), } as LoadContext; const vCurrent: VersionMetadata = { contentPath: path.join(versionedSiteDir, 'community'), contentPathLocalized: path.join( versionedSiteDir, 'i18n/en/docusaurus-plugin-content-docs-community/current', ), isLast: false, routePriority: undefined, sidebarFilePath: path.join(versionedSiteDir, 'sidebars.json'), tagsPath: '/communityBasePath/next/tags', label: 'Next', versionName: 'current', path: '/communityBasePath/next', banner: 'unreleased', badge: true, noIndex: false, className: 'docs-version-current', }; const v100: VersionMetadata = { contentPath: path.join( versionedSiteDir, 'community_versioned_docs/version-1.0.0', ), contentPathLocalized: path.join( versionedSiteDir, 'i18n/en/docusaurus-plugin-content-docs-community/version-1.0.0', ), isLast: true, routePriority: -1, sidebarFilePath: path.join( versionedSiteDir, 'community_versioned_sidebars/version-1.0.0-sidebars.json', ), tagsPath: '/communityBasePath/tags', label: '1.0.0', versionName: '1.0.0', path: '/communityBasePath', banner: null, badge: true, noIndex: false, className: 'docs-version-1.0.0', }; return {versionedSiteDir, defaultOptions, defaultContext, vCurrent, v100}; } it('works', async () => { const {defaultOptions, defaultContext, vCurrent, v100} = await loadSite(); const versionsMetadata = await readVersionsMetadata({ options: defaultOptions, context: defaultContext, }); expect(versionsMetadata).toEqual([vCurrent, v100]); }); it('works with includeCurrentVersion=false', async () => { const {defaultOptions, defaultContext, v100} = await loadSite(); const versionsMetadata = await readVersionsMetadata({ options: {...defaultOptions, includeCurrentVersion: false}, context: defaultContext, }); expect(versionsMetadata).toEqual([ // vCurrent removed {...v100, badge: false}, ]); }); it('works with disableVersioning', async () => { const {defaultOptions, defaultContext, vCurrent} = await loadSite(); const versionsMetadata = await readVersionsMetadata({ options: {...defaultOptions, disableVersioning: true}, context: defaultContext, }); expect(versionsMetadata).toEqual([ { ...vCurrent, isLast: true, routePriority: -1, tagsPath: '/communityBasePath/tags', path: '/communityBasePath', banner: null, badge: false, }, ]); }); it('throws with all versions disabled', async () => { const {defaultOptions, defaultContext} = await loadSite(); await expect( readVersionsMetadata({ options: { ...defaultOptions, includeCurrentVersion: false, disableVersioning: true, }, context: defaultContext, }), ).rejects.toThrowErrorMatchingInlineSnapshot( `"It is not possible to use docs without any version. No version is included because you have requested to not include <PROJECT_ROOT>/community through "includeCurrentVersion: false", while versioning is disabled with "disableVersioning: true"."`, ); }); }); });
1,309
0
petrpan-code/facebook/docusaurus/packages/docusaurus-plugin-content-pages/src
petrpan-code/facebook/docusaurus/packages/docusaurus-plugin-content-pages/src/__tests__/index.test.ts
/** * Copyright (c) Facebook, Inc. and its affiliates. * * This source code is licensed under the MIT license found in the * LICENSE file in the root directory of this source tree. */ import path from 'path'; import {loadContext} from '@docusaurus/core/lib/server'; import {normalizePluginOptions} from '@docusaurus/utils-validation'; import pluginContentPages from '../index'; import {validateOptions} from '../options'; describe('docusaurus-plugin-content-pages', () => { it('loads simple pages', async () => { const siteDir = path.join(__dirname, '__fixtures__', 'website'); const context = await loadContext({siteDir}); const plugin = pluginContentPages( context, validateOptions({ validate: normalizePluginOptions, options: { path: 'src/pages', }, }), ); const pagesMetadata = await plugin.loadContent!(); expect(pagesMetadata).toMatchSnapshot(); }); it('loads simple pages with french translations', async () => { const siteDir = path.join(__dirname, '__fixtures__', 'website'); const context = await loadContext({siteDir, locale: 'fr'}); const plugin = pluginContentPages( context, validateOptions({ validate: normalizePluginOptions, options: { path: 'src/pages', }, }), ); const pagesMetadata = await plugin.loadContent!(); expect(pagesMetadata).toMatchSnapshot(); }); });
1,310
0
petrpan-code/facebook/docusaurus/packages/docusaurus-plugin-content-pages/src
petrpan-code/facebook/docusaurus/packages/docusaurus-plugin-content-pages/src/__tests__/options.test.ts
/** * Copyright (c) Facebook, Inc. and its affiliates. * * This source code is licensed under the MIT license found in the * LICENSE file in the root directory of this source tree. */ import {normalizePluginOptions} from '@docusaurus/utils-validation'; import {validateOptions, DEFAULT_OPTIONS} from '../options'; import type {Options} from '@docusaurus/plugin-content-pages'; function testValidate(options: Options) { return validateOptions({validate: normalizePluginOptions, options}); } const defaultOptions = { ...DEFAULT_OPTIONS, id: 'default', }; describe('normalizePagesPluginOptions', () => { it('returns default options for undefined user options', () => { expect(testValidate({})).toEqual(defaultOptions); }); it('fills in default options for partially defined user options', () => { expect(testValidate({path: 'src/foo'})).toEqual({ ...defaultOptions, path: 'src/foo', }); }); it('accepts correctly defined user options', () => { const userOptions = { path: 'src/my-pages', routeBasePath: '/my-pages', include: ['**/*.{js,jsx,ts,tsx}'], exclude: ['**/$*/'], }; expect(testValidate(userOptions)).toEqual({ ...defaultOptions, ...userOptions, }); }); it('rejects bad path inputs', () => { expect(() => { testValidate({ // @ts-expect-error: bad attribute path: 42, }); }).toThrowErrorMatchingInlineSnapshot(`""path" must be a string"`); }); it('empty routeBasePath replace default path("/")', () => { expect( testValidate({ routeBasePath: '', }), ).toEqual({ ...defaultOptions, routeBasePath: '/', }); }); });
1,327
0
petrpan-code/facebook/docusaurus/packages/docusaurus-plugin-content-pages/src/__tests__
petrpan-code/facebook/docusaurus/packages/docusaurus-plugin-content-pages/src/__tests__/__snapshots__/index.test.ts.snap
// Jest Snapshot v1, https://goo.gl/fbAQLP exports[`docusaurus-plugin-content-pages loads simple pages 1`] = ` [ { "permalink": "/", "source": "@site/src/pages/index.js", "type": "jsx", }, { "permalink": "/typescript", "source": "@site/src/pages/typescript.tsx", "type": "jsx", }, { "description": "Markdown index page", "frontMatter": {}, "permalink": "/hello/", "source": "@site/src/pages/hello/index.md", "title": "Index", "type": "mdx", "unlisted": false, }, { "description": "my MDX page", "frontMatter": { "description": "my MDX page", "title": "MDX page", }, "permalink": "/hello/mdxPage", "source": "@site/src/pages/hello/mdxPage.mdx", "title": "MDX page", "type": "mdx", "unlisted": false, }, { "permalink": "/hello/translatedJs", "source": "@site/src/pages/hello/translatedJs.js", "type": "jsx", }, { "description": "translated Markdown page", "frontMatter": {}, "permalink": "/hello/translatedMd", "source": "@site/src/pages/hello/translatedMd.md", "title": undefined, "type": "mdx", "unlisted": false, }, { "permalink": "/hello/world", "source": "@site/src/pages/hello/world.js", "type": "jsx", }, ] `; exports[`docusaurus-plugin-content-pages loads simple pages with french translations 1`] = ` [ { "permalink": "/fr/", "source": "@site/src/pages/index.js", "type": "jsx", }, { "permalink": "/fr/typescript", "source": "@site/src/pages/typescript.tsx", "type": "jsx", }, { "description": "Markdown index page", "frontMatter": {}, "permalink": "/fr/hello/", "source": "@site/src/pages/hello/index.md", "title": "Index", "type": "mdx", "unlisted": false, }, { "description": "my MDX page", "frontMatter": { "description": "my MDX page", "title": "MDX page", }, "permalink": "/fr/hello/mdxPage", "source": "@site/src/pages/hello/mdxPage.mdx", "title": "MDX page", "type": "mdx", "unlisted": false, }, { "permalink": "/fr/hello/translatedJs", "source": "@site/i18n/fr/docusaurus-plugin-content-pages/hello/translatedJs.js", "type": "jsx", }, { "description": "translated Markdown page (fr)", "frontMatter": {}, "permalink": "/fr/hello/translatedMd", "source": "@site/i18n/fr/docusaurus-plugin-content-pages/hello/translatedMd.md", "title": undefined, "type": "mdx", "unlisted": false, }, { "permalink": "/fr/hello/world", "source": "@site/src/pages/hello/world.js", "type": "jsx", }, ] `;
1,366
0
petrpan-code/facebook/docusaurus/packages/docusaurus-plugin-google-gtag/src
petrpan-code/facebook/docusaurus/packages/docusaurus-plugin-google-gtag/src/__tests__/options.test.ts
/** * Copyright (c) Facebook, Inc. and its affiliates. * * This source code is licensed under the MIT license found in the * LICENSE file in the root directory of this source tree. */ import {normalizePluginOptions} from '@docusaurus/utils-validation'; import { validateOptions, type PluginOptions, type Options, DEFAULT_OPTIONS, } from '../options'; import type {Validate} from '@docusaurus/types'; function testValidateOptions(options: Options) { return validateOptions({ validate: normalizePluginOptions as Validate<Options, PluginOptions>, options, }); } function validationResult(options: Options) { return { id: 'default', ...DEFAULT_OPTIONS, ...options, trackingID: typeof options.trackingID === 'string' ? [options.trackingID] : options.trackingID, }; } const MinimalConfig: Options = { trackingID: 'G-XYZ12345', }; describe('validateOptions', () => { it('throws for undefined options', () => { expect( // @ts-expect-error: TS should error () => testValidateOptions(undefined), ).toThrowErrorMatchingInlineSnapshot(`""trackingID" is required"`); }); it('throws for null options', () => { expect( // @ts-expect-error: TS should error () => testValidateOptions(null), ).toThrowErrorMatchingInlineSnapshot(`""value" must be of type object"`); }); it('throws for empty object options', () => { expect( // @ts-expect-error: TS should error () => testValidateOptions({}), ).toThrowErrorMatchingInlineSnapshot(`""trackingID" is required"`); }); it('throws for number options', () => { expect( // @ts-expect-error: TS should error () => testValidateOptions(42), ).toThrowErrorMatchingInlineSnapshot(`""value" must be of type object"`); }); it('throws for null trackingID', () => { expect( // @ts-expect-error: TS should error () => testValidateOptions({trackingID: null}), ).toThrowErrorMatchingInlineSnapshot( `""trackingID" does not match any of the allowed types"`, ); }); it('throws for number trackingID', () => { expect( // @ts-expect-error: TS should error () => testValidateOptions({trackingID: 42}), ).toThrowErrorMatchingInlineSnapshot( `""trackingID" does not match any of the allowed types"`, ); }); it('throws for empty trackingID', () => { expect(() => testValidateOptions({trackingID: ''}), ).toThrowErrorMatchingInlineSnapshot( `""trackingID" does not match any of the allowed types"`, ); }); it('accepts minimal config', () => { expect(testValidateOptions(MinimalConfig)).toEqual( validationResult(MinimalConfig), ); }); it('accepts anonymizeIP', () => { const config: Options = { ...MinimalConfig, anonymizeIP: true, }; expect(testValidateOptions(config)).toEqual(validationResult(config)); }); it('accepts single trackingID', () => { const config: Options = { trackingID: 'G-ABCDEF123', }; expect(testValidateOptions(config)).toEqual(validationResult(config)); }); it('accepts multiple trackingIDs', () => { const config: Options = { trackingID: ['G-ABCDEF123', 'UA-XYZ456789'], }; expect(testValidateOptions(config)).toEqual(validationResult(config)); }); it('throws for empty trackingID arrays', () => { const config: Options = { // @ts-expect-error: TS should error trackingID: [], }; expect(() => testValidateOptions(config), ).toThrowErrorMatchingInlineSnapshot( `""trackingID" does not match any of the allowed types"`, ); }); it('throws for sparse trackingID arrays', () => { const config: Options = { // @ts-expect-error: TS should error trackingID: ['G-ABCDEF123', null, 'UA-XYZ456789'], }; expect(() => testValidateOptions(config), ).toThrowErrorMatchingInlineSnapshot( `""trackingID" does not match any of the allowed types"`, ); }); it('throws for bad trackingID arrays', () => { const config: Options = { // @ts-expect-error: TS should error trackingID: ['G-ABCDEF123', 42], }; expect(() => testValidateOptions(config), ).toThrowErrorMatchingInlineSnapshot( `""trackingID" does not match any of the allowed types"`, ); }); });
1,407
0
petrpan-code/facebook/docusaurus/packages/docusaurus-plugin-sitemap/src
petrpan-code/facebook/docusaurus/packages/docusaurus-plugin-sitemap/src/__tests__/createSitemap.test.ts
/** * Copyright (c) Facebook, Inc. and its affiliates. * * This source code is licensed under the MIT license found in the * LICENSE file in the root directory of this source tree. */ import React from 'react'; import {EnumChangefreq} from 'sitemap'; import createSitemap from '../createSitemap'; import type {PluginOptions} from '../options'; import type {DocusaurusConfig} from '@docusaurus/types'; describe('createSitemap', () => { it('simple site', async () => { const sitemap = await createSitemap( { url: 'https://example.com', } as DocusaurusConfig, ['/', '/test'], {}, { changefreq: EnumChangefreq.DAILY, priority: 0.7, ignorePatterns: [], filename: 'sitemap.xml', }, ); expect(sitemap).toContain( `<urlset xmlns="http://www.sitemaps.org/schemas/sitemap/0.9" xmlns:news="http://www.google.com/schemas/sitemap-news/0.9" xmlns:xhtml="http://www.w3.org/1999/xhtml" xmlns:image="http://www.google.com/schemas/sitemap-image/1.1" xmlns:video="http://www.google.com/schemas/sitemap-video/1.1">`, ); }); it('empty site', () => expect(async () => { // @ts-expect-error: test await createSitemap({}, [], {}, {} as PluginOptions); }).rejects.toThrow( 'URL in docusaurus.config.js cannot be empty/undefined.', )); it('exclusion of 404 page', async () => { const sitemap = await createSitemap( { url: 'https://example.com', } as DocusaurusConfig, ['/', '/404.html', '/my-page'], {}, { changefreq: EnumChangefreq.DAILY, priority: 0.7, ignorePatterns: [], filename: 'sitemap.xml', }, ); expect(sitemap).not.toContain('404'); }); it('excludes patterns configured to be ignored', async () => { const sitemap = await createSitemap( { url: 'https://example.com', } as DocusaurusConfig, ['/', '/search/', '/tags/', '/search/foo', '/tags/foo/bar'], {}, { changefreq: EnumChangefreq.DAILY, priority: 0.7, ignorePatterns: [ // Shallow ignore '/search/', // Deep ignore '/tags/**', ], filename: 'sitemap.xml', }, ); expect(sitemap).not.toContain('/search/</loc>'); expect(sitemap).toContain('/search/foo'); expect(sitemap).not.toContain('/tags'); }); it('keep trailing slash unchanged', async () => { const sitemap = await createSitemap( { url: 'https://example.com', trailingSlash: undefined, } as DocusaurusConfig, ['/', '/test', '/nested/test', '/nested/test2/'], {}, { changefreq: EnumChangefreq.DAILY, priority: 0.7, ignorePatterns: [], filename: 'sitemap.xml', }, ); expect(sitemap).toContain('<loc>https://example.com/</loc>'); expect(sitemap).toContain('<loc>https://example.com/test</loc>'); expect(sitemap).toContain('<loc>https://example.com/nested/test</loc>'); expect(sitemap).toContain('<loc>https://example.com/nested/test2/</loc>'); }); it('add trailing slash', async () => { const sitemap = await createSitemap( { url: 'https://example.com', trailingSlash: true, } as DocusaurusConfig, ['/', '/test', '/nested/test', '/nested/test2/'], {}, { changefreq: EnumChangefreq.DAILY, priority: 0.7, ignorePatterns: [], filename: 'sitemap.xml', }, ); expect(sitemap).toContain('<loc>https://example.com/</loc>'); expect(sitemap).toContain('<loc>https://example.com/test/</loc>'); expect(sitemap).toContain('<loc>https://example.com/nested/test/</loc>'); expect(sitemap).toContain('<loc>https://example.com/nested/test2/</loc>'); }); it('remove trailing slash', async () => { const sitemap = await createSitemap( { url: 'https://example.com', trailingSlash: false, } as DocusaurusConfig, ['/', '/test', '/nested/test', '/nested/test2/'], {}, { changefreq: EnumChangefreq.DAILY, priority: 0.7, ignorePatterns: [], filename: 'sitemap.xml', }, ); expect(sitemap).toContain('<loc>https://example.com/</loc>'); expect(sitemap).toContain('<loc>https://example.com/test</loc>'); expect(sitemap).toContain('<loc>https://example.com/nested/test</loc>'); expect(sitemap).toContain('<loc>https://example.com/nested/test2</loc>'); }); it('filters pages with noindex', async () => { const sitemap = await createSitemap( { url: 'https://example.com', trailingSlash: false, } as DocusaurusConfig, ['/', '/noindex', '/nested/test', '/nested/test2/'], { '/noindex': { meta: { // @ts-expect-error: bad lib def toComponent: () => [ React.createElement('meta', { name: 'robots', content: 'NoFolloW, NoiNDeX', }), ], }, }, }, { changefreq: EnumChangefreq.DAILY, priority: 0.7, ignorePatterns: [], }, ); expect(sitemap).not.toContain('/noindex'); }); it('does not generate anything for all pages with noindex', async () => { const sitemap = await createSitemap( { url: 'https://example.com', trailingSlash: false, } as DocusaurusConfig, ['/', '/noindex'], { '/': { meta: { // @ts-expect-error: bad lib def toComponent: () => [ React.createElement('meta', {name: 'robots', content: 'noindex'}), ], }, }, '/noindex': { meta: { // @ts-expect-error: bad lib def toComponent: () => [ React.createElement('meta', {name: 'robots', content: 'noindex'}), ], }, }, }, { changefreq: EnumChangefreq.DAILY, priority: 0.7, ignorePatterns: [], }, ); expect(sitemap).toBeNull(); }); });
1,408
0
petrpan-code/facebook/docusaurus/packages/docusaurus-plugin-sitemap/src
petrpan-code/facebook/docusaurus/packages/docusaurus-plugin-sitemap/src/__tests__/options.test.ts
/** * Copyright (c) Facebook, Inc. and its affiliates. * * This source code is licensed under the MIT license found in the * LICENSE file in the root directory of this source tree. */ import {normalizePluginOptions} from '@docusaurus/utils-validation'; import { validateOptions, DEFAULT_OPTIONS, type Options, type PluginOptions, } from '../options'; import type {EnumChangefreq} from 'sitemap'; import type {Validate} from '@docusaurus/types'; function testValidate(options: Options) { return validateOptions({ validate: normalizePluginOptions as Validate<Options, PluginOptions>, options, }); } const defaultOptions = { ...DEFAULT_OPTIONS, id: 'default', }; describe('validateOptions', () => { it('returns default values for empty user options', () => { expect(testValidate({})).toEqual(defaultOptions); }); it('accepts correctly defined user options', () => { const userOptions: Options = { changefreq: 'yearly' as EnumChangefreq, priority: 0.9, ignorePatterns: ['/search/**'], }; expect(testValidate(userOptions)).toEqual({ ...defaultOptions, ...userOptions, }); }); it('rejects out-of-range priority inputs', () => { expect(() => testValidate({priority: 2}), ).toThrowErrorMatchingInlineSnapshot( `""priority" must be less than or equal to 1"`, ); }); it('rejects bad changefreq inputs', () => { expect(() => testValidate({changefreq: 'annually' as EnumChangefreq}), ).toThrowErrorMatchingInlineSnapshot( `""changefreq" must be one of [daily, monthly, always, hourly, weekly, yearly, never]"`, ); }); it('rejects bad ignorePatterns inputs', () => { expect(() => // @ts-expect-error: test testValidate({ignorePatterns: '/search'}), ).toThrowErrorMatchingInlineSnapshot(`""ignorePatterns" must be an array"`); expect(() => // @ts-expect-error: test testValidate({ignorePatterns: [/^\/search/]}), ).toThrowErrorMatchingInlineSnapshot( `""ignorePatterns[0]" must be a string"`, ); }); });
1,420
0
petrpan-code/facebook/docusaurus/packages/docusaurus-remark-plugin-npm2yarn/src
petrpan-code/facebook/docusaurus/packages/docusaurus-remark-plugin-npm2yarn/src/__tests__/index.test.ts
/** * Copyright (c) Facebook, Inc. and its affiliates. * * This source code is licensed under the MIT license found in the * LICENSE file in the root directory of this source tree. */ import path from 'path'; import vfile from 'to-vfile'; import dedent from 'dedent'; import npm2yarn from '../index'; const process = async ( content: any, options?: Parameters<typeof npm2yarn>[0], ) => { const {remark} = await import('remark'); const {default: mdx} = await import('remark-mdx'); const result = await remark() .use(mdx) .use(npm2yarn, options) .process(content); return result.value; }; const processFixture = async ( name: string, options?: Parameters<typeof npm2yarn>[0], ) => { const filePath = path.join(__dirname, '__fixtures__', `${name}.md`); const file = await vfile.read(filePath); return process(file, options); }; describe('npm2yarn plugin', () => { it('works with simplest md', async () => { const result = await process(dedent` # Title Hey \`\`\`bash npm2yarn npm install test \`\`\` `); expect(result).toMatchSnapshot(); }); it('works on installation file', async () => { const result = await processFixture('installation'); expect(result).toMatchSnapshot(); }); it('works on plugin file', async () => { const result = await processFixture('plugin'); expect(result).toMatchSnapshot(); }); it('works with common commands', async () => { const result = await processFixture('conversion-test', {sync: true}); expect(result).toMatchSnapshot(); }); it('works with sync option', async () => { const result = await processFixture('plugin', {sync: true}); expect(result).toMatchSnapshot(); }); it('does not work when language is not set', async () => { const result = await processFixture('syntax-not-properly-set'); expect(result).toMatchSnapshot(); }); it('does not re-import tabs components when already imported above', async () => { const result = await processFixture('import-tabs-above'); expect(result).toMatchSnapshot(); }); it('does not re-import tabs components when already imported below', async () => { const result = await processFixture('import-tabs-below'); expect(result).toMatchSnapshot(); }); it('does not re-import tabs components real-world multiple npm2yarn usage', async () => { const result = await processFixture('multiple'); expect(result).toMatchSnapshot(); }); it('work with yarn converter', async () => { const result = await processFixture('plugin', {converters: ['yarn']}); expect(result).toMatchSnapshot(); }); it('work with pnpm converter', async () => { const result = await processFixture('plugin', {converters: ['pnpm']}); expect(result).toMatchSnapshot(); }); it('work with custom converter', async () => { const result = await processFixture('plugin', { converters: [['Turbo', (code) => code.replace(/npm/g, 'turbo')]], }); expect(result).toMatchSnapshot(); }); });
1,429
0
petrpan-code/facebook/docusaurus/packages/docusaurus-remark-plugin-npm2yarn/src/__tests__
petrpan-code/facebook/docusaurus/packages/docusaurus-remark-plugin-npm2yarn/src/__tests__/__snapshots__/index.test.ts.snap
// Jest Snapshot v1, https://goo.gl/fbAQLP exports[`npm2yarn plugin does not re-import tabs components real-world multiple npm2yarn usage 1`] = ` "import Tabs from '@theme/Tabs' import TabItem from '@theme/TabItem' # Title <Tabs> <TabItem value="npm"> \`\`\`bash $ npm install --global docusaurus \`\`\` </TabItem> <TabItem value="yarn" label="Yarn"> \`\`\`bash $ yarn global add docusaurus \`\`\` </TabItem> <TabItem value="pnpm" label="pnpm"> \`\`\`bash $ pnpm add --global docusaurus \`\`\` </TabItem> </Tabs> <div className="nested-npm2yarn"> <Tabs> <TabItem value="npm"> \`\`\`bash npm install \`\`\` </TabItem> <TabItem value="yarn" label="Yarn"> \`\`\`bash yarn install \`\`\` </TabItem> <TabItem value="pnpm" label="pnpm"> \`\`\`bash pnpm install \`\`\` </TabItem> </Tabs> </div> \`\`\`bash echo "no npm2yarn here" \`\`\` ## Subtitle <Tabs> <TabItem value="npm"> \`\`\`bash yarn add @docusaurus/core \`\`\` </TabItem> <TabItem value="yarn" label="Yarn"> \`\`\`bash yarn add @docusaurus/core \`\`\` </TabItem> <TabItem value="pnpm" label="pnpm"> \`\`\`bash yarn add @docusaurus/core \`\`\` </TabItem> </Tabs> " `; exports[`npm2yarn plugin does not re-import tabs components when already imported above 1`] = ` "import Tabs from '@theme/Tabs'; import TabItem from '@theme/TabItem'; <Tabs> <TabItem value="npm"> \`\`\`bash $ npm install --global docusaurus \`\`\` </TabItem> <TabItem value="yarn" label="Yarn"> \`\`\`bash $ yarn global add docusaurus \`\`\` </TabItem> <TabItem value="pnpm" label="pnpm"> \`\`\`bash $ pnpm add --global docusaurus \`\`\` </TabItem> </Tabs> " `; exports[`npm2yarn plugin does not re-import tabs components when already imported below 1`] = ` "<Tabs> <TabItem value="npm"> \`\`\`bash $ npm install --global docusaurus \`\`\` </TabItem> <TabItem value="yarn" label="Yarn"> \`\`\`bash $ yarn global add docusaurus \`\`\` </TabItem> <TabItem value="pnpm" label="pnpm"> \`\`\`bash $ pnpm add --global docusaurus \`\`\` </TabItem> </Tabs> import Tabs from '@theme/Tabs'; import TabItem from '@theme/TabItem'; " `; exports[`npm2yarn plugin does not work when language is not set 1`] = ` "\`\`\`npm2yarn npm install --save docusaurus-plugin-name \`\`\` \`\`\`bash npm install --save docusaurus-plugin-name \`\`\` \`\`\`shell npm install --save docusaurus-plugin-name \`\`\` " `; exports[`npm2yarn plugin work with custom converter 1`] = ` "import Tabs from '@theme/Tabs' import TabItem from '@theme/TabItem' ## Installing a plugin A plugin is usually a npm package, so you install them like other npm packages using npm. <Tabs> <TabItem value="npm"> \`\`\`bash npm install --save docusaurus-plugin-name \`\`\` </TabItem> <TabItem value="Turbo"> \`\`\`bash turbo install --save docusaurus-plugin-name \`\`\` </TabItem> </Tabs> " `; exports[`npm2yarn plugin work with pnpm converter 1`] = ` "import Tabs from '@theme/Tabs' import TabItem from '@theme/TabItem' ## Installing a plugin A plugin is usually a npm package, so you install them like other npm packages using npm. <Tabs> <TabItem value="npm"> \`\`\`bash npm install --save docusaurus-plugin-name \`\`\` </TabItem> <TabItem value="pnpm" label="pnpm"> \`\`\`bash pnpm add docusaurus-plugin-name \`\`\` </TabItem> </Tabs> " `; exports[`npm2yarn plugin work with yarn converter 1`] = ` "import Tabs from '@theme/Tabs' import TabItem from '@theme/TabItem' ## Installing a plugin A plugin is usually a npm package, so you install them like other npm packages using npm. <Tabs> <TabItem value="npm"> \`\`\`bash npm install --save docusaurus-plugin-name \`\`\` </TabItem> <TabItem value="yarn" label="Yarn"> \`\`\`bash yarn add docusaurus-plugin-name \`\`\` </TabItem> </Tabs> " `; exports[`npm2yarn plugin works on installation file 1`] = ` "import Tabs from '@theme/Tabs' import TabItem from '@theme/TabItem' <Tabs> <TabItem value="npm"> \`\`\`bash $ npm install --global docusaurus \`\`\` </TabItem> <TabItem value="yarn" label="Yarn"> \`\`\`bash $ yarn global add docusaurus \`\`\` </TabItem> <TabItem value="pnpm" label="pnpm"> \`\`\`bash $ pnpm add --global docusaurus \`\`\` </TabItem> </Tabs> " `; exports[`npm2yarn plugin works on plugin file 1`] = ` "import Tabs from '@theme/Tabs' import TabItem from '@theme/TabItem' ## Installing a plugin A plugin is usually a npm package, so you install them like other npm packages using npm. <Tabs> <TabItem value="npm"> \`\`\`bash npm install --save docusaurus-plugin-name \`\`\` </TabItem> <TabItem value="yarn" label="Yarn"> \`\`\`bash yarn add docusaurus-plugin-name \`\`\` </TabItem> <TabItem value="pnpm" label="pnpm"> \`\`\`bash pnpm add docusaurus-plugin-name \`\`\` </TabItem> </Tabs> " `; exports[`npm2yarn plugin works with common commands 1`] = ` "import Tabs from '@theme/Tabs' import TabItem from '@theme/TabItem' <Tabs groupId="npm2yarn"> <TabItem value="npm"> \`\`\`bash npm run xxx -- --arg \`\`\` </TabItem> <TabItem value="yarn" label="Yarn"> \`\`\`bash yarn xxx --arg \`\`\` </TabItem> <TabItem value="pnpm" label="pnpm"> \`\`\`bash pnpm run xxx -- --arg \`\`\` </TabItem> </Tabs> <Tabs groupId="npm2yarn"> <TabItem value="npm"> \`\`\`bash npm install package \`\`\` </TabItem> <TabItem value="yarn" label="Yarn"> \`\`\`bash yarn add package \`\`\` </TabItem> <TabItem value="pnpm" label="pnpm"> \`\`\`bash pnpm add package \`\`\` </TabItem> </Tabs> <Tabs groupId="npm2yarn"> <TabItem value="npm"> \`\`\`bash npm remove package-name \`\`\` </TabItem> <TabItem value="yarn" label="Yarn"> \`\`\`bash yarn remove package-name \`\`\` </TabItem> <TabItem value="pnpm" label="pnpm"> \`\`\`bash pnpm remove package-name \`\`\` </TabItem> </Tabs> <Tabs groupId="npm2yarn"> <TabItem value="npm"> \`\`\`bash npm init docusaurus npm init docusaurus@latest my-website classic \`\`\` </TabItem> <TabItem value="yarn" label="Yarn"> \`\`\`bash yarn create docusaurus yarn create docusaurus@latest my-website classic \`\`\` </TabItem> <TabItem value="pnpm" label="pnpm"> \`\`\`bash pnpm create docusaurus pnpm create docusaurus@latest my-website classic \`\`\` </TabItem> </Tabs> " `; exports[`npm2yarn plugin works with simplest md 1`] = ` "import Tabs from '@theme/Tabs' import TabItem from '@theme/TabItem' # Title Hey <Tabs> <TabItem value="npm"> \`\`\`bash npm install test \`\`\` </TabItem> <TabItem value="yarn" label="Yarn"> \`\`\`bash yarn add test \`\`\` </TabItem> <TabItem value="pnpm" label="pnpm"> \`\`\`bash pnpm add test \`\`\` </TabItem> </Tabs> " `; exports[`npm2yarn plugin works with sync option 1`] = ` "import Tabs from '@theme/Tabs' import TabItem from '@theme/TabItem' ## Installing a plugin A plugin is usually a npm package, so you install them like other npm packages using npm. <Tabs groupId="npm2yarn"> <TabItem value="npm"> \`\`\`bash npm install --save docusaurus-plugin-name \`\`\` </TabItem> <TabItem value="yarn" label="Yarn"> \`\`\`bash yarn add docusaurus-plugin-name \`\`\` </TabItem> <TabItem value="pnpm" label="pnpm"> \`\`\`bash pnpm add docusaurus-plugin-name \`\`\` </TabItem> </Tabs> " `;
1,443
0
petrpan-code/facebook/docusaurus/packages/docusaurus-theme-classic/src
petrpan-code/facebook/docusaurus/packages/docusaurus-theme-classic/src/__tests__/options.test.ts
/** * Copyright (c) Facebook, Inc. and its affiliates. * * This source code is licensed under the MIT license found in the * LICENSE file in the root directory of this source tree. */ import _ from 'lodash'; import { normalizeThemeConfig, normalizePluginOptions, } from '@docusaurus/utils-validation'; import {themes} from 'prism-react-renderer'; import {ThemeConfigSchema, DEFAULT_CONFIG, validateOptions} from '../options'; import type {Options, PluginOptions} from '@docusaurus/theme-classic'; import type {ThemeConfig} from '@docusaurus/theme-common'; import type {Validate} from '@docusaurus/types'; function testValidateThemeConfig(partialThemeConfig: {[key: string]: unknown}) { return normalizeThemeConfig(ThemeConfigSchema, { ...DEFAULT_CONFIG, ...partialThemeConfig, }); } function testValidateOptions(options: Options) { return validateOptions({ validate: normalizePluginOptions as Validate<Options, PluginOptions>, options, }); } describe('themeConfig', () => { it('accepts valid theme config', () => { const userConfig = { prism: { theme: themes.github, darkTheme: themes.dracula, defaultLanguage: 'javaSCRIPT', additionalLanguages: ['koTLin', 'jaVa'], magicComments: [ { className: 'theme-code-block-highlighted-line', line: 'highlight-next-line', block: {start: 'highlight-start', end: 'highlight-end'}, }, ], }, docs: { versionPersistence: 'localStorage', sidebar: { hideable: true, autoCollapseCategories: false, }, }, announcementBar: { id: 'supports', content: 'pls support', backgroundColor: '#fff', textColor: '#000', isCloseable: true, }, image: 'img/docusaurus-social-card.jpg', navbar: { style: 'primary', hideOnScroll: true, title: 'Docusaurus', logo: { alt: 'Docusaurus Logo', src: 'img/docusaurus.svg', srcDark: 'img/docusaurus_keytar.svg', target: '_self', className: 'navbar__logo__custom', style: { maxWidth: 42, }, }, items: [ { type: 'docsVersionDropdown', position: 'left', dropdownItemsBefore: [], dropdownItemsAfter: [], }, { to: 'docs/next/support', label: 'Community', position: 'left', activeBaseRegex: `docs/next/(support|team|resources)`, 'aria-label': 'Community', }, ], }, footer: { style: 'dark', links: [ { title: 'Learn', items: [ { label: 'Introduction', to: 'docs', }, ], }, ], logo: { alt: 'Meta Open Source Logo', src: 'img/footer_logo.png', href: 'https://opensource.facebook.com', target: '_self', className: 'footer__logo__custom', style: { maxWidth: 42, }, }, copyright: `Copyright © ${new Date().getFullYear()} Facebook, Inc. Built with Docusaurus.`, }, tableOfContents: { minHeadingLevel: 2, maxHeadingLevel: 5, }, }; expect(testValidateThemeConfig(userConfig)).toEqual({ ...DEFAULT_CONFIG, ...userConfig, prism: { ...userConfig.prism, // Modified/normalized values defaultLanguage: 'javascript', additionalLanguages: ['kotlin', 'java'], }, }); }); it('rejects outdated sidebar options', () => { expect(() => testValidateThemeConfig({hideableSidebar: true}), ).toThrowErrorMatchingInlineSnapshot( `"themeConfig.hideableSidebar has been moved to themeConfig.docs.sidebar.hideable."`, ); expect(() => testValidateThemeConfig({autoCollapseSidebarCategories: true}), ).toThrowErrorMatchingInlineSnapshot( `"themeConfig.autoCollapseSidebarCategories has been moved to themeConfig.docs.sidebar.autoCollapseCategories."`, ); }); it('allows possible types of navbar items', () => { const config = { navbar: { items: [ // Doc link { type: 'doc', position: 'left', docId: 'intro', label: 'Introduction', }, // Doc link with HTML as label { type: 'doc', position: 'left', docId: 'intro', html: '<b>Introduction</b>', }, // Regular link { to: '/guide/', label: 'Guide', position: 'left', activeBaseRegex: '/guide/', }, // Regular link with HTML as label { to: '/guide/', html: '<b>Guide</b>', position: 'left', activeBaseRegex: '/guide/', }, // Regular dropdown { label: 'Community', position: 'right', items: [ { label: 'Facebook', href: 'https://.facebook.com/', target: '_self', }, { label: 'GitHub', href: 'https://github.com/facebook/docusaurus', className: 'github-link', }, ], }, // HTML-only { type: 'html', position: 'right', value: '<button>Give feedback</button>', }, // Dropdown with label as HTML { type: 'dropdown', label: 'Tools <sup>new</sup>', position: 'left', items: [ { type: 'html', value: '<b>Supported package managers</b>', }, { type: 'doc', docId: 'npm', label: 'npm', }, { to: '/yarn', label: 'Yarn', }, ], }, // Doc version dropdown { type: 'docsVersionDropdown', position: 'right', dropdownActiveClassDisabled: true, dropdownItemsBefore: [ { href: 'https://www.npmjs.com/package/docusaurus?activeTab=versions', label: 'Versions on npm', className: 'npm-styled', target: '_self', }, ], dropdownItemsAfter: [ { type: 'html', value: '<hr/>', }, { to: '/versions', label: 'All versions', className: 'all_vers', }, ], }, // External link with custom data attribute { href: 'https://github.com/facebook/docusaurus', position: 'right', className: 'header-github-link', 'aria-label': 'GitHub repository', }, // Docs version { type: 'docsVersion', position: 'left', label: 'Current version', }, // Search with className { type: 'search', position: 'right', className: 'search-bar-wrapper', }, ], }, }; expect(testValidateThemeConfig(config)).toEqual({ ...DEFAULT_CONFIG, navbar: { ...DEFAULT_CONFIG.navbar, ...config.navbar, }, }); }); it('accept "custom-" prefixed custom navbar item type', () => { const config = { navbar: { items: [ { type: 'custom-x', position: 'left', xyz: 42, }, { label: 'Dropdown with custom item', position: 'right', items: [ { label: 'Facebook', href: 'https://.facebook.com/', target: '_self', }, { type: 'custom-y', any: new Date(), prop: 42, isAccepted: true, }, ], }, ], }, }; expect(testValidateThemeConfig(config)).toEqual({ ...DEFAULT_CONFIG, navbar: { ...DEFAULT_CONFIG.navbar, ...config.navbar, }, }); }); it('rejects unknown navbar item type', () => { const config = { navbar: { items: [ { type: 'joke', position: 'left', label: 'hahaha', }, ], }, }; expect(() => testValidateThemeConfig(config), ).toThrowErrorMatchingInlineSnapshot(`"Bad navbar item type joke"`); }); it('rejects nested dropdowns', () => { const config = { navbar: { items: [ { position: 'left', label: 'Nested', items: [ { label: 'Still a dropdown', items: [ { label: 'Should reject this', to: '/rejected', }, ], }, ], }, ], }, }; expect(() => testValidateThemeConfig(config), ).toThrowErrorMatchingInlineSnapshot(`"Nested dropdowns are not allowed"`); }); it('rejects nested dropdowns 2', () => { const config = { navbar: { items: [ { position: 'left', label: 'Nested', items: [{type: 'docsVersionDropdown'}], }, ], }, }; expect(() => testValidateThemeConfig(config), ).toThrowErrorMatchingInlineSnapshot(`"Nested dropdowns are not allowed"`); }); it('rejects position attribute within dropdown', () => { const config = { navbar: { items: [ { position: 'left', label: 'Dropdown', items: [ { label: 'Hi', position: 'left', to: '/link', }, ], }, ], }, }; expect(() => testValidateThemeConfig(config), ).toThrowErrorMatchingInlineSnapshot( `""navbar.items[0].items[0].position" is not allowed"`, ); }); it('gives friendly error when href and to coexist', () => { const config = { navbar: { items: [ { position: 'left', label: 'Nested', to: '/link', href: 'http://example.com/link', }, ], }, }; expect(() => testValidateThemeConfig(config), ).toThrowErrorMatchingInlineSnapshot( `"One and only one between "to" and "href" should be provided"`, ); }); it('allows empty alt tags for the logo image in the header', () => { const altTagConfig = { navbar: { logo: { alt: '', src: '/arbitrary-logo.png', }, hideOnScroll: false, }, }; expect(testValidateThemeConfig(altTagConfig)).toEqual({ ...DEFAULT_CONFIG, navbar: { ...DEFAULT_CONFIG.navbar, ...altTagConfig.navbar, }, }); }); it('allows empty alt tags for the logo image in the footer', () => { const partialConfig = { footer: { logo: { alt: '', src: '/arbitrary-logo.png', }, }, }; const normalizedConfig = testValidateThemeConfig(partialConfig); expect(normalizedConfig).toEqual({ ...normalizedConfig, footer: { ...normalizedConfig.footer, ...partialConfig.footer, }, }); }); it('allows simple links in footer', () => { const partialConfig = { footer: { links: [ { label: 'Privacy', href: 'https://opensource.facebook.com/legal/privacy/', }, { label: 'Terms', href: 'https://opensource.facebook.com/legal/terms/', }, { label: 'Cookie Policy', href: 'https://opensource.facebook.com/legal/cookie-policy/', }, ], }, }; const normalizedConfig = testValidateThemeConfig(partialConfig); expect(normalizedConfig).toEqual({ ...normalizedConfig, footer: { ...normalizedConfig.footer, ...partialConfig.footer, }, }); }); it('allows footer column with no title', () => { const partialConfig = { footer: { links: [ { items: [ { label: 'Cookie Policy', href: 'https://opensource.facebook.com/legal/cookie-policy/', }, ], }, ], }, }; const normalizedConfig = testValidateThemeConfig(partialConfig); expect(normalizedConfig).toEqual({ ...normalizedConfig, footer: { ...normalizedConfig.footer, ...partialConfig.footer, links: [ { title: null, // Default value is important to distinguish simple footer from multi-column footer items: partialConfig.footer.links[0]!.items, }, ], }, }); }); it('rejects mix of simple and multi-column links in footer', () => { const partialConfig = { footer: { links: [ { title: 'Learn', items: [ { label: 'Introduction', to: 'docs', }, ], }, { label: 'Privacy', href: 'https://opensource.facebook.com/legal/privacy/', }, ], }, }; expect(() => testValidateThemeConfig(partialConfig), ).toThrowErrorMatchingInlineSnapshot( `"The footer must be either simple or multi-column, and not a mix of the two. See: https://docusaurus.io/docs/api/themes/configuration#footer-links"`, ); }); it('allows width and height specification for logo', () => { const altTagConfig = { navbar: { logo: { alt: '', src: '/arbitrary-logo.png', srcDark: '/arbitrary-dark-logo.png', width: '20px', height: '20%', }, }, }; expect(testValidateThemeConfig(altTagConfig)).toEqual({ ...DEFAULT_CONFIG, navbar: { ...DEFAULT_CONFIG.navbar, ...altTagConfig.navbar, }, }); }); describe('prism config', () => { it('accepts a range of magic comments', () => { const prismConfig = { prism: { additionalLanguages: ['kotlin', 'java'], theme: themes.dracula, magicComments: [], }, }; expect(testValidateThemeConfig(prismConfig)).toEqual({ ...DEFAULT_CONFIG, ...prismConfig, }); const prismConfig2 = { prism: { additionalLanguages: [], theme: themes.dracula, magicComments: [ { className: 'a', line: 'a-next-line', }, ], }, }; expect(testValidateThemeConfig(prismConfig2)).toEqual({ ...DEFAULT_CONFIG, ...prismConfig2, }); const prismConfig3 = { prism: { additionalLanguages: [], theme: themes.dracula, magicComments: [ { className: 'a', block: {start: 'a-start', end: 'a-end'}, }, ], }, }; expect(testValidateThemeConfig(prismConfig3)).toEqual({ ...DEFAULT_CONFIG, ...prismConfig3, }); }); it('rejects incomplete magic comments', () => { expect(() => testValidateThemeConfig({ prism: { magicComments: [{className: 'a'}], }, }), ).toThrowErrorMatchingInlineSnapshot( `""prism.magicComments[0]" must contain at least one of [line, block]"`, ); expect(() => testValidateThemeConfig({ prism: { magicComments: [{className: 'a', block: {start: 'start'}}], }, }), ).toThrowErrorMatchingInlineSnapshot( `""prism.magicComments[0].block.end" is required"`, ); }); }); describe('color mode config', () => { const withDefaultValues = (colorMode?: ThemeConfig['colorMode']) => _.merge({}, DEFAULT_CONFIG.colorMode, colorMode); it('switch config', () => { const colorMode = { switchConfig: { darkIcon: '🌙', }, }; expect(() => testValidateThemeConfig({colorMode}), ).toThrowErrorMatchingInlineSnapshot( `"colorMode.switchConfig is deprecated. If you want to customize the icons for light and dark mode, swizzle IconLightMode, IconDarkMode, or ColorModeToggle instead."`, ); }); it('max config', () => { const colorMode: ThemeConfig['colorMode'] = { defaultMode: 'dark', disableSwitch: false, respectPrefersColorScheme: true, }; expect(testValidateThemeConfig({colorMode})).toEqual({ ...DEFAULT_CONFIG, colorMode: withDefaultValues(colorMode), }); }); it('undefined config', () => { const colorMode = undefined; expect(testValidateThemeConfig({colorMode})).toEqual({ ...DEFAULT_CONFIG, colorMode: withDefaultValues(colorMode), }); }); it('empty config', () => { const colorMode = {}; expect(testValidateThemeConfig({colorMode})).toEqual({ ...DEFAULT_CONFIG, colorMode: { ...DEFAULT_CONFIG.colorMode, ...colorMode, }, }); }); }); describe('tableOfContents', () => { it('accepts undefined', () => { const tableOfContents = undefined; expect(testValidateThemeConfig({tableOfContents})).toEqual({ ...DEFAULT_CONFIG, tableOfContents: { minHeadingLevel: DEFAULT_CONFIG.tableOfContents.minHeadingLevel, maxHeadingLevel: DEFAULT_CONFIG.tableOfContents.maxHeadingLevel, }, }); }); it('accepts empty', () => { const tableOfContents = {}; expect(testValidateThemeConfig({tableOfContents})).toEqual({ ...DEFAULT_CONFIG, tableOfContents: { minHeadingLevel: DEFAULT_CONFIG.tableOfContents.minHeadingLevel, maxHeadingLevel: DEFAULT_CONFIG.tableOfContents.maxHeadingLevel, }, }); }); it('accepts min', () => { const tableOfContents = { minHeadingLevel: 3, }; expect(testValidateThemeConfig({tableOfContents})).toEqual({ ...DEFAULT_CONFIG, tableOfContents: { minHeadingLevel: 3, maxHeadingLevel: DEFAULT_CONFIG.tableOfContents.maxHeadingLevel, }, }); }); it('accepts max', () => { const tableOfContents = { maxHeadingLevel: 5, }; expect(testValidateThemeConfig({tableOfContents})).toEqual({ ...DEFAULT_CONFIG, tableOfContents: { minHeadingLevel: DEFAULT_CONFIG.tableOfContents.minHeadingLevel, maxHeadingLevel: 5, }, }); }); it('rejects min 2.5', () => { const tableOfContents = { minHeadingLevel: 2.5, }; expect(() => testValidateThemeConfig({tableOfContents}), ).toThrowErrorMatchingInlineSnapshot( `""tableOfContents.minHeadingLevel" must be an integer"`, ); }); it('rejects max 2.5', () => { const tableOfContents = { maxHeadingLevel: 2.5, }; expect(() => testValidateThemeConfig({tableOfContents}), ).toThrowErrorMatchingInlineSnapshot( `""tableOfContents.maxHeadingLevel" must be an integer"`, ); }); it('rejects min 1', () => { const tableOfContents = { minHeadingLevel: 1, }; expect(() => testValidateThemeConfig({tableOfContents}), ).toThrowErrorMatchingInlineSnapshot( `""tableOfContents.minHeadingLevel" must be greater than or equal to 2"`, ); }); it('rejects min 7', () => { const tableOfContents = { minHeadingLevel: 7, }; expect(() => testValidateThemeConfig({tableOfContents}), ).toThrowErrorMatchingInlineSnapshot( `""tableOfContents.minHeadingLevel" must be less than or equal to ref:maxHeadingLevel"`, ); }); it('rejects max 1', () => { const tableOfContents = { maxHeadingLevel: 1, }; expect(() => testValidateThemeConfig({tableOfContents}), ).toThrowErrorMatchingInlineSnapshot( `""tableOfContents.maxHeadingLevel" must be greater than or equal to 2"`, ); }); it('rejects max 7', () => { const tableOfContents = { maxHeadingLevel: 7, }; expect(() => testValidateThemeConfig({tableOfContents}), ).toThrowErrorMatchingInlineSnapshot( `""tableOfContents.maxHeadingLevel" must be less than or equal to 6"`, ); }); it('rejects min 5 + max 3', () => { const tableOfContents = { minHeadingLevel: 5, maxHeadingLevel: 3, }; expect(() => testValidateThemeConfig({tableOfContents}), ).toThrowErrorMatchingInlineSnapshot( `""tableOfContents.minHeadingLevel" must be less than or equal to ref:maxHeadingLevel"`, ); }); }); }); describe('validateOptions', () => { describe('customCss config', () => { it('accepts customCss undefined', () => { expect( testValidateOptions({ customCss: undefined, }), ).toEqual({ id: 'default', customCss: [], }); }); it('accepts customCss string', () => { expect( testValidateOptions({ customCss: './path/to/cssFile.css', }), ).toEqual({ id: 'default', customCss: ['./path/to/cssFile.css'], }); }); it('accepts customCss string array', () => { expect( testValidateOptions({ customCss: ['./path/to/cssFile.css', './path/to/cssFile2.css'], }), ).toEqual({ id: 'default', customCss: ['./path/to/cssFile.css', './path/to/cssFile2.css'], }); }); it('rejects customCss number', () => { expect(() => testValidateOptions({ // @ts-expect-error: test customCss: 42, }), ).toThrowErrorMatchingInlineSnapshot( `""customCss" must be a string or an array of strings"`, ); }); }); });
1,444
0
petrpan-code/facebook/docusaurus/packages/docusaurus-theme-classic/src
petrpan-code/facebook/docusaurus/packages/docusaurus-theme-classic/src/__tests__/translations.test.ts
/** * Copyright (c) Facebook, Inc. and its affiliates. * * This source code is licensed under the MIT license found in the * LICENSE file in the root directory of this source tree. */ import {updateTranslationFileMessages} from '@docusaurus/utils'; import {getTranslationFiles, translateThemeConfig} from '../translations'; import type {ThemeConfig} from '@docusaurus/theme-common'; const ThemeConfigSample = { colorMode: {}, announcementBar: {}, prism: {}, docs: { versionPersistence: 'none', }, navbar: { title: 'navbar title', logo: { alt: 'navbar alt text logo', src: 'img/docusaurus.svg', }, style: 'dark', hideOnScroll: false, items: [ { label: 'Dropdown', items: [ {label: 'Dropdown item 1', items: []}, {label: 'Dropdown item 2', items: []}, ], }, ], }, footer: { logo: { alt: 'footer alt text logo', src: 'img/docusaurus.svg', }, copyright: 'Copyright FB', style: 'light', links: [ { title: 'Footer link column 1', items: [ {label: 'Link 1', to: 'https://facebook.com'}, {label: 'Link 2', to: 'https://facebook.com'}, ], }, { title: 'Footer link column 2', items: [{label: 'Link 3', to: 'https://facebook.com'}], }, ], }, } as unknown as ThemeConfig; const ThemeConfigSampleSimpleFooter: ThemeConfig = { ...ThemeConfigSample, footer: { logo: { alt: 'footer alt text logo', src: 'img/docusaurus.svg', }, copyright: 'Copyright FB', style: 'light', links: [ {label: 'Link 1', to: 'https://facebook.com'}, {label: 'Link 2', to: 'https://facebook.com'}, ], }, }; function getSampleTranslationFiles(themeConfig: ThemeConfig) { return getTranslationFiles({ themeConfig, }); } function getSampleTranslationFilesTranslated(themeConfig: ThemeConfig) { const translationFiles = getSampleTranslationFiles(themeConfig); return translationFiles.map((translationFile) => updateTranslationFileMessages( translationFile, (message) => `${message} (translated)`, ), ); } describe('getTranslationFiles', () => { it('returns translation files matching snapshot', () => { expect(getSampleTranslationFiles(ThemeConfigSample)).toMatchSnapshot(); expect( getSampleTranslationFiles(ThemeConfigSampleSimpleFooter), ).toMatchSnapshot(); }); }); describe('translateThemeConfig', () => { it('does not translate anything if translation files are untranslated', () => { expect( translateThemeConfig({ themeConfig: ThemeConfigSample, translationFiles: getSampleTranslationFiles(ThemeConfigSample), }), ).toEqual(ThemeConfigSample); }); it('returns translated themeConfig', () => { expect( translateThemeConfig({ themeConfig: ThemeConfigSample, translationFiles: getSampleTranslationFilesTranslated(ThemeConfigSample), }), ).toMatchSnapshot(); }); }); describe('getTranslationFiles and translateThemeConfig isomorphism', () => { function verifyIsomorphism(themeConfig: ThemeConfig) { const translatedThemeConfig = translateThemeConfig({ themeConfig, translationFiles: getTranslationFiles({themeConfig}), }); expect(translatedThemeConfig).toEqual(themeConfig); } it('is verified for sample', () => { verifyIsomorphism(ThemeConfigSample); }); it('is verified for sample with simple footer', () => { verifyIsomorphism(ThemeConfigSampleSimpleFooter); }); // Undefined footer should not make the translation code crash // See https://github.com/facebook/docusaurus/issues/3936 it('is verified for sample without footer', () => { verifyIsomorphism({...ThemeConfigSample, footer: undefined}); }); });
1,445
0
petrpan-code/facebook/docusaurus/packages/docusaurus-theme-classic/src/__tests__
petrpan-code/facebook/docusaurus/packages/docusaurus-theme-classic/src/__tests__/__snapshots__/translations.test.ts.snap
// Jest Snapshot v1, https://goo.gl/fbAQLP exports[`getTranslationFiles returns translation files matching snapshot 1`] = ` [ { "content": { "item.label.Dropdown": { "description": "Navbar item with label Dropdown", "message": "Dropdown", }, "item.label.Dropdown item 1": { "description": "Navbar item with label Dropdown item 1", "message": "Dropdown item 1", }, "item.label.Dropdown item 2": { "description": "Navbar item with label Dropdown item 2", "message": "Dropdown item 2", }, "logo.alt": { "description": "The alt text of navbar logo", "message": "navbar alt text logo", }, "title": { "description": "The title in the navbar", "message": "navbar title", }, }, "path": "navbar", }, { "content": { "copyright": { "description": "The footer copyright", "message": "Copyright FB", }, "link.item.label.Link 1": { "description": "The label of footer link with label=Link 1 linking to https://facebook.com", "message": "Link 1", }, "link.item.label.Link 2": { "description": "The label of footer link with label=Link 2 linking to https://facebook.com", "message": "Link 2", }, "link.item.label.Link 3": { "description": "The label of footer link with label=Link 3 linking to https://facebook.com", "message": "Link 3", }, "link.title.Footer link column 1": { "description": "The title of the footer links column with title=Footer link column 1 in the footer", "message": "Footer link column 1", }, "link.title.Footer link column 2": { "description": "The title of the footer links column with title=Footer link column 2 in the footer", "message": "Footer link column 2", }, "logo.alt": { "description": "The alt text of footer logo", "message": "footer alt text logo", }, }, "path": "footer", }, ] `; exports[`getTranslationFiles returns translation files matching snapshot 2`] = ` [ { "content": { "item.label.Dropdown": { "description": "Navbar item with label Dropdown", "message": "Dropdown", }, "item.label.Dropdown item 1": { "description": "Navbar item with label Dropdown item 1", "message": "Dropdown item 1", }, "item.label.Dropdown item 2": { "description": "Navbar item with label Dropdown item 2", "message": "Dropdown item 2", }, "logo.alt": { "description": "The alt text of navbar logo", "message": "navbar alt text logo", }, "title": { "description": "The title in the navbar", "message": "navbar title", }, }, "path": "navbar", }, { "content": { "copyright": { "description": "The footer copyright", "message": "Copyright FB", }, "link.item.label.Link 1": { "description": "The label of footer link with label=Link 1 linking to https://facebook.com", "message": "Link 1", }, "link.item.label.Link 2": { "description": "The label of footer link with label=Link 2 linking to https://facebook.com", "message": "Link 2", }, "logo.alt": { "description": "The alt text of footer logo", "message": "footer alt text logo", }, }, "path": "footer", }, ] `; exports[`translateThemeConfig returns translated themeConfig 1`] = ` { "announcementBar": {}, "colorMode": {}, "docs": { "versionPersistence": "none", }, "footer": { "copyright": "Copyright FB (translated)", "links": [ { "items": [ { "label": "Link 1 (translated)", "to": "https://facebook.com", }, { "label": "Link 2 (translated)", "to": "https://facebook.com", }, ], "title": "Footer link column 1 (translated)", }, { "items": [ { "label": "Link 3 (translated)", "to": "https://facebook.com", }, ], "title": "Footer link column 2 (translated)", }, ], "logo": { "alt": "footer alt text logo (translated)", "src": "img/docusaurus.svg", }, "style": "light", }, "navbar": { "hideOnScroll": false, "items": [ { "items": [ { "items": [], "label": "Dropdown item 1 (translated)", }, { "items": [], "label": "Dropdown item 2 (translated)", }, ], "label": "Dropdown (translated)", }, ], "logo": { "alt": "navbar alt text logo (translated)", "src": "img/docusaurus.svg", }, "style": "dark", "title": "navbar title (translated)", }, "prism": {}, } `;
1,663
0
petrpan-code/facebook/docusaurus/packages/docusaurus-theme-classic/src/theme/Tabs
petrpan-code/facebook/docusaurus/packages/docusaurus-theme-classic/src/theme/Tabs/__tests__/index.test.tsx
/** * Copyright (c) Facebook, Inc. and its affiliates. * * This source code is licensed under the MIT license found in the * LICENSE file in the root directory of this source tree. */ import React, {type ReactNode} from 'react'; import renderer from 'react-test-renderer'; import {ScrollControllerProvider} from '@docusaurus/theme-common/internal'; import {StaticRouter} from 'react-router-dom'; import Tabs from '../index'; import TabItem from '../../TabItem'; function TestProviders({ children, pathname = '/', }: { children: ReactNode; pathname?: string; }) { return ( <StaticRouter location={{pathname}}> <ScrollControllerProvider>{children}</ScrollControllerProvider> </StaticRouter> ); } describe('Tabs', () => { it('rejects bad Tabs child', () => { expect(() => { renderer.create( <TestProviders> <Tabs> <div>Naughty</div> <TabItem value="good">Good</TabItem> </Tabs> </TestProviders>, ); }).toThrowErrorMatchingInlineSnapshot( `"Docusaurus error: Bad <Tabs> child <div>: all children of the <Tabs> component should be <TabItem>, and every <TabItem> should have a unique "value" prop."`, ); }); it('rejects bad Tabs defaultValue', () => { expect(() => { renderer.create( <TestProviders> <Tabs defaultValue="bad"> <TabItem value="v1">Tab 1</TabItem> <TabItem value="v2">Tab 2</TabItem> </Tabs> </TestProviders>, ); }).toThrowErrorMatchingInlineSnapshot( `"Docusaurus error: The <Tabs> has a defaultValue "bad" but none of its children has the corresponding value. Available values are: v1, v2. If you intend to show no default tab, use defaultValue={null} instead."`, ); }); it('rejects duplicate values', () => { expect(() => { renderer.create( <TestProviders> <Tabs> <TabItem value="v1">Tab 1</TabItem> <TabItem value="v2">Tab 2</TabItem> <TabItem value="v3">Tab 3</TabItem> <TabItem value="v4">Tab 4</TabItem> <TabItem value="v1">Tab 5</TabItem> <TabItem value="v2">Tab 6</TabItem> </Tabs> </TestProviders>, ); }).toThrowErrorMatchingInlineSnapshot( `"Docusaurus error: Duplicate values "v1, v2" found in <Tabs>. Every value needs to be unique."`, ); }); it('accepts valid Tabs config', () => { expect(() => { renderer.create( <TestProviders> <Tabs> <TabItem value="v1">Tab 1</TabItem> <TabItem value="v2">Tab 2</TabItem> </Tabs> <Tabs> <TabItem value="v1">Tab 1</TabItem> <TabItem value="v2" default> Tab 2 </TabItem> </Tabs> <Tabs defaultValue="v1"> <TabItem value="v1" label="V1"> Tab 1 </TabItem> <TabItem value="v2" label="V2"> Tab 2 </TabItem> </Tabs> <Tabs defaultValue="v1" values={[ {value: 'v1', label: 'V1'}, {value: 'v2', label: 'V2'}, ]}> <TabItem value="v1">Tab 1</TabItem> <TabItem value="v2">Tab 2</TabItem> </Tabs> <Tabs defaultValue={null} values={[ {value: 'v1', label: 'V1'}, {value: 'v2', label: 'V2'}, ]}> <TabItem value="v1">Tab 1</TabItem> <TabItem value="v2">Tab 2</TabItem> </Tabs> <Tabs defaultValue={null}> <TabItem value="v1" label="V1"> Tab 1 </TabItem> <TabItem value="v2" label="V2"> Tab 2 </TabItem> </Tabs> </TestProviders>, ); }).not.toThrow(); // TODO Better Jest infrastructure to mock the Layout }); // https://github.com/facebook/docusaurus/issues/5729 it('accepts dynamic Tabs with number values', () => { expect(() => { const tabs = ['Apple', 'Banana', 'Carrot']; renderer.create( <TestProviders> <Tabs values={tabs.map((t, idx) => ({label: t, value: idx}))} defaultValue={0}> {tabs.map((t, idx) => ( <TabItem key={idx} value={idx}> {t} </TabItem> ))} </Tabs> </TestProviders>, ); }).not.toThrow(); }); it('rejects if querystring is true, but groupId falsy', () => { expect(() => { renderer.create( <TestProviders> <Tabs queryString> <TabItem value="val1">Val1</TabItem> <TabItem value="val2">Val2</TabItem> </Tabs> </TestProviders>, ); }).toThrow( 'Docusaurus error: The <Tabs> component groupId prop is required if queryString=true, because this value is used as the search param name. You can also provide an explicit value such as queryString="my-search-param".', ); }); it('accept querystring=true when groupId is defined', () => { expect(() => { renderer.create( <TestProviders> <Tabs queryString groupId="my-group-id"> <TabItem value="val1">Val1</TabItem> <TabItem value="val2">Val2</TabItem> </Tabs> </TestProviders>, ); }).not.toThrow(); }); it('accept querystring as string, but groupId falsy', () => { expect(() => { renderer.create( <TestProviders> <Tabs queryString="qsKey"> <TabItem value="val1">Val1</TabItem> <TabItem value="val2">Val2</TabItem> </Tabs> </TestProviders>, ); }).not.toThrow(); }); it('accepts a single TabItem', () => { expect(() => { renderer.create( <TestProviders> <Tabs> <TabItem value="val1">Val1</TabItem> </Tabs> </TestProviders>, ); }).not.toThrow(); }); it('allows a tab to be falsy', () => { expect(() => { renderer.create( <TestProviders> <Tabs> <TabItem value="val1">Val1</TabItem> {null} {false} {undefined} </Tabs> </TestProviders>, ); }).not.toThrow(); }); });
1,695
0
petrpan-code/facebook/docusaurus/packages/docusaurus-theme-common/src/contexts
petrpan-code/facebook/docusaurus/packages/docusaurus-theme-common/src/contexts/__tests__/docsSidebar.test.tsx
/** * Copyright (c) Facebook, Inc. and its affiliates. * * This source code is licensed under the MIT license found in the * LICENSE file in the root directory of this source tree. */ import React from 'react'; import {renderHook} from '@testing-library/react-hooks'; import {useDocsSidebar, DocsSidebarProvider} from '../docsSidebar'; import type {PropSidebar} from '@docusaurus/plugin-content-docs'; describe('useDocsSidebar', () => { it('throws if context provider is missing', () => { expect( () => renderHook(() => useDocsSidebar()).result.current?.items, ).toThrowErrorMatchingInlineSnapshot( `"Hook useDocsSidebar is called outside the <DocsSidebarProvider>. "`, ); }); it('reads value from context provider', () => { const name = 'mySidebarName'; const items: PropSidebar = []; const {result} = renderHook(() => useDocsSidebar(), { wrapper: ({children}) => ( <DocsSidebarProvider name={name} items={items}> {children} </DocsSidebarProvider> ), }); expect(result.current).toBeDefined(); expect(result.current!.name).toBe(name); expect(result.current!.items).toBe(items); }); });
1,696
0
petrpan-code/facebook/docusaurus/packages/docusaurus-theme-common/src/contexts
petrpan-code/facebook/docusaurus/packages/docusaurus-theme-common/src/contexts/__tests__/docsVersion.test.tsx
/** * Copyright (c) Facebook, Inc. and its affiliates. * * This source code is licensed under the MIT license found in the * LICENSE file in the root directory of this source tree. */ import React from 'react'; import {renderHook} from '@testing-library/react-hooks'; import {useDocsVersion, DocsVersionProvider} from '../docsVersion'; import type {PropVersionMetadata} from '@docusaurus/plugin-content-docs'; function testVersion(data?: Partial<PropVersionMetadata>): PropVersionMetadata { return { version: 'versionName', label: 'Version Label', className: 'version className', badge: true, banner: 'unreleased', docs: {}, docsSidebars: {}, isLast: false, pluginId: 'default', ...data, }; } describe('useDocsVersion', () => { it('throws if context provider is missing', () => { expect( () => renderHook(() => useDocsVersion()).result.current, ).toThrowErrorMatchingInlineSnapshot( `"Hook useDocsVersion is called outside the <DocsVersionProvider>. "`, ); }); it('reads value from context provider', () => { const version = testVersion(); const {result} = renderHook(() => useDocsVersion(), { wrapper: ({children}) => ( <DocsVersionProvider version={version}>{children}</DocsVersionProvider> ), }); expect(result.current).toBe(version); }); });
1,740
0
petrpan-code/facebook/docusaurus/packages/docusaurus-theme-common/src/utils
petrpan-code/facebook/docusaurus/packages/docusaurus-theme-common/src/utils/__tests__/codeBlockUtils.test.ts
/** * Copyright (c) Facebook, Inc. and its affiliates. * * This source code is licensed under the MIT license found in the * LICENSE file in the root directory of this source tree. */ import { type MagicCommentConfig, parseCodeBlockTitle, parseLanguage, parseLines, } from '../codeBlockUtils'; describe('parseCodeBlockTitle', () => { it('parses double quote delimited title', () => { expect(parseCodeBlockTitle(`title="index.js"`)).toBe(`index.js`); }); it('parses single quote delimited title', () => { expect(parseCodeBlockTitle(`title='index.js'`)).toBe(`index.js`); }); it('does not parse mismatched quote delimiters', () => { expect(parseCodeBlockTitle(`title="index.js'`)).toBe(``); }); it('parses undefined metastring', () => { expect(parseCodeBlockTitle(undefined)).toBe(``); }); it('parses metastring with no title specified', () => { expect(parseCodeBlockTitle(`{1,2-3}`)).toBe(``); }); it('parses with multiple metadata title first', () => { expect(parseCodeBlockTitle(`title="index.js" label="JavaScript"`)).toBe( `index.js`, ); }); it('parses with multiple metadata title last', () => { expect(parseCodeBlockTitle(`label="JavaScript" title="index.js"`)).toBe( `index.js`, ); }); it('parses double quotes when delimited by single quotes', () => { expect(parseCodeBlockTitle(`title='console.log("Hello, World!")'`)).toBe( `console.log("Hello, World!")`, ); }); it('parses single quotes when delimited by double quotes', () => { expect(parseCodeBlockTitle(`title="console.log('Hello, World!')"`)).toBe( `console.log('Hello, World!')`, ); }); }); describe('parseLanguage', () => { it('works', () => { expect(parseLanguage('language-foo xxx yyy')).toBe('foo'); expect(parseLanguage('xxxxx language-foo yyy')).toBe('foo'); expect(parseLanguage('xx-language-foo yyyy')).toBeUndefined(); expect(parseLanguage('xxx yyy zzz')).toBeUndefined(); }); }); describe('parseLines', () => { const defaultMagicComments: MagicCommentConfig[] = [ { className: 'theme-code-block-highlighted-line', line: 'highlight-next-line', block: {start: 'highlight-start', end: 'highlight-end'}, }, ]; it('does not parse content with metastring', () => { expect( parseLines('aaaaa\nnnnnn', { metastring: '{1}', language: 'js', magicComments: defaultMagicComments, }), ).toMatchSnapshot(); expect( parseLines( `// highlight-next-line aaaaa bbbbb`, { metastring: '{1}', language: 'js', magicComments: defaultMagicComments, }, ), ).toMatchSnapshot(); expect( parseLines( `aaaaa bbbbb`, { metastring: '{1}', language: 'undefined', magicComments: defaultMagicComments, }, ), ).toMatchSnapshot(); expect(() => parseLines( `aaaaa bbbbb`, { metastring: '{1}', language: 'js', magicComments: [], }, ), ).toThrowErrorMatchingInlineSnapshot( `"A highlight range has been given in code block's metastring (\`\`\` {1}), but no magic comment config is available. Docusaurus applies the first magic comment entry's className for metastring ranges."`, ); }); it('does not parse content with no language', () => { expect( parseLines( `// highlight-next-line aaaaa bbbbb`, { metastring: '', language: undefined, magicComments: defaultMagicComments, }, ), ).toMatchSnapshot(); }); it('removes lines correctly', () => { expect( parseLines( `// highlight-next-line aaaaa bbbbb`, {metastring: '', language: 'js', magicComments: defaultMagicComments}, ), ).toMatchSnapshot(); expect( parseLines( `// highlight-start aaaaa // highlight-end bbbbb`, {metastring: '', language: 'js', magicComments: defaultMagicComments}, ), ).toMatchSnapshot(); expect( parseLines( `// highlight-start // highlight-next-line aaaaa bbbbbbb // highlight-next-line // highlight-end bbbbb`, {metastring: '', language: 'js', magicComments: defaultMagicComments}, ), ).toMatchSnapshot(); }); it('respects language', () => { expect( parseLines( `# highlight-next-line aaaaa bbbbb`, {metastring: '', language: 'js', magicComments: defaultMagicComments}, ), ).toMatchSnapshot('js'); expect( parseLines( `/* highlight-next-line */ aaaaa bbbbb`, {metastring: '', language: 'py', magicComments: defaultMagicComments}, ), ).toMatchSnapshot('py'); expect( parseLines( `// highlight-next-line aaaa /* highlight-next-line */ bbbbb # highlight-next-line ccccc <!-- highlight-next-line --> dddd`, {metastring: '', language: 'py', magicComments: defaultMagicComments}, ), ).toMatchSnapshot('py'); expect( parseLines( `// highlight-next-line aaaa /* highlight-next-line */ bbbbb # highlight-next-line ccccc <!-- highlight-next-line --> dddd`, {metastring: '', language: '', magicComments: defaultMagicComments}, ), ).toMatchSnapshot('none'); expect( parseLines( `// highlight-next-line aaaa {/* highlight-next-line */} bbbbb <!-- highlight-next-line --> dddd`, {metastring: '', language: 'jsx', magicComments: defaultMagicComments}, ), ).toMatchSnapshot('jsx'); expect( parseLines( `// highlight-next-line aaaa {/* highlight-next-line */} bbbbb <!-- highlight-next-line --> dddd`, {metastring: '', language: 'html', magicComments: defaultMagicComments}, ), ).toMatchSnapshot('html'); expect( parseLines( `--- # highlight-next-line aaa: boo --- aaaa <div> {/* highlight-next-line */} foo </div> bbbbb <!-- highlight-next-line --> dddd \`\`\`js // highlight-next-line console.log("preserved"); \`\`\` `, {metastring: '', language: 'md', magicComments: defaultMagicComments}, ), ).toMatchSnapshot('md'); }); it('parses multiple types of magic comments', () => { expect( parseLines( ` // highlight-next-line highlighted // collapse-next-line collapsed /* collapse-start */ collapsed collapsed /* collapse-end */ `, { language: 'js', metastring: '', magicComments: [ { className: 'highlight', line: 'highlight-next-line', block: {start: 'highlight-start', end: 'highlight-end'}, }, { className: 'collapse', line: 'collapse-next-line', block: {start: 'collapse-start', end: 'collapse-end'}, }, ], }, ), ).toMatchSnapshot(); }); it('handles one line with multiple class names', () => { expect( parseLines( ` // highlight-next-line // collapse-next-line highlighted and collapsed /* collapse-start */ /* highlight-start */ highlighted and collapsed highlighted and collapsed /* collapse-end */ Only highlighted /* highlight-end */ /* collapse-start */ Only collapsed /* highlight-start */ highlighted and collapsed highlighted and collapsed /* highlight-end */ Only collapsed // highlight-next-line highlighted and collapsed /* collapse-end */ `, { language: 'js', metastring: '', magicComments: [ { className: 'highlight', line: 'highlight-next-line', block: {start: 'highlight-start', end: 'highlight-end'}, }, { className: 'collapse', line: 'collapse-next-line', block: {start: 'collapse-start', end: 'collapse-end'}, }, ], }, ), ).toMatchSnapshot(); expect( parseLines( `// a // b // c // d line // b // d line `, { language: 'js', metastring: '', magicComments: [ {className: 'a', line: 'a'}, {className: 'b', line: 'b'}, {className: 'c', line: 'c'}, {className: 'd', line: 'd'}, ], }, ), ).toMatchSnapshot(); }); });
1,741
0
petrpan-code/facebook/docusaurus/packages/docusaurus-theme-common/src/utils
petrpan-code/facebook/docusaurus/packages/docusaurus-theme-common/src/utils/__tests__/docsUtils.test.tsx
/** * Copyright (c) Facebook, Inc. and its affiliates. * * This source code is licensed under the MIT license found in the * LICENSE file in the root directory of this source tree. */ import React from 'react'; import {renderHook} from '@testing-library/react-hooks'; import {StaticRouter} from 'react-router-dom'; import {Context} from '@docusaurus/core/src/client/docusaurusContext'; import { findFirstSidebarItemLink, isActiveSidebarItem, useDocById, findSidebarCategory, useCurrentSidebarCategory, useSidebarBreadcrumbs, isVisibleSidebarItem, } from '../docsUtils'; import {DocsSidebarProvider} from '../../contexts/docsSidebar'; import {DocsVersionProvider} from '../../contexts/docsVersion'; import type { PropSidebar, PropSidebarItem, PropSidebarItemCategory, PropSidebarItemLink, PropVersionMetadata, } from '@docusaurus/plugin-content-docs'; import type {DocusaurusContext} from '@docusaurus/types'; // Make tests more readable with some useful category item defaults function testCategory( data?: Partial<PropSidebarItemCategory>, ): PropSidebarItemCategory { return { type: 'category', href: undefined, label: 'Category label', items: [], collapsed: true, collapsible: true, ...data, }; } function testLink(data?: Partial<PropSidebarItemLink>): PropSidebarItemLink { return { type: 'link', href: '/testLinkHref', label: 'Link label', ...data, }; } function testVersion(data?: Partial<PropVersionMetadata>): PropVersionMetadata { return { version: 'versionName', label: 'Version Label', className: 'version className', badge: true, banner: 'unreleased', docs: {}, docsSidebars: {}, isLast: false, pluginId: 'default', noIndex: false, ...data, }; } describe('useDocById', () => { const version = testVersion({ docs: { doc1: { id: 'doc1', title: 'Doc 1', description: 'desc1', sidebar: 'sidebar1', }, doc2: { id: 'doc2', title: 'Doc 2', description: 'desc2', sidebar: 'sidebar2', }, }, }); function mockUseDocById(docId: string | undefined) { const {result} = renderHook(() => useDocById(docId), { wrapper: ({children}) => ( <DocsVersionProvider version={version}>{children}</DocsVersionProvider> ), }); return result.current; } it('accepts undefined', () => { expect(mockUseDocById(undefined)).toBeUndefined(); }); it('finds doc1', () => { expect(mockUseDocById('doc1')).toMatchObject({id: 'doc1'}); }); it('finds doc2', () => { expect(mockUseDocById('doc2')).toMatchObject({id: 'doc2'}); }); it('throws for doc3', () => { expect(() => mockUseDocById('doc3')).toThrowErrorMatchingInlineSnapshot( `"no version doc found by id=doc3"`, ); }); }); describe('findSidebarCategory', () => { it('is able to return undefined', () => { expect(findSidebarCategory([], () => false)).toBeUndefined(); expect( findSidebarCategory([testCategory(), testCategory()], () => false), ).toBeUndefined(); }); it('returns first element matching predicate', () => { const first = testCategory(); const second = testCategory(); const third = testCategory(); const sidebar = [first, second, third]; expect(findSidebarCategory(sidebar, () => true)).toEqual(first); expect(findSidebarCategory(sidebar, (item) => item === first)).toEqual( first, ); expect(findSidebarCategory(sidebar, (item) => item === second)).toEqual( second, ); expect(findSidebarCategory(sidebar, (item) => item === third)).toEqual( third, ); }); it('is able to search in sub items', () => { const subsub1 = testCategory(); const subsub2 = testCategory(); const sub1 = testCategory({ items: [subsub1, subsub2], }); const sub2 = testCategory(); const parent = testCategory({ items: [sub1, sub2], }); const sidebar = [parent]; expect(findSidebarCategory(sidebar, () => true)).toEqual(parent); expect(findSidebarCategory(sidebar, (item) => item === sub1)).toEqual(sub1); expect(findSidebarCategory(sidebar, (item) => item === sub2)).toEqual(sub2); expect(findSidebarCategory(sidebar, (item) => item === subsub1)).toEqual( subsub1, ); expect(findSidebarCategory(sidebar, (item) => item === subsub2)).toEqual( subsub2, ); }); }); describe('findFirstCategoryLink', () => { it('works with html item', () => { const htmlItem = {type: 'html', value: '<div/>'} as const; expect(findFirstSidebarItemLink(htmlItem)).toBeUndefined(); expect(findFirstSidebarItemLink(htmlItem)).toBeUndefined(); }); it('works with link item', () => { const linkItem = { type: 'link', href: '/linkHref', label: 'Label', } as const; expect(findFirstSidebarItemLink(linkItem)).toBe('/linkHref'); expect( findFirstSidebarItemLink({ ...linkItem, unlisted: true, }), ).toBeUndefined(); }); it('works with category without link nor child', () => { expect( findFirstSidebarItemLink( testCategory({ href: undefined, }), ), ).toBeUndefined(); }); it('works with category with link', () => { expect( findFirstSidebarItemLink( testCategory({ href: '/itemPath', }), ), ).toBe('/itemPath'); }); it('works with deeply nested category', () => { expect( findFirstSidebarItemLink( testCategory({ href: '/category1', linkUnlisted: true, items: [ {type: 'html', value: '<p>test1</p>'}, testCategory({ href: '/category2', linkUnlisted: true, items: [ {type: 'html', value: '<p>test2</p>'}, testCategory({ href: '/category3', items: [ {type: 'html', value: '<p>test2</p>'}, testCategory({ href: '/category4', linkUnlisted: true, }), ], }), ], }), ], }), ), ).toBe('/category3'); }); it('works with deeply nested link', () => { expect( findFirstSidebarItemLink( testCategory({ href: '/category1', linkUnlisted: true, items: [ { type: 'link', href: '/itemPathUnlisted', label: 'Label', unlisted: true, }, testCategory({ href: '/category2', linkUnlisted: true, items: [ testCategory({ href: '/category3', linkUnlisted: true, items: [ { type: 'link', href: '/itemPathUnlisted2', label: 'Label', unlisted: true, }, testCategory({ href: '/category4', linkUnlisted: true, }), { type: 'link', href: '/itemPathListed1', label: 'Label', }, testCategory({ href: '/category5', }), { type: 'link', href: '/itemPathListed2', label: 'Label', unlisted: true, }, ], }), ], }), ], }), ), ).toBe('/itemPathListed1'); }); it('works with category with deeply nested category link unlisted', () => { expect( findFirstSidebarItemLink( testCategory({ href: undefined, items: [ {type: 'html', value: '<p>test1</p>'}, testCategory({ href: undefined, items: [ {type: 'html', value: '<p>test2</p>'}, testCategory({ href: '/itemPath', linkUnlisted: true, }), ], }), ], }), ), ).toBeUndefined(); }); it('works with category with deeply nested link unlisted', () => { expect( findFirstSidebarItemLink( testCategory({ href: undefined, items: [ testCategory({ href: undefined, items: [ { type: 'link', href: '/itemPath', label: 'Label', unlisted: true, }, ], }), ], }), ), ).toBeUndefined(); }); }); describe('isActiveSidebarItem', () => { it('works with link href', () => { const item: PropSidebarItem = { type: 'link', href: '/itemPath', label: 'Label', }; expect(isActiveSidebarItem(item, '/nonexistentPath')).toBe(false); expect(isActiveSidebarItem(item, '/itemPath')).toBe(true); // Ensure it's not trailing slash sensitive: expect(isActiveSidebarItem(item, '/itemPath/')).toBe(true); expect( isActiveSidebarItem({...item, href: '/itemPath/'}, '/itemPath'), ).toBe(true); }); it('works with category href', () => { const item: PropSidebarItem = testCategory({ href: '/itemPath', }); expect(isActiveSidebarItem(item, '/nonexistentPath')).toBe(false); expect(isActiveSidebarItem(item, '/itemPath')).toBe(true); // Ensure it's not trailing slash sensitive: expect(isActiveSidebarItem(item, '/itemPath/')).toBe(true); expect( isActiveSidebarItem({...item, href: '/itemPath/'}, '/itemPath'), ).toBe(true); }); it('works with category nested items', () => { const item: PropSidebarItem = testCategory({ href: '/category-path', items: [ { type: 'link', href: '/sub-link-path', label: 'Label', }, testCategory({ href: '/sub-category-path', items: [ { type: 'link', href: '/sub-sub-link-path', label: 'Label', }, ], }), ], }); expect(isActiveSidebarItem(item, '/nonexistentPath')).toBe(false); expect(isActiveSidebarItem(item, '/category-path')).toBe(true); expect(isActiveSidebarItem(item, '/sub-link-path')).toBe(true); expect(isActiveSidebarItem(item, '/sub-category-path')).toBe(true); expect(isActiveSidebarItem(item, '/sub-sub-link-path')).toBe(true); // Ensure it's not trailing slash sensitive: expect(isActiveSidebarItem(item, '/category-path/')).toBe(true); expect(isActiveSidebarItem(item, '/sub-link-path/')).toBe(true); expect(isActiveSidebarItem(item, '/sub-category-path/')).toBe(true); expect(isActiveSidebarItem(item, '/sub-sub-link-path/')).toBe(true); }); }); describe('isVisibleSidebarItem', () => { it('works with item', () => { const item: PropSidebarItem = { type: 'link', href: '/itemPath', label: 'Label', }; expect(isVisibleSidebarItem(item, item.href)).toBe(true); expect(isVisibleSidebarItem(item, '/nonexistentPath/')).toBe(true); expect(isVisibleSidebarItem({...item, unlisted: false}, item.href)).toBe( true, ); expect( isVisibleSidebarItem({...item, unlisted: undefined}, item.href), ).toBe(true); expect(isVisibleSidebarItem({...item, unlisted: true}, item.href)).toBe( true, ); expect( isVisibleSidebarItem({...item, unlisted: true}, '/nonexistentPath/'), ).toBe(false); }); it('works with category', () => { const subCategoryAllUnlisted = testCategory({ href: '/sub-category-path', items: [ { type: 'link', href: '/sub-sub-link-path', label: 'Label', unlisted: true, }, { type: 'link', href: '/sub-sub-link-path', label: 'Label', unlisted: true, }, testCategory({ href: '/sub-sub-category-path', items: [ { type: 'link', href: '/sub-sub-sub-link-path', label: 'Label', unlisted: true, }, ], }), ], }); expect( isVisibleSidebarItem(subCategoryAllUnlisted, '/nonexistentPath'), ).toBe(false); expect( isVisibleSidebarItem( subCategoryAllUnlisted, subCategoryAllUnlisted.href!, ), ).toBe(true); expect( isVisibleSidebarItem(subCategoryAllUnlisted, '/sub-sub-link-path'), ).toBe(true); expect( isVisibleSidebarItem(subCategoryAllUnlisted, '/sub-sub-sub-link-path'), ).toBe(true); const categorySomeUnlisted = testCategory({ href: '/category-path', items: [ { type: 'link', href: '/sub-link-path', label: 'Label', }, subCategoryAllUnlisted, ], }); expect(isVisibleSidebarItem(categorySomeUnlisted, '/nonexistentPath')).toBe( true, ); expect( isVisibleSidebarItem(categorySomeUnlisted, categorySomeUnlisted.href!), ).toBe(true); }); }); describe('useSidebarBreadcrumbs', () => { const createUseSidebarBreadcrumbsMock = (sidebar: PropSidebar | undefined, breadcrumbsOption?: boolean) => (location: string) => renderHook(() => useSidebarBreadcrumbs(), { wrapper: ({children}) => ( <StaticRouter location={location}> <Context.Provider value={ { globalData: { 'docusaurus-plugin-content-docs': { default: {path: '/', breadcrumbs: breadcrumbsOption}, }, }, } as unknown as DocusaurusContext }> <DocsSidebarProvider name="sidebarName" items={sidebar}> {children} </DocsSidebarProvider> </Context.Provider> </StaticRouter> ), }).result.current; it('returns empty for empty sidebar', () => { expect(createUseSidebarBreadcrumbsMock([])('/doesNotExist')).toEqual([]); }); it('returns empty for sidebar but unknown pathname', () => { const sidebar = [testCategory(), testLink()]; expect(createUseSidebarBreadcrumbsMock(sidebar)('/doesNotExist')).toEqual( [], ); }); it('returns first level category', () => { const pathname = '/somePathName'; const sidebar = [testCategory({href: pathname}), testLink()]; expect(createUseSidebarBreadcrumbsMock(sidebar)(pathname)).toEqual([ sidebar[0], ]); }); it('returns first level link', () => { const pathname = '/somePathName'; const sidebar = [testCategory(), testLink({href: pathname})]; expect(createUseSidebarBreadcrumbsMock(sidebar)(pathname)).toEqual([ sidebar[1], ]); }); it('returns nested category', () => { const pathname = '/somePathName'; const categoryLevel3 = testCategory({ href: pathname, }); const categoryLevel2 = testCategory({ items: [ testCategory(), categoryLevel3, testLink({href: pathname}), testLink(), ], }); const categoryLevel1 = testCategory({ items: [testLink(), categoryLevel2], }); const sidebar = [ testLink(), testCategory(), categoryLevel1, testLink(), testCategory(), ]; expect(createUseSidebarBreadcrumbsMock(sidebar)(pathname)).toEqual([ categoryLevel1, categoryLevel2, categoryLevel3, ]); }); it('returns nested link', () => { const pathname = '/somePathName'; const link = testLink({href: pathname}); const categoryLevel3 = testCategory({ items: [testLink(), link, testLink()], }); const categoryLevel2 = testCategory({ items: [ testCategory(), categoryLevel3, testLink({href: pathname}), testLink(), ], }); const categoryLevel1 = testCategory({ items: [testLink(), categoryLevel2], }); const sidebar = [ testLink(), testCategory(), categoryLevel1, testLink(), testCategory(), ]; expect(createUseSidebarBreadcrumbsMock(sidebar)(pathname)).toEqual([ categoryLevel1, categoryLevel2, categoryLevel3, link, ]); }); it('returns null when breadcrumbs disabled', () => { expect(createUseSidebarBreadcrumbsMock([], false)('/foo')).toBeNull(); }); it('returns null when there is no sidebar', () => { expect( createUseSidebarBreadcrumbsMock(undefined, false)('/foo'), ).toBeNull(); }); }); describe('useCurrentSidebarCategory', () => { const createUseCurrentSidebarCategoryMock = (sidebar?: PropSidebar) => (location: string) => renderHook(() => useCurrentSidebarCategory(), { wrapper: ({children}) => ( <DocsSidebarProvider name="sidebarName" items={sidebar}> <StaticRouter location={location}>{children}</StaticRouter> </DocsSidebarProvider> ), }).result.current; it('works for sidebar category', () => { const category: PropSidebarItemCategory = testCategory({ href: '/cat', }); const sidebar: PropSidebar = [ testLink(), testLink(), category, testCategory(), ]; const mockUseCurrentSidebarCategory = createUseCurrentSidebarCategoryMock(sidebar); expect(mockUseCurrentSidebarCategory('/cat')).toEqual(category); }); it('works for nested sidebar category', () => { const category2: PropSidebarItemCategory = testCategory({ href: '/cat2', }); const category1: PropSidebarItemCategory = testCategory({ href: '/cat1', items: [testLink(), testLink(), category2, testCategory()], }); const sidebar: PropSidebar = [ testLink(), testLink(), category1, testCategory(), ]; const mockUseCurrentSidebarCategory = createUseCurrentSidebarCategoryMock(sidebar); expect(mockUseCurrentSidebarCategory('/cat2')).toEqual(category2); }); it('works for category link item', () => { const link = testLink({href: '/my/link/path'}); const category: PropSidebarItemCategory = testCategory({ href: '/cat1', items: [testLink(), testLink(), link, testCategory()], }); const sidebar: PropSidebar = [ testLink(), testLink(), category, testCategory(), ]; const mockUseCurrentSidebarCategory = createUseCurrentSidebarCategoryMock(sidebar); expect(mockUseCurrentSidebarCategory('/my/link/path')).toEqual(category); }); it('works for nested category link item', () => { const link = testLink({href: '/my/link/path'}); const category2: PropSidebarItemCategory = testCategory({ href: '/cat2', items: [testLink(), testLink(), link, testCategory()], }); const category1: PropSidebarItemCategory = testCategory({ href: '/cat1', items: [testLink(), testLink(), category2, testCategory()], }); const sidebar: PropSidebar = [ testLink(), testLink(), category1, testCategory(), ]; const mockUseCurrentSidebarCategory = createUseCurrentSidebarCategoryMock(sidebar); expect(mockUseCurrentSidebarCategory('/my/link/path')).toEqual(category2); }); it('throws for non-category index page', () => { const category: PropSidebarItemCategory = { type: 'category', label: 'Category', collapsible: true, collapsed: false, items: [ {type: 'link', href: '/cat/foo', label: 'Foo'}, {type: 'link', href: '/cat/bar', label: 'Bar'}, {type: 'link', href: '/baz', label: 'Baz'}, ], }; const mockUseCurrentSidebarCategory = createUseCurrentSidebarCategoryMock([ category, ]); expect(() => mockUseCurrentSidebarCategory('/cat'), ).toThrowErrorMatchingInlineSnapshot( `"/cat is not associated with a category. useCurrentSidebarCategory() should only be used on category index pages."`, ); }); it('throws when sidebar is missing', () => { const mockUseCurrentSidebarCategory = createUseCurrentSidebarCategoryMock(); expect(() => mockUseCurrentSidebarCategory('/cat'), ).toThrowErrorMatchingInlineSnapshot( `"Unexpected: cant find current sidebar in context"`, ); }); });
1,742
0
petrpan-code/facebook/docusaurus/packages/docusaurus-theme-common/src/utils
petrpan-code/facebook/docusaurus/packages/docusaurus-theme-common/src/utils/__tests__/footerUtils.test.ts
/** * Copyright (c) Facebook, Inc. and its affiliates. * * This source code is licensed under the MIT license found in the * LICENSE file in the root directory of this source tree. */ import {isMultiColumnFooterLinks} from '../footerUtils'; describe('isMultiColumnFooterLinks', () => { it('works', () => { expect( isMultiColumnFooterLinks([ { title: 'section', items: [ {href: '/foo', label: 'Foo'}, {href: '/bar', label: 'Bar'}, ], }, { title: 'section2', items: [ {href: '/foo', label: 'Foo2'}, {href: '/bar', label: 'Bar2'}, ], }, ]), ).toBe(true); expect( isMultiColumnFooterLinks([ {href: '/foo', label: 'Foo'}, {href: '/bar', label: 'Bar'}, ]), ).toBe(false); }); });
1,743
0
petrpan-code/facebook/docusaurus/packages/docusaurus-theme-common/src/utils
petrpan-code/facebook/docusaurus/packages/docusaurus-theme-common/src/utils/__tests__/generalUtils.test.tsx
/** * Copyright (c) Facebook, Inc. and its affiliates. * * This source code is licensed under the MIT license found in the * LICENSE file in the root directory of this source tree. */ import React from 'react'; import {renderHook} from '@testing-library/react-hooks'; import {Context} from '@docusaurus/core/src/client/docusaurusContext'; import {useTitleFormatter} from '../generalUtils'; import type {DocusaurusContext} from '@docusaurus/types'; describe('useTitleFormatter', () => { const createUseTitleFormatterMock = (context: DocusaurusContext) => (title?: string) => renderHook(() => useTitleFormatter(title), { wrapper: ({children}) => ( <Context.Provider value={context}>{children}</Context.Provider> ), }).result.current; it('works', () => { const mockUseTitleFormatter = createUseTitleFormatterMock({ siteConfig: { title: 'my site', titleDelimiter: '·', }, } as DocusaurusContext); expect(mockUseTitleFormatter('a page')).toBe('a page · my site'); expect(mockUseTitleFormatter(undefined)).toBe('my site'); expect(mockUseTitleFormatter(' ')).toBe('my site'); }); });
1,744
0
petrpan-code/facebook/docusaurus/packages/docusaurus-theme-common/src/utils
petrpan-code/facebook/docusaurus/packages/docusaurus-theme-common/src/utils/__tests__/jsUtils.test.ts
/** * Copyright (c) Facebook, Inc. and its affiliates. * * This source code is licensed under the MIT license found in the * LICENSE file in the root directory of this source tree. */ import {uniq, duplicates} from '../jsUtils'; describe('duplicates', () => { it('gets duplicate values', () => { expect(duplicates(['a', 'b', 'c', 'd'])).toEqual([]); expect(duplicates(['a', 'b', 'b', 'b'])).toEqual(['b', 'b']); expect(duplicates(['c', 'b', 'b', 'c'])).toEqual(['b', 'c']); expect(duplicates([{a: 1}, {a: 1}, {a: 1}])).toEqual([]); }); it('accepts custom comparator', () => { expect(duplicates([{a: 1}, {a: 1}, {a: 1}], (a, b) => a.a === b.a)).toEqual( [{a: 1}, {a: 1}], ); expect(duplicates(['a', 'b', 'c', 'd'], (a, b) => a !== b)).toEqual([ 'a', 'b', 'c', 'd', ]); }); }); describe('uniq', () => { it('remove duplicate primitives', () => { expect(uniq(['A', 'B', 'C', 'B', 'A', 'D'])).toEqual(['A', 'B', 'C', 'D']); expect(uniq([3, 3, 5, 1, 6, 3, 5])).toEqual([3, 5, 1, 6]); expect(uniq([null, undefined, 3, null, 4, 3])).toEqual([ null, undefined, 3, 4, ]); }); it('remove duplicate objects/arrays by identity', () => { const obj1 = {}; const obj2 = {}; const obj3 = {}; const array1: unknown[] = []; const array2: unknown[] = []; const array3: unknown[] = []; expect( uniq([obj1, obj1, obj2, array1, obj2, array3, array2, array1, obj3]), ).toEqual([obj1, obj2, array1, array3, array2, obj3]); }); });
1,745
0
petrpan-code/facebook/docusaurus/packages/docusaurus-theme-common/src/utils
petrpan-code/facebook/docusaurus/packages/docusaurus-theme-common/src/utils/__tests__/reactUtils.test.ts
/** * Copyright (c) Facebook, Inc. and its affiliates. * * This source code is licensed under the MIT license found in the * LICENSE file in the root directory of this source tree. */ import {renderHook} from '@testing-library/react-hooks'; import {usePrevious, useShallowMemoObject} from '../reactUtils'; describe('usePrevious', () => { it('returns the previous value of a variable', () => { const {result, rerender} = renderHook((val) => usePrevious(val), { initialProps: 1, }); expect(result.current).toBeUndefined(); rerender(2); expect(result.current).toBe(1); rerender(3); expect(result.current).toBe(2); }); }); describe('useShallowMemoObject', () => { it('can memoize object', () => { const someObj = {hello: 'world'}; const someArray = ['hello', 'world']; const obj1 = {a: 1, b: '2', someObj, someArray}; const {result, rerender} = renderHook<object, object>( (val) => useShallowMemoObject(val), { initialProps: obj1, }, ); expect(result.current).toBe(obj1); const obj2 = {a: 1, b: '2', someObj, someArray}; rerender(obj2); expect(result.current).toBe(obj1); const obj3 = {a: 1, b: '2', someObj, someArray}; rerender(obj3); expect(result.current).toBe(obj1); const obj4 = {b: '2', a: 1, someObj, someArray}; rerender(obj4); expect(result.current).toBe(obj1); const obj5 = {b: '2', a: 1, someObj, someArray}; rerender(obj5); expect(result.current).toBe(obj1); const obj6 = {b: 1, a: '2', someObj, someArray}; rerender(obj6); expect(result.current).toBe(obj6); expect(result.current).not.toBe(obj5); const obj7 = {b: 1, a: '2', someObj: {...someObj}, someArray}; rerender(obj7); expect(result.current).toBe(obj7); expect(result.current).not.toBe(obj6); const obj8 = {...obj7}; rerender(obj8); expect(result.current).toBe(obj7); const obj9 = {...obj7, another: true}; rerender(obj9); expect(result.current).toBe(obj9); expect(result.current).not.toBe(obj7); }); });
1,746
0
petrpan-code/facebook/docusaurus/packages/docusaurus-theme-common/src/utils
petrpan-code/facebook/docusaurus/packages/docusaurus-theme-common/src/utils/__tests__/regexpUtils.test.ts
/** * Copyright (c) Facebook, Inc. and its affiliates. * * This source code is licensed under the MIT license found in the * LICENSE file in the root directory of this source tree. */ import {isRegexpStringMatch} from '../regexpUtils'; describe('isRegexpStringMatch', () => { it('works', () => { expect(isRegexpStringMatch(undefined, 'foo')).toBe(false); expect(isRegexpStringMatch('bar', undefined)).toBe(false); expect(isRegexpStringMatch('foo', 'bar')).toBe(false); expect(isRegexpStringMatch('foo', 'foo')).toBe(true); // cSpell:ignore fooooooooooo expect(isRegexpStringMatch('fooooooooooo', 'foo')).toBe(false); expect(isRegexpStringMatch('foo', 'fooooooooooo')).toBe(true); expect(isRegexpStringMatch('f.*o', 'fooooooooooo')).toBe(true); expect(isRegexpStringMatch('FOO', 'foo')).toBe(true); }); });
1,747
0
petrpan-code/facebook/docusaurus/packages/docusaurus-theme-common/src/utils
petrpan-code/facebook/docusaurus/packages/docusaurus-theme-common/src/utils/__tests__/routesUtils.test.ts
/** * Copyright (c) Facebook, Inc. and its affiliates. * * This source code is licensed under the MIT license found in the * LICENSE file in the root directory of this source tree. */ import {findHomePageRoute, isSamePath} from '../routesUtils'; import type {RouteConfig} from 'react-router-config'; describe('isSamePath', () => { it('returns true for compared path without trailing slash', () => { expect(isSamePath('/docs', '/docs')).toBeTruthy(); }); it('returns true for compared path with trailing slash', () => { expect(isSamePath('/docs', '/docs/')).toBeTruthy(); }); it('returns true for compared path with different case', () => { expect(isSamePath('/doCS', '/DOcs')).toBeTruthy(); }); it('returns true for compared path with different case + trailing slash', () => { expect(isSamePath('/doCS', '/DOcs/')).toBeTruthy(); }); it('returns false for compared path with double trailing slash', () => { expect(isSamePath('/docs', '/docs//')).toBeFalsy(); }); it('returns true for twice undefined/null', () => { expect(isSamePath(undefined, undefined)).toBeTruthy(); expect(isSamePath(undefined, undefined)).toBeTruthy(); }); it('returns false when one undefined', () => { expect(isSamePath('/docs', undefined)).toBeFalsy(); expect(isSamePath(undefined, '/docs')).toBeFalsy(); }); }); describe('findHomePageRoute', () => { const homePage: RouteConfig = { path: '/', exact: true, }; it('returns undefined for no routes', () => { expect(findHomePageRoute({baseUrl: '/', routes: []})).toBeUndefined(); }); it('returns undefined for no homepage', () => { expect( findHomePageRoute({ baseUrl: '/', routes: [ {path: '/a', exact: true}, {path: '/b', exact: false}, {path: '/c', exact: undefined}, { path: '/d', exact: false, routes: [ {path: '/d/1', exact: true}, {path: '/d/2', exact: false}, {path: '/d/3', exact: undefined}, ], }, ], }), ).toBeUndefined(); }); it('finds top-level homepage', () => { expect( findHomePageRoute({ baseUrl: '/', routes: [ {path: '/a', exact: true}, {path: '/b', exact: false}, {path: '/c', exact: undefined}, {...homePage, exact: false}, homePage, {...homePage, exact: undefined}, ], }), ).toEqual(homePage); }); it('finds nested homepage', () => { expect( findHomePageRoute({ baseUrl: '/', routes: [ {path: '/a', exact: true}, { path: '/', exact: false, routes: [ {path: '/b', exact: true}, { path: '/', exact: undefined, routes: [{path: '/c', exact: true}, homePage], }, ], }, {path: '/d', exact: true}, ], }), ).toEqual(homePage); }); it('finds nested homepage with baseUrl', () => { const baseUrl = '/baseUrl/'; const baseUrlHomePage = {...homePage, path: baseUrl}; expect( findHomePageRoute({ baseUrl, routes: [ {path: `${baseUrl}a`, exact: true}, { path: baseUrl, exact: false, routes: [ {path: `${baseUrl}b`, exact: true}, { path: baseUrl, exact: false, routes: [{path: `${baseUrl}c`, exact: true}, baseUrlHomePage], }, ], }, {path: `${baseUrl}d`, exact: true}, ], }), ).toEqual(baseUrlHomePage); }); });
1,748
0
petrpan-code/facebook/docusaurus/packages/docusaurus-theme-common/src/utils
petrpan-code/facebook/docusaurus/packages/docusaurus-theme-common/src/utils/__tests__/searchUtils.test.ts
/** * Copyright (c) Facebook, Inc. and its affiliates. * * This source code is licensed under the MIT license found in the * LICENSE file in the root directory of this source tree. */ import {docVersionSearchTag} from '../searchUtils'; describe('docVersionSearchTag', () => { it('works', () => { expect(docVersionSearchTag('foo', 'bar')).toBe('docs-foo-bar'); }); });
1,749
0
petrpan-code/facebook/docusaurus/packages/docusaurus-theme-common/src/utils
petrpan-code/facebook/docusaurus/packages/docusaurus-theme-common/src/utils/__tests__/tagUtils.test.ts
/** * Copyright (c) Facebook, Inc. and its affiliates. * * This source code is licensed under the MIT license found in the * LICENSE file in the root directory of this source tree. */ import _ from 'lodash'; import {listTagsByLetters} from '../tagsUtils'; describe('listTagsByLetters', () => { type Param = Parameters<typeof listTagsByLetters>[0]; type Tag = Param[number]; type Result = ReturnType<typeof listTagsByLetters>; it('creates letters list', () => { const tag1: Tag = { label: 'tag1', permalink: '/tag1', count: 1, }; const tag2: Tag = { label: 'Tag2', permalink: '/tag2', count: 11, }; const tagZxy: Tag = { label: 'zxy', permalink: '/zxy', count: 987, }; const tagAbc: Tag = { label: 'Abc', permalink: '/abc', count: 123, }; const tagDef: Tag = { label: 'def', permalink: '/def', count: 1, }; const tagAaa: Tag = { label: 'aaa', permalink: '/aaa', count: 10, }; const expectedResult: Result = [ {letter: 'A', tags: [tagAaa, tagAbc]}, {letter: 'D', tags: [tagDef]}, {letter: 'T', tags: [tag1, tag2]}, {letter: 'Z', tags: [tagZxy]}, ]; // Input order shouldn't matter, output is always consistently sorted expect( listTagsByLetters([tag1, tag2, tagZxy, tagAbc, tagDef, tagAaa]), ).toEqual(expectedResult); expect( listTagsByLetters([tagZxy, tagDef, tagAaa, tag2, tagAbc, tag1]), ).toEqual(expectedResult); expect( listTagsByLetters( _.shuffle([tagZxy, tagDef, tagAaa, tag2, tagAbc, tag1]), ), ).toEqual(expectedResult); }); });
1,750
0
petrpan-code/facebook/docusaurus/packages/docusaurus-theme-common/src/utils
petrpan-code/facebook/docusaurus/packages/docusaurus-theme-common/src/utils/__tests__/tocUtils.test.ts
/** * Copyright (c) Facebook, Inc. and its affiliates. * * This source code is licensed under the MIT license found in the * LICENSE file in the root directory of this source tree. */ import {renderHook} from '@testing-library/react-hooks'; import {useFilteredAndTreeifiedTOC, useTreeifiedTOC} from '../tocUtils'; import type {TOCItem} from '@docusaurus/mdx-loader'; const mockTOC: TOCItem[] = [ { id: 'bravo', level: 2, value: 'Bravo', }, { id: 'charlie', level: 3, value: 'Charlie', }, { id: 'delta', level: 4, value: 'Delta', }, { id: 'echo', level: 5, value: 'Echo', }, { id: 'foxtrot', level: 6, value: 'Foxtrot', }, ]; describe('useTreeifiedTOC', () => { it('treeifies TOC without filtering', () => { expect( renderHook(() => useTreeifiedTOC(mockTOC)).result.current, ).toMatchSnapshot(); }); }); describe('useFilteredAndTreeifiedTOC', () => { it('filters a toc with all heading levels', () => { expect( renderHook(() => useFilteredAndTreeifiedTOC({ toc: mockTOC, minHeadingLevel: 2, maxHeadingLevel: 2, }), ).result.current, ).toEqual([ { id: 'bravo', level: 2, value: 'Bravo', children: [], }, ]); expect( renderHook(() => useFilteredAndTreeifiedTOC({ toc: mockTOC, minHeadingLevel: 3, maxHeadingLevel: 3, }), ).result.current, ).toEqual([ { id: 'charlie', level: 3, value: 'Charlie', children: [], }, ]); expect( renderHook(() => useFilteredAndTreeifiedTOC({ toc: mockTOC, minHeadingLevel: 2, maxHeadingLevel: 3, }), ).result.current, ).toEqual([ { id: 'bravo', level: 2, value: 'Bravo', children: [ { id: 'charlie', level: 3, value: 'Charlie', children: [], }, ], }, ]); expect( renderHook(() => useFilteredAndTreeifiedTOC({ toc: mockTOC, minHeadingLevel: 2, maxHeadingLevel: 4, }), ).result.current, ).toEqual([ { id: 'bravo', level: 2, value: 'Bravo', children: [ { id: 'charlie', level: 3, value: 'Charlie', children: [ { id: 'delta', level: 4, value: 'Delta', children: [], }, ], }, ], }, ]); }); // It's not 100% clear exactly how the TOC should behave under weird heading // levels provided by the user. Adding a test so that behavior stays the same // over time it('filters invalid heading levels (but possible) TOC', () => { const toc: TOCItem[] = [ { id: 'charlie', level: 3, value: 'Charlie', }, { id: 'bravo', level: 2, value: 'Bravo', }, { id: 'delta', level: 4, value: 'Delta', }, ]; expect( renderHook(() => useFilteredAndTreeifiedTOC({ toc, minHeadingLevel: 2, maxHeadingLevel: 2, }), ).result.current, ).toEqual([ { id: 'bravo', level: 2, value: 'Bravo', children: [], }, ]); expect( renderHook(() => useFilteredAndTreeifiedTOC({ toc, minHeadingLevel: 3, maxHeadingLevel: 3, }), ).result.current, ).toEqual([ { id: 'charlie', level: 3, value: 'Charlie', children: [], }, ]); expect( renderHook(() => useFilteredAndTreeifiedTOC({ toc, minHeadingLevel: 4, maxHeadingLevel: 4, }), ).result.current, ).toEqual([ { id: 'delta', level: 4, value: 'Delta', children: [], }, ]); expect( renderHook(() => useFilteredAndTreeifiedTOC({ toc, minHeadingLevel: 2, maxHeadingLevel: 3, }), ).result.current, ).toEqual([ { id: 'charlie', level: 3, value: 'Charlie', children: [], }, { id: 'bravo', level: 2, value: 'Bravo', children: [], }, ]); expect( renderHook(() => useFilteredAndTreeifiedTOC({ toc, minHeadingLevel: 3, maxHeadingLevel: 4, }), ).result.current, ).toEqual([ { id: 'charlie', level: 3, value: 'Charlie', children: [], }, { id: 'delta', level: 4, value: 'Delta', children: [], }, ]); }); });
1,751
0
petrpan-code/facebook/docusaurus/packages/docusaurus-theme-common/src/utils
petrpan-code/facebook/docusaurus/packages/docusaurus-theme-common/src/utils/__tests__/useAlternatePageUtils.test.tsx
/** * Copyright (c) Facebook, Inc. and its affiliates. * * This source code is licensed under the MIT license found in the * LICENSE file in the root directory of this source tree. */ import React from 'react'; import {renderHook} from '@testing-library/react-hooks'; import {StaticRouter} from 'react-router-dom'; import {Context} from '@docusaurus/core/src/client/docusaurusContext'; import {useAlternatePageUtils} from '../useAlternatePageUtils'; import type {DocusaurusContext} from '@docusaurus/types'; describe('useAlternatePageUtils', () => { const createUseAlternatePageUtilsMock = (context: DocusaurusContext) => (location: string) => renderHook(() => useAlternatePageUtils(), { wrapper: ({children}) => ( <Context.Provider value={context}> <StaticRouter location={location}>{children}</StaticRouter> </Context.Provider> ), }).result.current; it('works for baseUrl: / and currentLocale = defaultLocale', () => { const mockUseAlternatePageUtils = createUseAlternatePageUtilsMock({ siteConfig: {baseUrl: '/', url: 'https://example.com'}, i18n: {defaultLocale: 'en', currentLocale: 'en'}, } as DocusaurusContext); expect( mockUseAlternatePageUtils('/').createUrl({ locale: 'zh-Hans', fullyQualified: false, }), ).toBe('/zh-Hans/'); expect( mockUseAlternatePageUtils('/foo').createUrl({ locale: 'zh-Hans', fullyQualified: false, }), ).toBe('/zh-Hans/foo'); expect( mockUseAlternatePageUtils('/foo').createUrl({ locale: 'zh-Hans', fullyQualified: true, }), ).toBe('https://example.com/zh-Hans/foo'); }); it('works for baseUrl: / and currentLocale /= defaultLocale', () => { const mockUseAlternatePageUtils = createUseAlternatePageUtilsMock({ siteConfig: {baseUrl: '/zh-Hans/', url: 'https://example.com'}, i18n: {defaultLocale: 'en', currentLocale: 'zh-Hans'}, } as DocusaurusContext); expect( mockUseAlternatePageUtils('/zh-Hans/').createUrl({ locale: 'en', fullyQualified: false, }), ).toBe('/'); expect( mockUseAlternatePageUtils('/zh-Hans/foo').createUrl({ locale: 'en', fullyQualified: false, }), ).toBe('/foo'); expect( mockUseAlternatePageUtils('/zh-Hans/foo').createUrl({ locale: 'en', fullyQualified: true, }), ).toBe('https://example.com/foo'); }); it('works for non-root base URL and currentLocale = defaultLocale', () => { const mockUseAlternatePageUtils = createUseAlternatePageUtilsMock({ siteConfig: {baseUrl: '/base/', url: 'https://example.com'}, i18n: {defaultLocale: 'en', currentLocale: 'en'}, } as DocusaurusContext); expect( mockUseAlternatePageUtils('/base/').createUrl({ locale: 'zh-Hans', fullyQualified: false, }), ).toBe('/base/zh-Hans/'); expect( mockUseAlternatePageUtils('/base/foo').createUrl({ locale: 'zh-Hans', fullyQualified: false, }), ).toBe('/base/zh-Hans/foo'); expect( mockUseAlternatePageUtils('/base/foo').createUrl({ locale: 'zh-Hans', fullyQualified: true, }), ).toBe('https://example.com/base/zh-Hans/foo'); }); it('works for non-root base URL and currentLocale /= defaultLocale', () => { const mockUseAlternatePageUtils = createUseAlternatePageUtilsMock({ siteConfig: {baseUrl: '/base/zh-Hans/', url: 'https://example.com'}, i18n: {defaultLocale: 'en', currentLocale: 'zh-Hans'}, } as DocusaurusContext); expect( mockUseAlternatePageUtils('/base/zh-Hans/').createUrl({ locale: 'en', fullyQualified: false, }), ).toBe('/base/'); expect( mockUseAlternatePageUtils('/base/zh-Hans/foo').createUrl({ locale: 'en', fullyQualified: false, }), ).toBe('/base/foo'); expect( mockUseAlternatePageUtils('/base/zh-Hans/foo').createUrl({ locale: 'en', fullyQualified: true, }), ).toBe('https://example.com/base/foo'); }); });
1,752
0
petrpan-code/facebook/docusaurus/packages/docusaurus-theme-common/src/utils
petrpan-code/facebook/docusaurus/packages/docusaurus-theme-common/src/utils/__tests__/useLocalPathname.test.tsx
/** * Copyright (c) Facebook, Inc. and its affiliates. * * This source code is licensed under the MIT license found in the * LICENSE file in the root directory of this source tree. */ import React from 'react'; import {renderHook} from '@testing-library/react-hooks'; import {StaticRouter} from 'react-router-dom'; import {Context} from '@docusaurus/core/src/client/docusaurusContext'; import {useLocalPathname} from '../useLocalPathname'; import type {DocusaurusContext} from '@docusaurus/types'; describe('useLocalPathname', () => { const createUseLocalPathnameMock = (context: DocusaurusContext) => (location: string) => renderHook(() => useLocalPathname(), { wrapper: ({children}) => ( <Context.Provider value={context}> <StaticRouter location={location}>{children}</StaticRouter> </Context.Provider> ), }).result.current; it('works for baseUrl: /', () => { const mockUseLocalPathname = createUseLocalPathnameMock({ siteConfig: {baseUrl: '/'}, } as DocusaurusContext); expect(mockUseLocalPathname('/foo')).toBe('/foo'); }); it('works for non-root baseUrl', () => { const mockUseLocalPathname = createUseLocalPathnameMock({ siteConfig: {baseUrl: '/base/'}, } as DocusaurusContext); expect(mockUseLocalPathname('/base/foo')).toBe('/foo'); }); });
1,753
0
petrpan-code/facebook/docusaurus/packages/docusaurus-theme-common/src/utils
petrpan-code/facebook/docusaurus/packages/docusaurus-theme-common/src/utils/__tests__/usePluralForm.test.tsx
/** * Copyright (c) Facebook, Inc. and its affiliates. * * This source code is licensed under the MIT license found in the * LICENSE file in the root directory of this source tree. */ import {jest} from '@jest/globals'; import React from 'react'; import {renderHook} from '@testing-library/react-hooks'; import {Context} from '@docusaurus/core/src/client/docusaurusContext'; import {usePluralForm} from '../usePluralForm'; import type {DocusaurusContext} from '@docusaurus/types'; describe('usePluralForm', () => { const createUsePluralFormMock = (context: DocusaurusContext) => () => renderHook(() => usePluralForm(), { wrapper: ({children}) => ( <Context.Provider value={context}>{children}</Context.Provider> ), }).result.current; it('returns the right plural', () => { const mockUsePluralForm = createUsePluralFormMock({ i18n: { currentLocale: 'en', }, } as DocusaurusContext); expect(mockUsePluralForm().selectMessage(1, 'one|many')).toBe('one'); expect(mockUsePluralForm().selectMessage(10, 'one|many')).toBe('many'); }); it('warns against too many plurals', () => { const mockUsePluralForm = createUsePluralFormMock({ i18n: { currentLocale: 'zh-Hans', }, } as DocusaurusContext); const consoleMock = jest .spyOn(console, 'error') .mockImplementation(() => {}); expect(mockUsePluralForm().selectMessage(1, 'one|many')).toBe('one'); expect(mockUsePluralForm().selectMessage(10, 'one|many')).toBe('one'); expect(consoleMock.mock.calls[0]![0]).toMatchInlineSnapshot( `"For locale=zh-Hans, a maximum of 1 plural forms are expected (other), but the message contains 2: one|many"`, ); }); it('uses the last with not enough plurals', () => { const mockUsePluralForm = createUsePluralFormMock({ i18n: { currentLocale: 'en', }, } as DocusaurusContext); expect(mockUsePluralForm().selectMessage(10, 'many')).toBe('many'); }); it('falls back when Intl.PluralForms is not available', () => { const mockUsePluralForm = createUsePluralFormMock({ i18n: { currentLocale: 'zh-Hans', }, } as DocusaurusContext); const consoleMock = jest .spyOn(console, 'error') .mockImplementation(() => {}); const pluralMock = jest .spyOn(Intl, 'PluralRules') // @ts-expect-error: for testing when it doesn't exist .mockImplementation(() => undefined); expect(mockUsePluralForm().selectMessage(1, 'one|many')).toBe('one'); expect(mockUsePluralForm().selectMessage(10, 'one|many')).toBe('many'); expect(consoleMock.mock.calls[0]![0]).toMatchInlineSnapshot(` "Failed to use Intl.PluralRules for locale "zh-Hans". Docusaurus will fallback to the default (English) implementation. Error: pluralRules.resolvedOptions is not a function " `); pluralMock.mockRestore(); }); });
1,754
0
petrpan-code/facebook/docusaurus/packages/docusaurus-theme-common/src/utils/__tests__
petrpan-code/facebook/docusaurus/packages/docusaurus-theme-common/src/utils/__tests__/__snapshots__/codeBlockUtils.test.ts.snap
// Jest Snapshot v1, https://goo.gl/fbAQLP exports[`parseLines does not parse content with metastring 1`] = ` { "code": "aaaaa nnnnn", "lineClassNames": { "0": [ "theme-code-block-highlighted-line", ], }, } `; exports[`parseLines does not parse content with metastring 2`] = ` { "code": "// highlight-next-line aaaaa bbbbb", "lineClassNames": { "0": [ "theme-code-block-highlighted-line", ], }, } `; exports[`parseLines does not parse content with metastring 3`] = ` { "code": "aaaaa bbbbb", "lineClassNames": { "0": [ "theme-code-block-highlighted-line", ], }, } `; exports[`parseLines does not parse content with no language 1`] = ` { "code": "// highlight-next-line aaaaa bbbbb", "lineClassNames": {}, } `; exports[`parseLines handles one line with multiple class names 1`] = ` { "code": " highlighted and collapsed highlighted and collapsed highlighted and collapsed Only highlighted Only collapsed highlighted and collapsed highlighted and collapsed Only collapsed highlighted and collapsed", "lineClassNames": { "1": [ "highlight", "collapse", ], "2": [ "highlight", "collapse", ], "3": [ "highlight", "collapse", ], "4": [ "highlight", ], "5": [ "collapse", ], "6": [ "highlight", "collapse", ], "7": [ "highlight", "collapse", ], "8": [ "collapse", ], "9": [ "highlight", "collapse", ], }, } `; exports[`parseLines handles one line with multiple class names 2`] = ` { "code": "line line", "lineClassNames": { "0": [ "a", "b", "c", "d", ], "1": [ "b", "d", ], }, } `; exports[`parseLines parses multiple types of magic comments 1`] = ` { "code": " highlighted collapsed collapsed collapsed", "lineClassNames": { "1": [ "highlight", ], "2": [ "collapse", ], "3": [ "collapse", ], "4": [ "collapse", ], }, } `; exports[`parseLines removes lines correctly 1`] = ` { "code": "aaaaa bbbbb", "lineClassNames": { "0": [ "theme-code-block-highlighted-line", ], }, } `; exports[`parseLines removes lines correctly 2`] = ` { "code": "aaaaa bbbbb", "lineClassNames": { "0": [ "theme-code-block-highlighted-line", ], }, } `; exports[`parseLines removes lines correctly 3`] = ` { "code": "aaaaa bbbbbbb bbbbb", "lineClassNames": { "0": [ "theme-code-block-highlighted-line", "theme-code-block-highlighted-line", ], "1": [ "theme-code-block-highlighted-line", ], "2": [ "theme-code-block-highlighted-line", ], }, } `; exports[`parseLines respects language: html 1`] = ` { "code": "aaaa {/* highlight-next-line */} bbbbb dddd", "lineClassNames": { "0": [ "theme-code-block-highlighted-line", ], "3": [ "theme-code-block-highlighted-line", ], }, } `; exports[`parseLines respects language: js 1`] = ` { "code": "# highlight-next-line aaaaa bbbbb", "lineClassNames": {}, } `; exports[`parseLines respects language: jsx 1`] = ` { "code": "aaaa bbbbb <!-- highlight-next-line --> dddd", "lineClassNames": { "0": [ "theme-code-block-highlighted-line", ], "1": [ "theme-code-block-highlighted-line", ], }, } `; exports[`parseLines respects language: md 1`] = ` { "code": "--- aaa: boo --- aaaa <div> foo </div> bbbbb dddd \`\`\`js // highlight-next-line console.log("preserved"); \`\`\`", "lineClassNames": { "1": [ "theme-code-block-highlighted-line", ], "11": [ "theme-code-block-highlighted-line", ], "7": [ "theme-code-block-highlighted-line", ], }, } `; exports[`parseLines respects language: none 1`] = ` { "code": "aaaa bbbbb ccccc dddd", "lineClassNames": { "0": [ "theme-code-block-highlighted-line", ], "1": [ "theme-code-block-highlighted-line", ], "2": [ "theme-code-block-highlighted-line", ], "3": [ "theme-code-block-highlighted-line", ], }, } `; exports[`parseLines respects language: py 1`] = ` { "code": "/* highlight-next-line */ aaaaa bbbbb", "lineClassNames": {}, } `; exports[`parseLines respects language: py 2`] = ` { "code": "// highlight-next-line aaaa /* highlight-next-line */ bbbbb ccccc <!-- highlight-next-line --> dddd", "lineClassNames": { "4": [ "theme-code-block-highlighted-line", ], }, } `;
1,755
0
petrpan-code/facebook/docusaurus/packages/docusaurus-theme-common/src/utils/__tests__
petrpan-code/facebook/docusaurus/packages/docusaurus-theme-common/src/utils/__tests__/__snapshots__/tocUtils.test.ts.snap
// Jest Snapshot v1, https://goo.gl/fbAQLP exports[`useTreeifiedTOC treeifies TOC without filtering 1`] = ` [ { "children": [ { "children": [ { "children": [ { "children": [ { "children": [], "id": "foxtrot", "level": 6, "value": "Foxtrot", }, ], "id": "echo", "level": 5, "value": "Echo", }, ], "id": "delta", "level": 4, "value": "Delta", }, ], "id": "charlie", "level": 3, "value": "Charlie", }, ], "id": "bravo", "level": 2, "value": "Bravo", }, ] `;
1,767
0
petrpan-code/facebook/docusaurus/packages/docusaurus-theme-live-codeblock/src
petrpan-code/facebook/docusaurus/packages/docusaurus-theme-live-codeblock/src/__tests__/validateThemeConfig.test.ts
/** * Copyright (c) Facebook, Inc. and its affiliates. * * This source code is licensed under the MIT license found in the * LICENSE file in the root directory of this source tree. */ import {validateThemeConfig, DEFAULT_CONFIG} from '../validateThemeConfig'; import type {Joi} from '@docusaurus/utils-validation'; function testValidateThemeConfig(themeConfig: {[key: string]: unknown}) { function validate( schema: Joi.ObjectSchema<{[key: string]: unknown}>, cfg: {[key: string]: unknown}, ) { const {value, error} = schema.validate(cfg, { convert: false, }); if (error) { throw error; } return value; } return validateThemeConfig({validate, themeConfig}); } describe('validateThemeConfig', () => { it('undefined config', () => { const liveCodeBlock = undefined; expect(testValidateThemeConfig({liveCodeBlock})).toEqual({ liveCodeBlock: { ...DEFAULT_CONFIG, }, }); }); it('nonexistent config', () => { expect(testValidateThemeConfig({})).toEqual({ liveCodeBlock: { ...DEFAULT_CONFIG, }, }); }); it('empty config', () => { const liveCodeBlock = {}; expect(testValidateThemeConfig({liveCodeBlock})).toEqual({ liveCodeBlock: { ...DEFAULT_CONFIG, }, }); }); it('playgroundPosition top', () => { const liveCodeBlock = { playgroundPosition: 'top', }; expect(testValidateThemeConfig({liveCodeBlock})).toEqual({ liveCodeBlock: { ...DEFAULT_CONFIG, ...liveCodeBlock, }, }); }); it('playgroundPosition bottom', () => { const liveCodeBlock = { playgroundPosition: 'bottom', }; expect(testValidateThemeConfig({liveCodeBlock})).toEqual({ liveCodeBlock: { ...DEFAULT_CONFIG, ...liveCodeBlock, }, }); }); it('playgroundPosition invalid string', () => { const liveCodeBlock = {playgroundPosition: 'invalid'}; expect(() => testValidateThemeConfig({liveCodeBlock}), ).toThrowErrorMatchingInlineSnapshot( `""liveCodeBlock.playgroundPosition" must be one of [top, bottom]"`, ); }); it('playgroundPosition invalid boolean', () => { const liveCodeBlock = {playgroundPosition: true}; expect(() => testValidateThemeConfig({liveCodeBlock}), ).toThrowErrorMatchingInlineSnapshot( `""liveCodeBlock.playgroundPosition" must be one of [top, bottom]"`, ); }); });
1,780
0
petrpan-code/facebook/docusaurus/packages/docusaurus-theme-mermaid/src
petrpan-code/facebook/docusaurus/packages/docusaurus-theme-mermaid/src/__tests__/validateThemeConfig.test.ts
/** * Copyright (c) Facebook, Inc. and its affiliates. * * This source code is licensed under the MIT license found in the * LICENSE file in the root directory of this source tree. */ import { validateThemeConfig, DEFAULT_THEME_CONFIG, } from '../validateThemeConfig'; import type {Joi} from '@docusaurus/utils-validation'; import type {ThemeConfig, UserThemeConfig} from '@docusaurus/theme-mermaid'; function testValidateThemeConfig(themeConfig: UserThemeConfig) { function validate( schema: Joi.ObjectSchema<ThemeConfig>, cfg: UserThemeConfig, ) { const {value, error} = schema.validate(cfg, { convert: false, }); if (error) { throw error; } return value; } return validateThemeConfig({validate, themeConfig}); } describe('validateThemeConfig', () => { it('undefined config', () => { const mermaid = undefined; expect(testValidateThemeConfig({mermaid})).toEqual(DEFAULT_THEME_CONFIG); }); it('nonexistent config', () => { expect(testValidateThemeConfig({})).toEqual(DEFAULT_THEME_CONFIG); }); it('empty config', () => { const mermaid = {}; expect(testValidateThemeConfig({mermaid})).toEqual(DEFAULT_THEME_CONFIG); }); it('theme', () => { const mermaid = { theme: { light: 'light', dark: 'dark', }, }; expect(testValidateThemeConfig({mermaid})).toEqual({ mermaid: { ...DEFAULT_THEME_CONFIG.mermaid, ...mermaid, }, }); }); it('mermaid options', () => { const mermaid = { options: { fontFamily: 'Ariel', }, }; expect(testValidateThemeConfig({mermaid})).toEqual({ mermaid: { ...DEFAULT_THEME_CONFIG.mermaid, ...mermaid, }, }); }); });
1,794
0
petrpan-code/facebook/docusaurus/packages/docusaurus-theme-search-algolia/src
petrpan-code/facebook/docusaurus/packages/docusaurus-theme-search-algolia/src/__tests__/validateThemeConfig.test.ts
/** * Copyright (c) Facebook, Inc. and its affiliates. * * This source code is licensed under the MIT license found in the * LICENSE file in the root directory of this source tree. */ import {DEFAULT_CONFIG, validateThemeConfig} from '../validateThemeConfig'; import type {Joi} from '@docusaurus/utils-validation'; function testValidateThemeConfig(themeConfig: {[key: string]: unknown}) { function validate( schema: Joi.ObjectSchema<{[key: string]: unknown}>, cfg: {[key: string]: unknown}, ) { const {value, error} = schema.validate(cfg, { convert: false, }); if (error) { throw error; } return value; } return validateThemeConfig({themeConfig, validate}); } describe('validateThemeConfig', () => { it('minimal config', () => { const algolia = { indexName: 'index', apiKey: 'apiKey', appId: 'BH4D9OD16A', }; expect(testValidateThemeConfig({algolia})).toEqual({ algolia: { ...DEFAULT_CONFIG, ...algolia, }, }); }); it('unknown attributes', () => { const algolia = { indexName: 'index', apiKey: 'apiKey', unknownKey: 'unknownKey', appId: 'BH4D9OD16A', }; expect(testValidateThemeConfig({algolia})).toEqual({ algolia: { ...DEFAULT_CONFIG, ...algolia, }, }); }); it('undefined config', () => { const algolia = undefined; expect(() => testValidateThemeConfig({algolia}), ).toThrowErrorMatchingInlineSnapshot(`""themeConfig.algolia" is required"`); }); it('undefined config 2', () => { expect(() => testValidateThemeConfig({}), ).toThrowErrorMatchingInlineSnapshot(`""themeConfig.algolia" is required"`); }); it('missing indexName config', () => { const algolia = {apiKey: 'apiKey', appId: 'BH4D9OD16A'}; expect(() => testValidateThemeConfig({algolia}), ).toThrowErrorMatchingInlineSnapshot(`""algolia.indexName" is required"`); }); it('missing apiKey config', () => { const algolia = {indexName: 'indexName', appId: 'BH4D9OD16A'}; expect(() => testValidateThemeConfig({algolia}), ).toThrowErrorMatchingInlineSnapshot(`""algolia.apiKey" is required"`); }); it('missing appId config', () => { const algolia = {indexName: 'indexName', apiKey: 'apiKey'}; expect(() => testValidateThemeConfig({algolia}), ).toThrowErrorMatchingInlineSnapshot( `""algolia.appId" is required. If you haven't migrated to the new DocSearch infra, please refer to the blog post for instructions: https://docusaurus.io/blog/2021/11/21/algolia-docsearch-migration"`, ); }); it('contextualSearch config', () => { const algolia = { appId: 'BH4D9OD16A', indexName: 'index', apiKey: 'apiKey', contextualSearch: true, }; expect(testValidateThemeConfig({algolia})).toEqual({ algolia: { ...DEFAULT_CONFIG, ...algolia, }, }); }); it('externalUrlRegex config', () => { const algolia = { appId: 'BH4D9OD16A', indexName: 'index', apiKey: 'apiKey', externalUrlRegex: 'http://external-domain.com', }; expect(testValidateThemeConfig({algolia})).toEqual({ algolia: { ...DEFAULT_CONFIG, ...algolia, }, }); }); describe('replaceSearchResultPathname', () => { it('escapes from string', () => { const algolia = { appId: 'BH4D9OD16A', indexName: 'index', apiKey: 'apiKey', replaceSearchResultPathname: { from: '/docs/some-\\special-.[regexp]{chars*}', to: '/abc', }, }; expect(testValidateThemeConfig({algolia})).toEqual({ algolia: { ...DEFAULT_CONFIG, ...algolia, replaceSearchResultPathname: { from: '/docs/some\\x2d\\\\special\\x2d\\.\\[regexp\\]\\{chars\\*\\}', to: '/abc', }, }, }); }); it('converts from regexp to string', () => { const algolia = { appId: 'BH4D9OD16A', indexName: 'index', apiKey: 'apiKey', replaceSearchResultPathname: { from: /^\/docs\/(?:1\.0|next)/, to: '/abc', }, }; expect(testValidateThemeConfig({algolia})).toEqual({ algolia: { ...DEFAULT_CONFIG, ...algolia, replaceSearchResultPathname: { from: '^\\/docs\\/(?:1\\.0|next)', to: '/abc', }, }, }); }); }); it('searchParameters.facetFilters search config', () => { const algolia = { appId: 'BH4D9OD16A', indexName: 'index', apiKey: 'apiKey', searchParameters: { facetFilters: ['version:1.0'], }, }; expect(testValidateThemeConfig({algolia})).toEqual({ algolia: { ...DEFAULT_CONFIG, ...algolia, }, }); }); });
1,811
0
petrpan-code/facebook/docusaurus/packages/docusaurus-theme-translations/locales
petrpan-code/facebook/docusaurus/packages/docusaurus-theme-translations/locales/__tests__/locales.test.ts
/** * Copyright (c) Facebook, Inc. and its affiliates. * * This source code is licensed under the MIT license found in the * LICENSE file in the root directory of this source tree. */ import path from 'path'; import fs from 'fs-extra'; import _ from 'lodash'; import {extractThemeCodeMessages} from '../../src/utils'; describe('theme translations', () => { it('has base messages files contain EXACTLY all the translations extracted from the theme. Please run "yarn workspace @docusaurus/theme-translations update" to keep base messages files up-to-date', async () => { const baseMessagesDirPath = path.join(__dirname, '../base'); const baseMessages = await fs .readdir(baseMessagesDirPath) .then((files) => Promise.all( files.map( (baseMessagesFile) => fs.readJSON( path.join(baseMessagesDirPath, baseMessagesFile), ) as Promise<{[key: string]: string}>, ), ), ) .then((translations) => Object.fromEntries( translations .map(Object.entries) .flat() .filter(([key]) => !key.endsWith('___DESCRIPTION')), ), ); const codeMessages = _.mapValues( await extractThemeCodeMessages(), (translation) => translation.message, ); expect(codeMessages).toEqual(baseMessages); }); });
1,964
0
petrpan-code/facebook/docusaurus/packages/docusaurus-theme-translations/src
petrpan-code/facebook/docusaurus/packages/docusaurus-theme-translations/src/__tests__/index.test.ts
/** * Copyright (c) Facebook, Inc. and its affiliates. * * This source code is licensed under the MIT license found in the * LICENSE file in the root directory of this source tree. */ import path from 'path'; import fs from 'fs-extra'; import { codeTranslationLocalesToTry, readDefaultCodeTranslationMessages, } from '../index'; describe('codeTranslationLocalesToTry', () => { it('returns appropriate locale lists', () => { expect(codeTranslationLocalesToTry('fr')).toEqual([ 'fr', 'fr-FR', 'fr-Latn', 'fr', ]); expect(codeTranslationLocalesToTry('fr-FR')).toEqual([ 'fr-FR', 'fr-FR', 'fr-Latn', 'fr', ]); // Note: "pt" is expanded into "pt-BR", not "pt-PT", as "pt-BR" is more // widely used! See https://github.com/facebook/docusaurus/pull/4536#issuecomment-810088783 expect(codeTranslationLocalesToTry('pt')).toEqual([ 'pt', 'pt-BR', 'pt-Latn', 'pt', ]); expect(codeTranslationLocalesToTry('pt-BR')).toEqual([ 'pt-BR', 'pt-BR', 'pt-Latn', 'pt', ]); expect(codeTranslationLocalesToTry('pt-PT')).toEqual([ 'pt-PT', 'pt-PT', 'pt-Latn', 'pt', ]); expect(codeTranslationLocalesToTry('zh')).toEqual([ 'zh', 'zh-CN', 'zh-Hans', 'zh', ]); expect(codeTranslationLocalesToTry('zh-cn')).toEqual([ 'zh-cn', 'zh-CN', 'zh-Hans', 'zh', ]); }); }); describe('readDefaultCodeTranslationMessages', () => { const dirPath = path.resolve( __dirname, '__fixtures__', 'defaultCodeTranslations', ); const name = 'default'; async function readAsJSON(locale: string, filename: string = name) { console.log(path.resolve(dirPath, locale, `${filename}.json`)); return fs.readJSON(path.resolve(dirPath, locale, `${filename}.json`)); } it('for empty locale', async () => { await expect( readDefaultCodeTranslationMessages({ name: 'default', locale: '', dirPath, }), ).rejects.toThrowErrorMatchingInlineSnapshot( `"First argument to Intl.Locale constructor can't be empty or missing"`, ); }); it('for nonexistent locale', async () => { await expect( readDefaultCodeTranslationMessages({ locale: 'es', dirPath, name, }), ).resolves.toEqual({}); }); it('for fr but bad folder', async () => { await expect( readDefaultCodeTranslationMessages({ locale: 'fr', dirPath: __dirname, name, }), ).resolves.toEqual({}); }); it('for fr', async () => { await expect( readDefaultCodeTranslationMessages({ locale: 'fr', dirPath, name, }), ).resolves.toEqual(await readAsJSON('fr')); }); it('for fr-FR', async () => { await expect( readDefaultCodeTranslationMessages({ locale: 'fr-FR', dirPath, name, }), ).resolves.toEqual(await readAsJSON('fr-FR')); }); it('for en', async () => { await expect( readDefaultCodeTranslationMessages({ locale: 'en', dirPath, name, }), ).resolves.toEqual(await readAsJSON('en')); }); it('for en-US', async () => { await expect( readDefaultCodeTranslationMessages({ locale: 'en-US', dirPath, name, }), ).resolves.toEqual(await readAsJSON('en')); }); it('for en-WHATEVER', async () => { await expect( readDefaultCodeTranslationMessages({ locale: 'en-WHATEVER', dirPath, name, }), ).resolves.toEqual(await readAsJSON('en')); }); it('default locale', async () => { await expect( readDefaultCodeTranslationMessages({ locale: 'zh', name: 'plugin-pwa', }), ).resolves.toEqual({ 'theme.PwaReloadPopup.closeButtonAriaLabel': '关闭', 'theme.PwaReloadPopup.info': '有可用的新版本', 'theme.PwaReloadPopup.refreshButtonText': '刷新', }); }); });
1,965
0
petrpan-code/facebook/docusaurus/packages/docusaurus-theme-translations/src
petrpan-code/facebook/docusaurus/packages/docusaurus-theme-translations/src/__tests__/utils.test.ts
/** * Copyright (c) Facebook, Inc. and its affiliates. * * This source code is licensed under the MIT license found in the * LICENSE file in the root directory of this source tree. */ import path from 'path'; import {extractThemeCodeMessages} from '../utils'; describe('extractThemeCodeMessages', () => { it('throws with invalid syntax', async () => { await expect(() => extractThemeCodeMessages([path.join(__dirname, '__fixtures__/theme')]), ).rejects.toThrowErrorMatchingInlineSnapshot(` " Please make sure all theme translations are static! Some warnings were found! Translate content could not be extracted. It has to be a static string and use optional but static props, like <Translate id="my-id" description="my-description">text</Translate>. File: packages/docusaurus-theme-translations/src/__tests__/__fixtures__/theme/index.js at line 4 Full code: <Translate>{index}</Translate> " `); }); });
1,990
0
petrpan-code/facebook/docusaurus/packages/docusaurus-utils-common/src
petrpan-code/facebook/docusaurus/packages/docusaurus-utils-common/src/__tests__/applyTrailingSlash.test.ts
/** * Copyright (c) Facebook, Inc. and its affiliates. * * This source code is licensed under the MIT license found in the * LICENSE file in the root directory of this source tree. */ import applyTrailingSlash, { type ApplyTrailingSlashParams, } from '../applyTrailingSlash'; function params( trailingSlash: boolean | undefined, baseUrl: string = '/', ): ApplyTrailingSlashParams { return {trailingSlash, baseUrl}; } describe('applyTrailingSlash', () => { it('applies to empty', () => { expect(applyTrailingSlash('', params(true))).toBe('/'); expect(applyTrailingSlash('', params(false))).toBe(''); expect(applyTrailingSlash('', params(undefined))).toBe(''); }); it('does not apply to /', () => { expect(applyTrailingSlash('/', params(true))).toBe('/'); expect(applyTrailingSlash('/', params(false))).toBe('/'); expect(applyTrailingSlash('/', params(undefined))).toBe('/'); expect(applyTrailingSlash('/?query#anchor', params(true))).toBe( '/?query#anchor', ); expect(applyTrailingSlash('/?query#anchor', params(false))).toBe( '/?query#anchor', ); expect(applyTrailingSlash('/?query#anchor', params(undefined))).toBe( '/?query#anchor', ); }); it('does not apply to /baseUrl/', () => { const baseUrl = '/baseUrl/'; expect(applyTrailingSlash('/baseUrl/', params(true, baseUrl))).toBe( '/baseUrl/', ); expect(applyTrailingSlash('/baseUrl/', params(false, baseUrl))).toBe( '/baseUrl/', ); expect(applyTrailingSlash('/baseUrl/', params(undefined, baseUrl))).toBe( '/baseUrl/', ); expect( applyTrailingSlash('/baseUrl/?query#anchor', params(true, baseUrl)), ).toBe('/baseUrl/?query#anchor'); expect( applyTrailingSlash('/baseUrl/?query#anchor', params(false, baseUrl)), ).toBe('/baseUrl/?query#anchor'); expect( applyTrailingSlash('/baseUrl/?query#anchor', params(undefined, baseUrl)), ).toBe('/baseUrl/?query#anchor'); }); it('does not apply to #anchor links', () => { expect(applyTrailingSlash('#', params(true))).toBe('#'); expect(applyTrailingSlash('#', params(false))).toBe('#'); expect(applyTrailingSlash('#', params(undefined))).toBe('#'); expect(applyTrailingSlash('#anchor', params(true))).toBe('#anchor'); expect(applyTrailingSlash('#anchor', params(false))).toBe('#anchor'); expect(applyTrailingSlash('#anchor', params(undefined))).toBe('#anchor'); }); it('applies to simple paths', () => { expect(applyTrailingSlash('abc', params(true))).toBe('abc/'); expect(applyTrailingSlash('abc', params(false))).toBe('abc'); expect(applyTrailingSlash('abc', params(undefined))).toBe('abc'); expect(applyTrailingSlash('abc/', params(true))).toBe('abc/'); expect(applyTrailingSlash('abc/', params(false))).toBe('abc'); expect(applyTrailingSlash('abc/', params(undefined))).toBe('abc/'); expect(applyTrailingSlash('/abc', params(true))).toBe('/abc/'); expect(applyTrailingSlash('/abc', params(false))).toBe('/abc'); expect(applyTrailingSlash('/abc', params(undefined))).toBe('/abc'); expect(applyTrailingSlash('/abc/', params(true))).toBe('/abc/'); expect(applyTrailingSlash('/abc/', params(false))).toBe('/abc'); expect(applyTrailingSlash('/abc/', params(undefined))).toBe('/abc/'); }); it('applies to path with #anchor', () => { expect(applyTrailingSlash('/abc#anchor', params(true))).toBe( '/abc/#anchor', ); expect(applyTrailingSlash('/abc#anchor', params(false))).toBe( '/abc#anchor', ); expect(applyTrailingSlash('/abc#anchor', params(undefined))).toBe( '/abc#anchor', ); expect(applyTrailingSlash('/abc/#anchor', params(true))).toBe( '/abc/#anchor', ); expect(applyTrailingSlash('/abc/#anchor', params(false))).toBe( '/abc#anchor', ); expect(applyTrailingSlash('/abc/#anchor', params(undefined))).toBe( '/abc/#anchor', ); }); it('applies to path with ?search', () => { expect(applyTrailingSlash('/abc?search', params(true))).toBe( '/abc/?search', ); expect(applyTrailingSlash('/abc?search', params(false))).toBe( '/abc?search', ); expect(applyTrailingSlash('/abc?search', params(undefined))).toBe( '/abc?search', ); expect(applyTrailingSlash('/abc/?search', params(true))).toBe( '/abc/?search', ); expect(applyTrailingSlash('/abc/?search', params(false))).toBe( '/abc?search', ); expect(applyTrailingSlash('/abc/?search', params(undefined))).toBe( '/abc/?search', ); }); it('applies to path with ?search#anchor', () => { expect(applyTrailingSlash('/abc?search#anchor', params(true))).toBe( '/abc/?search#anchor', ); expect(applyTrailingSlash('/abc?search#anchor', params(false))).toBe( '/abc?search#anchor', ); expect(applyTrailingSlash('/abc?search#anchor', params(undefined))).toBe( '/abc?search#anchor', ); expect(applyTrailingSlash('/abc/?search#anchor', params(true))).toBe( '/abc/?search#anchor', ); expect(applyTrailingSlash('/abc/?search#anchor', params(false))).toBe( '/abc?search#anchor', ); expect(applyTrailingSlash('/abc/?search#anchor', params(undefined))).toBe( '/abc/?search#anchor', ); }); it('applies to fully qualified urls', () => { expect( applyTrailingSlash('https://xyz.com/abc?search#anchor', params(true)), ).toBe('https://xyz.com/abc/?search#anchor'); expect( applyTrailingSlash('https://xyz.com/abc?search#anchor', params(false)), ).toBe('https://xyz.com/abc?search#anchor'); expect( applyTrailingSlash( 'https://xyz.com/abc?search#anchor', params(undefined), ), ).toBe('https://xyz.com/abc?search#anchor'); expect( applyTrailingSlash('https://xyz.com/abc/?search#anchor', params(true)), ).toBe('https://xyz.com/abc/?search#anchor'); expect( applyTrailingSlash('https://xyz.com/abc/?search#anchor', params(false)), ).toBe('https://xyz.com/abc?search#anchor'); expect( applyTrailingSlash( 'https://xyz.com/abc/?search#anchor', params(undefined), ), ).toBe('https://xyz.com/abc/?search#anchor'); }); });
1,991
0
petrpan-code/facebook/docusaurus/packages/docusaurus-utils-common/src
petrpan-code/facebook/docusaurus/packages/docusaurus-utils-common/src/__tests__/errorUtils.test.ts
/** * Copyright (c) Facebook, Inc. and its affiliates. * * This source code is licensed under the MIT license found in the * LICENSE file in the root directory of this source tree. */ import {getErrorCausalChain} from '../errorUtils'; describe('getErrorCausalChain', () => { it('works for simple error', () => { const error = new Error('msg'); expect(getErrorCausalChain(error)).toEqual([error]); }); it('works for nested errors', () => { const error = new Error('msg', { cause: new Error('msg', {cause: new Error('msg')}), }); expect(getErrorCausalChain(error)).toEqual([ error, error.cause, (error.cause as Error).cause, ]); }); });
2,001
0
petrpan-code/facebook/docusaurus/packages/docusaurus-utils-validation/src
petrpan-code/facebook/docusaurus/packages/docusaurus-utils-validation/src/__tests__/validationSchemas.test.ts
/** * Copyright (c) Facebook, Inc. and its affiliates. * * This source code is licensed under the MIT license found in the * LICENSE file in the root directory of this source tree. */ import Joi from '../Joi'; import { AdmonitionsSchema, RehypePluginsSchema, RemarkPluginsSchema, PluginIdSchema, URISchema, PathnameSchema, RouteBasePathSchema, ContentVisibilitySchema, } from '../validationSchemas'; function createTestHelpers({ schema, defaultValue, }: { schema: Joi.Schema; defaultValue?: unknown; }) { function testOK(value: unknown, options?: {normalizedValue?: unknown}) { const expectedValue = options?.normalizedValue ?? value ?? defaultValue; expect(Joi.attempt(value, schema)).toEqual(expectedValue); } function testFail(value: unknown) { expect(() => Joi.attempt(value, schema)).toThrowErrorMatchingSnapshot( `for value=${JSON.stringify(value)}`, ); } return {testOK, testFail}; } function testMarkdownPluginSchemas(schema: Joi.Schema) { const {testOK, testFail} = createTestHelpers({ schema, defaultValue: [], }); testOK(undefined); testOK([() => {}]); testOK([[() => {}, {attr: 'val'}]]); testOK([[() => {}, {attr: 'val'}], () => {}, [() => {}, {attr: 'val'}]]); // cSpell:ignore remarkjs // official `remarkjs/remark-frontmatter` plugin accepts string options testOK([[() => {}, 'string-option']]); testOK([[() => {}, true]]); testFail(null); testFail(false); testFail(3); testFail([null]); testFail([false]); testFail([3]); testFail([[]]); testFail([[() => {}, undefined]]); } describe('validation schemas', () => { it('pluginIdSchema', () => { const {testOK, testFail} = createTestHelpers({ schema: PluginIdSchema, defaultValue: 'default', }); testOK(undefined); testOK('docs'); testOK('default'); testOK('plugin-id_with-simple-special-chars'); testOK('doc1'); testFail('/docs'); testFail('docs/'); testFail('do/cs'); testFail('do cs'); testFail(null); testFail(3); testFail(true); testFail([]); }); it('admonitionsSchema', () => { const {testOK, testFail} = createTestHelpers({ schema: AdmonitionsSchema, defaultValue: true, }); testOK(undefined); testOK(true); testOK(false); testOK({}); testOK({keywords: ['info', 'tip']}); testOK({keywords: ['info', 'tip'], extendDefaults: true}); testOK({keywords: ['info', 'tip'], extendDefaults: false}); testOK({keywords: []}); testOK({keywords: [], extendDefaults: true}); // noop testOK({keywords: [], extendDefaults: false}); // disable admonitions testOK({keywords: ['custom-keyword'], extendDefaults: true}); testOK({keywords: ['custom-keyword'], extendDefaults: false}); testFail(3); testFail([]); testFail({unknownAttribute: 'val'}); testFail({tag: ''}); testFail({keywords: ['custom-keyword'], extendDefaults: 42}); testFail({tag: '+++'}); testFail({tag: '+++', keywords: ['info', 'tip']}); // Legacy types testFail({ infima: true, }); testFail({ icons: 'emoji', }); testFail({ customTypes: { myKeyword: { keyword: `myKeyword`, infima: true, svg: '<svg width="512px" height="512px" viewBox="0 0 512 512" xmlns="http://www.w3.org/2000/svg"></svg>', }, }, }); }); it('remarkPluginsSchema', () => { testMarkdownPluginSchemas(RemarkPluginsSchema); }); it('rehypePluginsSchema', () => { testMarkdownPluginSchemas(RehypePluginsSchema); }); it('uRISchema', () => { const {testFail, testOK} = createTestHelpers({schema: URISchema}); const validURL = 'https://docusaurus.io'; const doubleHash = 'https://docusaurus.io#github#/:'; const invalidURL = 'spaces are invalid in a URL'; const relativeURL = 'relativeURL'; const relativeURLWithParent = '../relativeURLWithParent'; const urlFromIssue = 'https://riot.im/app/#/room/#ligo-public:matrix.org'; testOK(validURL); testOK(doubleHash); testFail(invalidURL); testOK(relativeURL); testOK(relativeURLWithParent); testOK(urlFromIssue); const protocolRelativeUrl1 = '//docusaurus.io/path'; const protocolRelativeUrl2 = '//docusaurus.io/docs/doc1#hash'; testOK(protocolRelativeUrl1); testOK(protocolRelativeUrl2); }); it('pathnameSchema', () => { const {testFail, testOK} = createTestHelpers({schema: PathnameSchema}); testOK('/foo'); testFail('foo'); testFail('https://github.com/foo'); }); it('routeBasePathSchema', () => { const {testFail, testOK} = createTestHelpers({ schema: RouteBasePathSchema, defaultValue: undefined, }); testOK('', {normalizedValue: '/'}); testOK('/'); testOK('/foo', {normalizedValue: '/foo'}); testOK('foo', {normalizedValue: '/foo'}); testOK('blog', {normalizedValue: '/blog'}); testOK('blog/', {normalizedValue: '/blog/'}); testOK('prefix/blog', {normalizedValue: '/prefix/blog'}); testOK('prefix/blog/', {normalizedValue: '/prefix/blog/'}); testOK('/prefix/blog', {normalizedValue: '/prefix/blog'}); testOK(undefined); testFail(3); testFail([]); testFail(null); testFail({}); }); it('contentVisibilitySchema', () => { const {testFail, testOK} = createTestHelpers({ schema: ContentVisibilitySchema, }); testOK({}); testOK({draft: false}); testOK({draft: true}); testOK({unlisted: false}); testOK({unlisted: true}); testOK({draft: false, unlisted: false}); testOK({draft: true, unlisted: false}); testOK({draft: false, unlisted: true}); testOK({draft: true, unlisted: undefined}); testOK({draft: undefined, unlisted: true}); testFail({draft: 'bad string'}); testFail({draft: 42}); testFail({unlisted: 'bad string'}); testFail({unlisted: 42}); testFail({draft: true, unlisted: true}); }); });
2,002
0
petrpan-code/facebook/docusaurus/packages/docusaurus-utils-validation/src
petrpan-code/facebook/docusaurus/packages/docusaurus-utils-validation/src/__tests__/validationUtils.test.ts
/** * Copyright (c) Facebook, Inc. and its affiliates. * * This source code is licensed under the MIT license found in the * LICENSE file in the root directory of this source tree. */ import {jest} from '@jest/globals'; import Joi from '../Joi'; import {JoiFrontMatter} from '../JoiFrontMatter'; import { normalizePluginOptions, normalizeThemeConfig, validateFrontMatter, } from '../validationUtils'; describe('normalizePluginOptions', () => { it('always adds an "id" field', () => { const options = {id: 'a'}; expect( normalizePluginOptions( // "Malicious" schema that tries to forbid "id" Joi.object({id: Joi.any().forbidden()}), options, ), ).toEqual(options); expect( normalizePluginOptions(Joi.object({foo: Joi.string()}), undefined), ).toEqual({id: 'default'}); }); it('normalizes plugin options', () => { const options = {}; expect( normalizePluginOptions( Joi.object({foo: Joi.string().default('a')}), options, ), ).toEqual({foo: 'a', id: 'default'}); }); it('throws for invalid options', () => { const options = {foo: 1}; expect(() => normalizePluginOptions(Joi.object<object>({foo: Joi.string()}), options), ).toThrowErrorMatchingInlineSnapshot(`""foo" must be a string"`); }); it('warns', () => { const options = {foo: 'a'}; const consoleMock = jest .spyOn(console, 'warn') .mockImplementation(() => {}); expect( normalizePluginOptions( Joi.object({foo: Joi.string().warning('deprecated', {})}).messages({ deprecated: '{#label} deprecated', }), options, ), ).toEqual({foo: 'a', id: 'default'}); expect(consoleMock).toHaveBeenCalledWith( expect.stringMatching(/"foo" deprecated/), ); }); }); describe('normalizeThemeConfig', () => { it('always allows unknown attributes', () => { const themeConfig = {foo: 'a', bar: 1}; expect( normalizeThemeConfig( // "Malicious" schema that tries to forbid extra properties Joi.object({foo: Joi.string()}).unknown(false), themeConfig, ), ).toEqual(themeConfig); }); it('normalizes theme config', () => { const themeConfig = {bar: 1}; expect( normalizeThemeConfig( Joi.object({foo: Joi.string().default('a')}), themeConfig, ), ).toEqual({bar: 1, foo: 'a'}); }); it('throws for invalid options', () => { const themeConfig = {foo: 1, bar: 1}; expect(() => normalizeThemeConfig( Joi.object<object>({foo: Joi.string()}), themeConfig, ), ).toThrowErrorMatchingInlineSnapshot(`""foo" must be a string"`); }); it('warns', () => { const themeConfig = {foo: 'a', bar: 1}; const consoleMock = jest .spyOn(console, 'warn') .mockImplementation(() => {}); expect( normalizeThemeConfig( Joi.object({foo: Joi.string().warning('deprecated', {})}).messages({ deprecated: '{#label} deprecated', }), themeConfig, ), ).toEqual(themeConfig); expect(consoleMock).toHaveBeenCalledWith( expect.stringMatching(/"foo" deprecated/), ); }); }); describe('validateFrontMatter', () => { it('accepts good values', () => { const schema = Joi.object<{test: string}>({ test: Joi.string(), }); const frontMatter = { test: 'hello', }; expect(validateFrontMatter(frontMatter, schema)).toEqual(frontMatter); }); it('rejects bad values', () => { const consoleError = jest .spyOn(console, 'error') .mockImplementation(() => {}); const schema = Joi.object<{test: string}>({ test: Joi.string(), }); const frontMatter = { test: true, }; expect(() => validateFrontMatter(frontMatter, schema), ).toThrowErrorMatchingInlineSnapshot(`""test" must be a string"`); expect(consoleError).toHaveBeenCalledWith( expect.stringContaining('The following front matter'), ); }); it('does not convert simple values', () => { const schema = Joi.object({ test: JoiFrontMatter.string(), }); const frontMatter = { test: 'foo', tags: ['foo', 'bar'], }; expect(validateFrontMatter(frontMatter, schema)).toEqual(frontMatter); }); // Fix Yaml trying to convert strings to numbers automatically // We only want to deal with a single type in the final front matter // (not string | number) it('converts number values to string when string schema', () => { const schema = Joi.object<{test: string}>({ test: JoiFrontMatter.string(), }); const frontMatter = { test: 42, }; expect(validateFrontMatter(frontMatter, schema)).toEqual({test: '42'}); }); // Helps to fix Yaml trying to convert strings to dates automatically // We only want to deal with a single type in the final front matter // (not string | Date) it('converts date values when string schema', () => { const schema = Joi.object<{test: string}>({ test: JoiFrontMatter.string(), }); const date = new Date(); const frontMatter = { test: date, }; expect(validateFrontMatter(frontMatter, schema)).toEqual({ test: date.toString(), }); }); });
2,003
0
petrpan-code/facebook/docusaurus/packages/docusaurus-utils-validation/src/__tests__
petrpan-code/facebook/docusaurus/packages/docusaurus-utils-validation/src/__tests__/__snapshots__/validationSchemas.test.ts.snap
// Jest Snapshot v1, https://goo.gl/fbAQLP exports[`validation schemas admonitionsSchema: for value=[] 1`] = `""value" does not look like a valid admonitions config"`; exports[`validation schemas admonitionsSchema: for value={"customTypes":{"myKeyword":{"keyword":"myKeyword","infima":true,"svg":"<svg width=\\"512px\\" height=\\"512px\\" viewBox=\\"0 0 512 512\\" xmlns=\\"http://www.w3.org/2000/svg\\"></svg>"}}} 1`] = `""customTypes" is not allowed"`; exports[`validation schemas admonitionsSchema: for value={"icons":"emoji"} 1`] = `""icons" is not allowed"`; exports[`validation schemas admonitionsSchema: for value={"infima":true} 1`] = `""infima" is not allowed"`; exports[`validation schemas admonitionsSchema: for value={"keywords":["custom-keyword"],"extendDefaults":42} 1`] = `""extendDefaults" must be a boolean"`; exports[`validation schemas admonitionsSchema: for value={"tag":""} 1`] = `"It is not possible anymore to use a custom admonition tag. The only admonition tag supported is ':::' (Markdown Directive syntax)"`; exports[`validation schemas admonitionsSchema: for value={"tag":"+++","keywords":["info","tip"]} 1`] = `"It is not possible anymore to use a custom admonition tag. The only admonition tag supported is ':::' (Markdown Directive syntax)"`; exports[`validation schemas admonitionsSchema: for value={"tag":"+++"} 1`] = `"It is not possible anymore to use a custom admonition tag. The only admonition tag supported is ':::' (Markdown Directive syntax)"`; exports[`validation schemas admonitionsSchema: for value={"unknownAttribute":"val"} 1`] = `""unknownAttribute" is not allowed"`; exports[`validation schemas admonitionsSchema: for value=3 1`] = `""value" does not look like a valid admonitions config"`; exports[`validation schemas contentVisibilitySchema: for value={"draft":"bad string"} 1`] = `""draft" must be a boolean"`; exports[`validation schemas contentVisibilitySchema: for value={"draft":42} 1`] = `""draft" must be a boolean"`; exports[`validation schemas contentVisibilitySchema: for value={"draft":true,"unlisted":true} 1`] = `"Can't be draft and unlisted at the same time."`; exports[`validation schemas contentVisibilitySchema: for value={"unlisted":"bad string"} 1`] = `""unlisted" must be a boolean"`; exports[`validation schemas contentVisibilitySchema: for value={"unlisted":42} 1`] = `""unlisted" must be a boolean"`; exports[`validation schemas pathnameSchema: for value="foo" 1`] = `""value" (foo) is not a valid pathname. Pathname should start with slash and not contain any domain or query string."`; exports[`validation schemas pathnameSchema: for value="https://github.com/foo" 1`] = `""value" (https://github.com/foo) is not a valid pathname. Pathname should start with slash and not contain any domain or query string."`; exports[`validation schemas pluginIdSchema: for value="/docs" 1`] = `"Illegal plugin ID value "/docs": it should only contain alphanumerics, underscores, and dashes."`; exports[`validation schemas pluginIdSchema: for value="do cs" 1`] = `"Illegal plugin ID value "do cs": it should only contain alphanumerics, underscores, and dashes."`; exports[`validation schemas pluginIdSchema: for value="do/cs" 1`] = `"Illegal plugin ID value "do/cs": it should only contain alphanumerics, underscores, and dashes."`; exports[`validation schemas pluginIdSchema: for value="docs/" 1`] = `"Illegal plugin ID value "docs/": it should only contain alphanumerics, underscores, and dashes."`; exports[`validation schemas pluginIdSchema: for value=[] 1`] = `""value" must be a string"`; exports[`validation schemas pluginIdSchema: for value=3 1`] = `""value" must be a string"`; exports[`validation schemas pluginIdSchema: for value=null 1`] = `""value" must be a string"`; exports[`validation schemas pluginIdSchema: for value=true 1`] = `""value" must be a string"`; exports[`validation schemas rehypePluginsSchema: for value=[[]] 1`] = ` ""[0]" does not look like a valid MDX plugin config. A plugin config entry should be one of: - A tuple, like \`[require("rehype-katex"), { strict: false }]\`, or - A simple module, like \`require("remark-math")\`" `; exports[`validation schemas rehypePluginsSchema: for value=[[null,null]] 1`] = ` ""[0]" does not look like a valid MDX plugin config. A plugin config entry should be one of: - A tuple, like \`[require("rehype-katex"), { strict: false }]\`, or - A simple module, like \`require("remark-math")\`" `; exports[`validation schemas rehypePluginsSchema: for value=[3] 1`] = ` ""[0]" does not look like a valid MDX plugin config. A plugin config entry should be one of: - A tuple, like \`[require("rehype-katex"), { strict: false }]\`, or - A simple module, like \`require("remark-math")\`" `; exports[`validation schemas rehypePluginsSchema: for value=[false] 1`] = ` ""[0]" does not look like a valid MDX plugin config. A plugin config entry should be one of: - A tuple, like \`[require("rehype-katex"), { strict: false }]\`, or - A simple module, like \`require("remark-math")\`" `; exports[`validation schemas rehypePluginsSchema: for value=[null] 1`] = ` ""[0]" does not look like a valid MDX plugin config. A plugin config entry should be one of: - A tuple, like \`[require("rehype-katex"), { strict: false }]\`, or - A simple module, like \`require("remark-math")\`" `; exports[`validation schemas rehypePluginsSchema: for value=3 1`] = `""value" must be an array"`; exports[`validation schemas rehypePluginsSchema: for value=false 1`] = `""value" must be an array"`; exports[`validation schemas rehypePluginsSchema: for value=null 1`] = `""value" must be an array"`; exports[`validation schemas remarkPluginsSchema: for value=[[]] 1`] = ` ""[0]" does not look like a valid MDX plugin config. A plugin config entry should be one of: - A tuple, like \`[require("rehype-katex"), { strict: false }]\`, or - A simple module, like \`require("remark-math")\`" `; exports[`validation schemas remarkPluginsSchema: for value=[[null,null]] 1`] = ` ""[0]" does not look like a valid MDX plugin config. A plugin config entry should be one of: - A tuple, like \`[require("rehype-katex"), { strict: false }]\`, or - A simple module, like \`require("remark-math")\`" `; exports[`validation schemas remarkPluginsSchema: for value=[3] 1`] = ` ""[0]" does not look like a valid MDX plugin config. A plugin config entry should be one of: - A tuple, like \`[require("rehype-katex"), { strict: false }]\`, or - A simple module, like \`require("remark-math")\`" `; exports[`validation schemas remarkPluginsSchema: for value=[false] 1`] = ` ""[0]" does not look like a valid MDX plugin config. A plugin config entry should be one of: - A tuple, like \`[require("rehype-katex"), { strict: false }]\`, or - A simple module, like \`require("remark-math")\`" `; exports[`validation schemas remarkPluginsSchema: for value=[null] 1`] = ` ""[0]" does not look like a valid MDX plugin config. A plugin config entry should be one of: - A tuple, like \`[require("rehype-katex"), { strict: false }]\`, or - A simple module, like \`require("remark-math")\`" `; exports[`validation schemas remarkPluginsSchema: for value=3 1`] = `""value" must be an array"`; exports[`validation schemas remarkPluginsSchema: for value=false 1`] = `""value" must be an array"`; exports[`validation schemas remarkPluginsSchema: for value=null 1`] = `""value" must be an array"`; exports[`validation schemas routeBasePathSchema: for value=[] 1`] = `""value" must be a string"`; exports[`validation schemas routeBasePathSchema: for value={} 1`] = `""value" must be a string"`; exports[`validation schemas routeBasePathSchema: for value=3 1`] = `""value" must be a string"`; exports[`validation schemas routeBasePathSchema: for value=null 1`] = `""value" must be a string"`; exports[`validation schemas uRISchema: for value="spaces are invalid in a URL" 1`] = `""value" does not look like a valid url (value='')"`;
2,029
0
petrpan-code/facebook/docusaurus/packages/docusaurus-utils/src
petrpan-code/facebook/docusaurus/packages/docusaurus-utils/src/__tests__/dataFileUtils.test.ts
/** * Copyright (c) Facebook, Inc. and its affiliates. * * This source code is licensed under the MIT license found in the * LICENSE file in the root directory of this source tree. */ import path from 'path'; import { findFolderContainingFile, getFolderContainingFile, getDataFilePath, getDataFileData, } from '../dataFileUtils'; describe('getDataFilePath', () => { const fixturesDir = path.join(__dirname, '__fixtures__/dataFiles'); const contentPathYml1 = path.join(fixturesDir, 'contentPathYml1'); const contentPathYml2 = path.join(fixturesDir, 'contentPathYml2'); const contentPathJson1 = path.join(fixturesDir, 'contentPathJson1'); const contentPathJson2 = path.join(fixturesDir, 'contentPathJson2'); const contentPathEmpty = path.join(fixturesDir, 'contentPathEmpty'); const contentPathNestedYml = path.join(fixturesDir, 'contentPathNestedYml'); it('getDataFilePath returns localized Yml path in priority', async () => { await expect( getDataFilePath({ filePath: 'authors.yml', contentPaths: { contentPathLocalized: contentPathYml1, contentPath: contentPathYml2, }, }), ).resolves.toEqual(path.join(contentPathYml1, 'authors.yml')); await expect( getDataFilePath({ filePath: 'authors.yml', contentPaths: { contentPathLocalized: contentPathYml2, contentPath: contentPathYml1, }, }), ).resolves.toEqual(path.join(contentPathYml2, 'authors.yml')); }); it('getDataFilePath returns localized Json path in priority', async () => { await expect( getDataFilePath({ filePath: 'authors.json', contentPaths: { contentPathLocalized: contentPathJson1, contentPath: contentPathJson2, }, }), ).resolves.toEqual(path.join(contentPathJson1, 'authors.json')); await expect( getDataFilePath({ filePath: 'authors.json', contentPaths: { contentPathLocalized: contentPathJson2, contentPath: contentPathJson1, }, }), ).resolves.toEqual(path.join(contentPathJson2, 'authors.json')); }); it('getDataFilePath returns unlocalized Yml path as fallback', async () => { await expect( getDataFilePath({ filePath: 'authors.yml', contentPaths: { contentPathLocalized: contentPathEmpty, contentPath: contentPathYml2, }, }), ).resolves.toEqual(path.join(contentPathYml2, 'authors.yml')); }); it('getDataFilePath returns unlocalized Json path as fallback', async () => { await expect( getDataFilePath({ filePath: 'authors.json', contentPaths: { contentPathLocalized: contentPathEmpty, contentPath: contentPathJson1, }, }), ).resolves.toEqual(path.join(contentPathJson1, 'authors.json')); }); it('getDataFilePath can return undefined (file not found)', async () => { await expect( getDataFilePath({ filePath: 'authors.json', contentPaths: { contentPathLocalized: contentPathEmpty, contentPath: contentPathYml1, }, }), ).resolves.toBeUndefined(); await expect( getDataFilePath({ filePath: 'authors.yml', contentPaths: { contentPathLocalized: contentPathEmpty, contentPath: contentPathJson1, }, }), ).resolves.toBeUndefined(); }); it('getDataFilePath can return nested path', async () => { await expect( getDataFilePath({ filePath: 'sub/folder/authors.yml', contentPaths: { contentPathLocalized: contentPathEmpty, contentPath: contentPathNestedYml, }, }), ).resolves.toEqual( path.join(contentPathNestedYml, 'sub/folder/authors.yml'), ); }); }); describe('getDataFileData', () => { const fixturesDir = path.join(__dirname, '__fixtures__/dataFiles/actualData'); function readDataFile(filePath: string) { return getDataFileData( { filePath, contentPaths: {contentPath: fixturesDir, contentPathLocalized: ''}, fileType: 'test', }, (content) => { // @ts-expect-error: good enough if (content.a !== 1) { throw new Error('Nope'); } return content; }, ); } it('returns undefined for nonexistent file', async () => { await expect(readDataFile('nonexistent.yml')).resolves.toBeUndefined(); }); it('read valid yml author file', async () => { await expect(readDataFile('valid.yml')).resolves.toEqual({a: 1}); }); it('read valid json author file', async () => { await expect(readDataFile('valid.json')).resolves.toEqual({a: 1}); }); it('fail to read invalid yml', async () => { await expect( readDataFile('bad.yml'), ).rejects.toThrowErrorMatchingInlineSnapshot(`"Nope"`); }); it('fail to read invalid json', async () => { await expect( readDataFile('bad.json'), ).rejects.toThrowErrorMatchingInlineSnapshot(`"Nope"`); }); }); describe('findFolderContainingFile', () => { it('find appropriate folder', async () => { await expect( findFolderContainingFile( ['/foo', '/baz', __dirname, '/bar'], 'dataFileUtils.test.ts', ), ).resolves.toEqual(__dirname); }); it('return undefined if no folder contain such file', async () => { await expect( findFolderContainingFile(['/foo', '/bar', '/baz'], 'index.test.ts'), ).resolves.toBeUndefined(); }); }); describe('getFolderContainingFile', () => { it('get appropriate folder', async () => { await expect( getFolderContainingFile( ['/foo', '/baz', __dirname, '/bar'], 'dataFileUtils.test.ts', ), ).resolves.toEqual(__dirname); }); it('throw if no folder contain such file', async () => { await expect( getFolderContainingFile( ['/foo', '/bar', '/baz'], 'dataFileUtils.test.ts', ), ).rejects.toThrowErrorMatchingInlineSnapshot(` "File "dataFileUtils.test.ts" does not exist in any of these folders: - /foo - /bar - /baz" `); }); });
2,030
0
petrpan-code/facebook/docusaurus/packages/docusaurus-utils/src
petrpan-code/facebook/docusaurus/packages/docusaurus-utils/src/__tests__/emitUtils.test.ts
/** * Copyright (c) Facebook, Inc. and its affiliates. * * This source code is licensed under the MIT license found in the * LICENSE file in the root directory of this source tree. */ import {jest} from '@jest/globals'; import path from 'path'; import fs from 'fs-extra'; import {readOutputHTMLFile, generate} from '../emitUtils'; describe('readOutputHTMLFile', () => { it('reads both files with trailing slash undefined', async () => { await expect( readOutputHTMLFile( '/file', path.join(__dirname, '__fixtures__/build-snap'), undefined, ).then(String), ).resolves.toBe('file\n'); await expect( readOutputHTMLFile( '/folder', path.join(__dirname, '__fixtures__/build-snap'), undefined, ).then(String), ).resolves.toBe('folder\n'); await expect( readOutputHTMLFile( '/file/', path.join(__dirname, '__fixtures__/build-snap'), undefined, ).then(String), ).resolves.toBe('file\n'); await expect( readOutputHTMLFile( '/folder/', path.join(__dirname, '__fixtures__/build-snap'), undefined, ).then(String), ).resolves.toBe('folder\n'); }); it('reads only folder with trailing slash true', async () => { await expect( readOutputHTMLFile( '/folder', path.join(__dirname, '__fixtures__/build-snap'), true, ).then(String), ).resolves.toBe('folder\n'); await expect( readOutputHTMLFile( '/folder/', path.join(__dirname, '__fixtures__/build-snap'), true, ).then(String), ).resolves.toBe('folder\n'); }); it('reads only file trailing slash false', async () => { await expect( readOutputHTMLFile( '/file', path.join(__dirname, '__fixtures__/build-snap'), false, ).then(String), ).resolves.toBe('file\n'); await expect( readOutputHTMLFile( '/file/', path.join(__dirname, '__fixtures__/build-snap'), false, ).then(String), ).resolves.toBe('file\n'); }); it('reads file ending in .html', async () => { await expect( readOutputHTMLFile( '/htmlFile.html', path.join(__dirname, '__fixtures__/build-snap'), false, ).then(String), ).resolves.toBe('htmlFile.html\n'); await expect( readOutputHTMLFile( '/htmlFile.html', path.join(__dirname, '__fixtures__/build-snap'), undefined, ).then(String), ).resolves.toBe('htmlFile.html\n'); }); it('reads file ending in .html in folder containing .html', async () => { await expect( readOutputHTMLFile( '/weird.html.folder/nestedHtmlFile.html', path.join(__dirname, '__fixtures__/build-snap'), undefined, ).then(String), ).resolves.toBe('nestedHtmlFile.html\n'); await expect( readOutputHTMLFile( '/weird.html.folder/nestedHtmlFile.html', path.join(__dirname, '__fixtures__/build-snap'), undefined, ).then(String), ).resolves.toBe('nestedHtmlFile.html\n'); }); // Can it ever happen? it('throws if file does not exist', async () => { await expect( readOutputHTMLFile( '/nonExistent', path.join(__dirname, '__fixtures__/build-snap'), undefined, ).then(String), ).rejects.toThrowErrorMatchingInlineSnapshot( `"Expected output HTML file to be found at <PROJECT_ROOT>/packages/docusaurus-utils/src/__tests__/__fixtures__/build-snap/nonExistent/index.html for permalink /nonExistent."`, ); }); }); describe('generate', () => { const writeMock = jest.spyOn(fs, 'outputFile').mockImplementation(() => {}); const existsMock = jest.spyOn(fs, 'pathExists'); const readMock = jest.spyOn(fs, 'readFile'); it('works with no file and no cache', async () => { existsMock.mockImplementationOnce(() => false); await generate(__dirname, 'foo', 'bar'); expect(writeMock).toHaveBeenNthCalledWith( 1, path.join(__dirname, 'foo'), 'bar', ); }); it('works with existing cache', async () => { await generate(__dirname, 'foo', 'bar'); expect(writeMock).toHaveBeenCalledTimes(1); }); it('works with existing file but no cache', async () => { existsMock.mockImplementationOnce(() => true); // @ts-expect-error: seems the typedef doesn't understand overload readMock.mockImplementationOnce(() => Promise.resolve('bar')); await generate(__dirname, 'baz', 'bar'); expect(writeMock).toHaveBeenCalledTimes(1); }); it('works when force skipping cache', async () => { await generate(__dirname, 'foo', 'bar', true); expect(writeMock).toHaveBeenNthCalledWith( 2, path.join(__dirname, 'foo'), 'bar', ); }); });
2,031
0
petrpan-code/facebook/docusaurus/packages/docusaurus-utils/src
petrpan-code/facebook/docusaurus/packages/docusaurus-utils/src/__tests__/gitUtils.test.ts
/** * Copyright (c) Facebook, Inc. and its affiliates. * * This source code is licensed under the MIT license found in the * LICENSE file in the root directory of this source tree. */ import fs from 'fs-extra'; import path from 'path'; import {createTempRepo} from '@testing-utils/git'; import {FileNotTrackedError, getFileCommitDate} from '../gitUtils'; /* eslint-disable no-restricted-properties */ function initializeTempRepo() { const {repoDir, git} = createTempRepo(); fs.writeFileSync(path.join(repoDir, 'test.txt'), 'Some content'); git.commit( 'Create test.txt', '2020-06-19', 'Caroline <[email protected]>', ); fs.writeFileSync(path.join(repoDir, 'test.txt'), 'Updated content'); git.commit( 'Update test.txt', '2020-06-20', 'Josh-Cena <[email protected]>', ); fs.writeFileSync(path.join(repoDir, 'test.txt'), 'Updated content (2)'); fs.writeFileSync(path.join(repoDir, 'moved.txt'), 'This file is moved'); git.commit( 'Update test.txt again, create moved.txt', '2020-09-13', 'Caroline <[email protected]>', ); fs.moveSync(path.join(repoDir, 'moved.txt'), path.join(repoDir, 'dest.txt')); git.commit( 'Rename moved.txt to dest.txt', '2020-11-13', 'Josh-Cena <[email protected]>', ); fs.writeFileSync(path.join(repoDir, 'untracked.txt'), "I'm untracked"); return repoDir; } describe('getFileCommitDate', () => { const repoDir = initializeTempRepo(); it('returns earliest commit date', async () => { expect(getFileCommitDate(path.join(repoDir, 'test.txt'), {})).toEqual({ date: new Date('2020-06-19'), timestamp: new Date('2020-06-19').getTime() / 1000, }); expect(getFileCommitDate(path.join(repoDir, 'dest.txt'), {})).toEqual({ date: new Date('2020-09-13'), timestamp: new Date('2020-09-13').getTime() / 1000, }); }); it('returns latest commit date', async () => { expect( getFileCommitDate(path.join(repoDir, 'test.txt'), {age: 'newest'}), ).toEqual({ date: new Date('2020-09-13'), timestamp: new Date('2020-09-13').getTime() / 1000, }); expect( getFileCommitDate(path.join(repoDir, 'dest.txt'), {age: 'newest'}), ).toEqual({ date: new Date('2020-11-13'), timestamp: new Date('2020-11-13').getTime() / 1000, }); }); it('returns latest commit date with author', async () => { expect( getFileCommitDate(path.join(repoDir, 'test.txt'), { age: 'oldest', includeAuthor: true, }), ).toEqual({ date: new Date('2020-06-19'), timestamp: new Date('2020-06-19').getTime() / 1000, author: 'Caroline', }); expect( getFileCommitDate(path.join(repoDir, 'dest.txt'), { age: 'oldest', includeAuthor: true, }), ).toEqual({ date: new Date('2020-09-13'), timestamp: new Date('2020-09-13').getTime() / 1000, author: 'Caroline', }); }); it('returns earliest commit date with author', async () => { expect( getFileCommitDate(path.join(repoDir, 'test.txt'), { age: 'newest', includeAuthor: true, }), ).toEqual({ date: new Date('2020-09-13'), timestamp: new Date('2020-09-13').getTime() / 1000, author: 'Caroline', }); expect( getFileCommitDate(path.join(repoDir, 'dest.txt'), { age: 'newest', includeAuthor: true, }), ).toEqual({ date: new Date('2020-11-13'), timestamp: new Date('2020-11-13').getTime() / 1000, author: 'Josh-Cena', }); }); it('throws custom error when file is not tracked', async () => { expect(() => getFileCommitDate(path.join(repoDir, 'untracked.txt'), { age: 'newest', includeAuthor: true, }), ).toThrow(FileNotTrackedError); }); it('throws when file not found', async () => { expect(() => getFileCommitDate(path.join(repoDir, 'nonexistent.txt'), { age: 'newest', includeAuthor: true, }), ).toThrow( /Failed to retrieve git history for ".*nonexistent.txt" because the file does not exist./, ); }); });
2,032
0
petrpan-code/facebook/docusaurus/packages/docusaurus-utils/src
petrpan-code/facebook/docusaurus/packages/docusaurus-utils/src/__tests__/globUtils.test.ts
/** * Copyright (c) Facebook, Inc. and its affiliates. * * This source code is licensed under the MIT license found in the * LICENSE file in the root directory of this source tree. */ import { GlobExcludeDefault, createMatcher, createAbsoluteFilePathMatcher, } from '../globUtils'; describe('createMatcher', () => { it('match default exclude MD/MDX partials correctly', () => { const matcher = createMatcher(GlobExcludeDefault); expect(matcher('doc.md')).toBe(false); expect(matcher('category/doc.md')).toBe(false); expect(matcher('category/subcategory/doc.md')).toBe(false); // expect(matcher('doc.mdx')).toBe(false); expect(matcher('category/doc.mdx')).toBe(false); expect(matcher('category/subcategory/doc.mdx')).toBe(false); // expect(matcher('_doc.md')).toBe(true); expect(matcher('category/_doc.md')).toBe(true); expect(matcher('category/subcategory/_doc.md')).toBe(true); expect(matcher('_category/doc.md')).toBe(true); expect(matcher('_category/subcategory/doc.md')).toBe(true); expect(matcher('category/_subcategory/doc.md')).toBe(true); }); it('match default exclude tests correctly', () => { const matcher = createMatcher(GlobExcludeDefault); expect(matcher('xyz.js')).toBe(false); expect(matcher('xyz.ts')).toBe(false); expect(matcher('xyz.jsx')).toBe(false); expect(matcher('xyz.tsx')).toBe(false); expect(matcher('folder/xyz.js')).toBe(false); expect(matcher('folder/xyz.ts')).toBe(false); expect(matcher('folder/xyz.jsx')).toBe(false); expect(matcher('folder/xyz.tsx')).toBe(false); // expect(matcher('xyz.test.js')).toBe(true); expect(matcher('xyz.test.ts')).toBe(true); expect(matcher('xyz.test.jsx')).toBe(true); expect(matcher('xyz.test.tsx')).toBe(true); expect(matcher('folder/xyz.test.js')).toBe(true); expect(matcher('folder/xyz.test.ts')).toBe(true); expect(matcher('folder/xyz.test.jsx')).toBe(true); expect(matcher('folder/xyz.test.tsx')).toBe(true); expect(matcher('folder/subfolder/xyz.test.js')).toBe(true); expect(matcher('folder/subfolder/xyz.test.ts')).toBe(true); expect(matcher('folder/subfolder/xyz.test.jsx')).toBe(true); expect(matcher('folder/subfolder/xyz.test.tsx')).toBe(true); // expect(matcher('__tests__/subfolder/xyz.js')).toBe(true); expect(matcher('__tests__/subfolder/xyz.ts')).toBe(true); expect(matcher('__tests__/subfolder/xyz.jsx')).toBe(true); expect(matcher('__tests__/subfolder/xyz.tsx')).toBe(true); expect(matcher('folder/__tests__/xyz.js')).toBe(true); expect(matcher('folder/__tests__/xyz.ts')).toBe(true); expect(matcher('folder/__tests__/xyz.jsx')).toBe(true); expect(matcher('folder/__tests__/xyz.tsx')).toBe(true); }); it('matches nothing given nothing', () => { const matcher = createMatcher([]); expect(matcher('foo')).toBe(false); expect(matcher('')).toBe(false); expect(matcher('we/are/the/champions')).toBe(false); }); }); describe('createAbsoluteFilePathMatcher', () => { const rootFolders = ['/_root/docs', '/root/_docs/', '/__test__/website/src']; const matcher = createAbsoluteFilePathMatcher( GlobExcludeDefault, rootFolders, ); it('match default exclude MD/MDX partials correctly', () => { expect(matcher('/_root/docs/myDoc.md')).toBe(false); expect(matcher('/_root/docs/myDoc.mdx')).toBe(false); expect(matcher('/root/_docs/myDoc.md')).toBe(false); expect(matcher('/root/_docs/myDoc.mdx')).toBe(false); expect(matcher('/_root/docs/category/myDoc.md')).toBe(false); expect(matcher('/_root/docs/category/myDoc.mdx')).toBe(false); expect(matcher('/root/_docs/category/myDoc.md')).toBe(false); expect(matcher('/root/_docs/category/myDoc.mdx')).toBe(false); // expect(matcher('/_root/docs/_myDoc.md')).toBe(true); expect(matcher('/_root/docs/_myDoc.mdx')).toBe(true); expect(matcher('/root/_docs/_myDoc.md')).toBe(true); expect(matcher('/root/_docs/_myDoc.mdx')).toBe(true); expect(matcher('/_root/docs/_category/myDoc.md')).toBe(true); expect(matcher('/_root/docs/_category/myDoc.mdx')).toBe(true); expect(matcher('/root/_docs/_category/myDoc.md')).toBe(true); expect(matcher('/root/_docs/_category/myDoc.mdx')).toBe(true); }); it('match default exclude tests correctly', () => { expect(matcher('/__test__/website/src/xyz.js')).toBe(false); expect(matcher('/__test__/website/src/__test__/xyz.js')).toBe(true); expect(matcher('/__test__/website/src/xyz.test.js')).toBe(true); }); it('throw if file is not contained in any root doc', () => { expect(() => matcher('/bad/path/myDoc.md'), ).toThrowErrorMatchingInlineSnapshot( `"createAbsoluteFilePathMatcher unexpected error, absoluteFilePath=/bad/path/myDoc.md was not contained in any of the root folders: /_root/docs, /root/_docs/, /__test__/website/src"`, ); }); it('matches paths with overlapping paths', () => { const overlapMatcher = createAbsoluteFilePathMatcher(GlobExcludeDefault, [ '/root/docs', '/root/versioned_docs/version-2.0.0', '/root/versioned_docs/version-2.0.0-rc.1', ]); expect( overlapMatcher('/root/versioned_docs/version-2.0.0-rc.1/_partial.mdx'), ).toBe(true); expect( overlapMatcher('/root/versioned_docs/version-2.0.0/_partial.mdx'), ).toBe(true); expect( overlapMatcher('/root/versioned_docs/version-2.0.0/no-partial.mdx'), ).toBe(false); }); });
2,033
0
petrpan-code/facebook/docusaurus/packages/docusaurus-utils/src
petrpan-code/facebook/docusaurus/packages/docusaurus-utils/src/__tests__/hashUtils.test.ts
/** * Copyright (c) Facebook, Inc. and its affiliates. * * This source code is licensed under the MIT license found in the * LICENSE file in the root directory of this source tree. */ import {simpleHash, docuHash} from '../hashUtils'; describe('hashUtils', () => { it('simpleHash', () => { const asserts: {[key: string]: string} = { '': 'd41', '/foo-bar': '096', '/foo/bar': '1df', '/endi/lie': '9fa', '/endi-lie': 'fd3', '/yangshun/tay': '48d', '/yangshun-tay': 'f3b', '/foo/bar/foo/bar/foo/bar/foo/bar/foo/bar/foo/bar/foo/bar/foo/bar/foo/bar/foo/bar/foo/bar/foo/bar/foo/bar/foo/bar/foo/bar/foo/bar/foo/bar/foo/bar/foo/bar/foo/bar/foo/bar/foo/bar/foo/bar/foo/bar/foo/bar/foo/bar/foo/bar/foo/bar/foo/bar/foo/bar/foo/bar/foo/bar': 'd46', '/foo/bar/foo/bar/foo/bar/foo/bar/foo/bar/foo/bar/foo/bar/foo/bar/foo/bar/foo/bar/foo/bar/foo/bar/foo/bar/foo/bar/foo/bar/foo/bar/foo/bar/foo/bar/foo/bar/foo/bar/foo/bar/foo/bar/foo/bar/foo/bar/foo/bar/foo/bar/foo/bar/foo/bar/foo/bar/test1-test2': '787', }; Object.keys(asserts).forEach((str) => { expect(simpleHash(str, 3)).toBe(asserts[str]); }); }); }); describe('docuHash', () => { it('docuHash works', () => { const asserts: {[key: string]: string} = { '': '-d41', '/': 'index', '/foo-bar': 'foo-bar-096', '/foo/bar': 'foo-bar-1df', '/endi/lie': 'endi-lie-9fa', '/endi-lie': 'endi-lie-fd3', '/yangshun/tay': 'yangshun-tay-48d', '/yangshun-tay': 'yangshun-tay-f3b', '/foo/bar/foo/bar/foo/bar/foo/bar/foo/bar/foo/bar/foo/bar/foo/bar/foo/bar/foo/bar/foo/bar/foo/bar/foo/bar/foo/bar/foo/bar/foo/bar/foo/bar/foo/bar/foo/bar/foo/bar/foo/bar/foo/bar/foo/bar/foo/bar/foo/bar/foo/bar/foo/bar/foo/bar/foo/bar/foo/bar/foo/bar/foo/bar': 'foo-bar-foo-bar-foo-bar-foo-bar-foo-bar-foo-bar-foo-bar-foo-bar-foo-bar-foo-bar-foo-bar-foo-bar-foo-bar-foo-bar-foo-bar-foo-bar-foo-bar-foo-bar-foo-bar-foo-bar-foo-bar-foo-bar-foo-bar-foo-bar-foo-bar-foo-bar-foo-bar-foo-bar-foo-bar-foo-bar-foo--d46', '/foo/bar/foo/bar/foo/bar/foo/bar/foo/bar/foo/bar/foo/bar/foo/bar/foo/bar/foo/bar/foo/bar/foo/bar/foo/bar/foo/bar/foo/bar/foo/bar/foo/bar/foo/bar/foo/bar/foo/bar/foo/bar/foo/bar/foo/bar/foo/bar/foo/bar/foo/bar/foo/bar/foo/bar/foo/bar/test1-test2': 'foo-bar-foo-bar-foo-bar-foo-bar-foo-bar-foo-bar-foo-bar-foo-bar-foo-bar-foo-bar-foo-bar-foo-bar-foo-bar-foo-bar-foo-bar-foo-bar-foo-bar-foo-bar-foo-bar-foo-bar-foo-bar-foo-bar-foo-bar-foo-bar-foo-bar-foo-bar-foo-bar-foo-bar-foo-bar-test-1-test--787', }; Object.keys(asserts).forEach((file) => { expect(docuHash(file)).toBe(asserts[file]); }); }); });
2,034
0
petrpan-code/facebook/docusaurus/packages/docusaurus-utils/src
petrpan-code/facebook/docusaurus/packages/docusaurus-utils/src/__tests__/i18nUtils.test.ts
/** * Copyright (c) Facebook, Inc. and its affiliates. * * This source code is licensed under the MIT license found in the * LICENSE file in the root directory of this source tree. */ import path from 'path'; import { mergeTranslations, updateTranslationFileMessages, getPluginI18nPath, localizePath, } from '../i18nUtils'; describe('mergeTranslations', () => { it('works', () => { expect( mergeTranslations([ { T1: {message: 'T1 message', description: 'T1 desc'}, T2: {message: 'T2 message', description: 'T2 desc'}, T3: {message: 'T3 message', description: 'T3 desc'}, }, { T4: {message: 'T4 message', description: 'T4 desc'}, }, {T2: {message: 'T2 message 2', description: 'T2 desc 2'}}, ]), ).toEqual({ T1: {message: 'T1 message', description: 'T1 desc'}, T2: {message: 'T2 message 2', description: 'T2 desc 2'}, T3: {message: 'T3 message', description: 'T3 desc'}, T4: {message: 'T4 message', description: 'T4 desc'}, }); }); }); describe('updateTranslationFileMessages', () => { it('works', () => { expect( updateTranslationFileMessages( { path: 'abc', content: { t1: {message: 't1 message', description: 't1 desc'}, t2: {message: 't2 message', description: 't2 desc'}, t3: {message: 't3 message', description: 't3 desc'}, }, }, (message) => `prefix ${message} suffix`, ), ).toEqual({ path: 'abc', content: { t1: {message: 'prefix t1 message suffix', description: 't1 desc'}, t2: {message: 'prefix t2 message suffix', description: 't2 desc'}, t3: {message: 'prefix t3 message suffix', description: 't3 desc'}, }, }); }); }); describe('getPluginI18nPath', () => { it('gets correct path', () => { expect( getPluginI18nPath({ localizationDir: '<SITE_DIR>/i18n/zh-Hans', pluginName: 'plugin-content-docs', pluginId: 'community', subPaths: ['foo'], }), ).toMatchInlineSnapshot( `"<SITE_DIR>/i18n/zh-Hans/plugin-content-docs-community/foo"`, ); }); it('gets correct path for default plugin', () => { expect( getPluginI18nPath({ localizationDir: '<SITE_DIR>/i18n/zh-Hans', pluginName: 'plugin-content-docs', subPaths: ['foo'], }), ).toMatchInlineSnapshot( `"<SITE_DIR>/i18n/zh-Hans/plugin-content-docs/foo"`, ); }); it('gets correct path when no sub-paths', () => { expect( getPluginI18nPath({ localizationDir: '<SITE_DIR>/i18n/zh-Hans', pluginName: 'plugin-content-docs', }), ).toMatchInlineSnapshot(`"<SITE_DIR>/i18n/zh-Hans/plugin-content-docs"`); }); }); describe('localizePath', () => { it('localizes url path with current locale', () => { expect( localizePath({ pathType: 'url', path: '/baseUrl', i18n: { defaultLocale: 'en', path: 'i18n', locales: ['en', 'fr'], currentLocale: 'fr', localeConfigs: {}, }, options: {localizePath: true}, }), ).toBe('/baseUrl/fr/'); }); it('localizes fs path with current locale', () => { expect( localizePath({ pathType: 'fs', path: '/baseFsPath', i18n: { defaultLocale: 'en', path: 'i18n', locales: ['en', 'fr'], currentLocale: 'fr', localeConfigs: {fr: {path: 'fr'}, en: {path: 'en'}}, }, options: {localizePath: true}, }), ).toBe(`${path.sep}baseFsPath${path.sep}fr`); }); it('localizes path for default locale, if requested', () => { expect( localizePath({ pathType: 'url', path: '/baseUrl/', i18n: { defaultLocale: 'en', path: 'i18n', locales: ['en', 'fr'], currentLocale: 'en', localeConfigs: {fr: {path: 'fr'}, en: {path: 'en'}}, }, options: {localizePath: true}, }), ).toBe('/baseUrl/en/'); }); it('does not localize path for default locale by default', () => { expect( localizePath({ pathType: 'url', path: '/baseUrl/', i18n: { defaultLocale: 'en', path: 'i18n', locales: ['en', 'fr'], currentLocale: 'en', localeConfigs: {fr: {path: 'fr'}, en: {path: 'en'}}, }, }), ).toBe('/baseUrl/'); }); it('localizes path for non-default locale by default', () => { expect( localizePath({ pathType: 'url', path: '/baseUrl/', i18n: { defaultLocale: 'en', path: 'i18n', locales: ['en', 'fr'], currentLocale: 'en', localeConfigs: {fr: {path: 'fr'}, en: {path: 'en'}}, }, }), ).toBe('/baseUrl/'); }); });
2,035
0
petrpan-code/facebook/docusaurus/packages/docusaurus-utils/src
petrpan-code/facebook/docusaurus/packages/docusaurus-utils/src/__tests__/jsUtils.test.ts
/** * Copyright (c) Facebook, Inc. and its affiliates. * * This source code is licensed under the MIT license found in the * LICENSE file in the root directory of this source tree. */ import {jest} from '@jest/globals'; import _ from 'lodash'; import { removeSuffix, removePrefix, mapAsyncSequential, findAsyncSequential, } from '../jsUtils'; describe('removeSuffix', () => { it("is no-op when suffix doesn't exist", () => { expect(removeSuffix('abcdef', 'ijk')).toBe('abcdef'); expect(removeSuffix('abcdef', 'abc')).toBe('abcdef'); expect(removeSuffix('abcdef', '')).toBe('abcdef'); }); it('removes suffix', () => { expect(removeSuffix('abcdef', 'ef')).toBe('abcd'); }); }); describe('removePrefix', () => { it("is no-op when prefix doesn't exist", () => { expect(removePrefix('abcdef', 'ijk')).toBe('abcdef'); expect(removePrefix('abcdef', 'def')).toBe('abcdef'); expect(removePrefix('abcdef', '')).toBe('abcdef'); }); it('removes prefix', () => { expect(removePrefix('prefix', 'pre')).toBe('fix'); }); }); describe('mapAsyncSequential', () => { function sleep(timeout: number): Promise<void> { return new Promise((resolve) => { setTimeout(resolve, timeout); }); } it('maps sequentially', async () => { const itemToTimeout: {[key: string]: number} = { '1': 200, '2': 600, '3': 400, }; const items = Object.keys(itemToTimeout); const itemMapStartsAt: {[key: string]: number} = {}; const itemMapEndsAt: {[key: string]: number} = {}; const timeBefore = Date.now(); await expect( mapAsyncSequential(items, async (item) => { const itemTimeout = itemToTimeout[item]!; itemMapStartsAt[item] = Date.now(); await sleep(itemTimeout); itemMapEndsAt[item] = Date.now(); return `${item} mapped`; }), ).resolves.toEqual(['1 mapped', '2 mapped', '3 mapped']); const timeAfter = Date.now(); const timeTotal = timeAfter - timeBefore; const totalTimeouts = _.sum(Object.values(itemToTimeout)); expect(timeTotal).toBeGreaterThanOrEqual(totalTimeouts - 100); expect(itemMapStartsAt[1]).toBeGreaterThanOrEqual(0); expect(itemMapStartsAt[2]).toBeGreaterThanOrEqual(itemMapEndsAt[1]! - 100); expect(itemMapStartsAt['3']).toBeGreaterThanOrEqual( itemMapEndsAt[2]! - 100, ); }); }); describe('findAsyncSequential', () => { function sleep(timeout: number): Promise<void> { return new Promise((resolve) => { setTimeout(resolve, timeout); }); } it('finds sequentially', async () => { const items = ['1', '2', '3']; const findFn = jest.fn(async (item: string) => { await sleep(400); return item === '2'; }); const timeBefore = Date.now(); await expect(findAsyncSequential(items, findFn)).resolves.toBe('2'); const timeAfter = Date.now(); expect(findFn).toHaveBeenCalledTimes(2); expect(findFn).toHaveBeenNthCalledWith(1, '1'); expect(findFn).toHaveBeenNthCalledWith(2, '2'); const timeTotal = timeAfter - timeBefore; expect(timeTotal).toBeGreaterThanOrEqual(600); expect(timeTotal).toBeLessThan(1000); }); });
2,036
0
petrpan-code/facebook/docusaurus/packages/docusaurus-utils/src
petrpan-code/facebook/docusaurus/packages/docusaurus-utils/src/__tests__/markdownLinks.test.ts
/** * Copyright (c) Facebook, Inc. and its affiliates. * * This source code is licensed under the MIT license found in the * LICENSE file in the root directory of this source tree. */ import {replaceMarkdownLinks} from '../markdownLinks'; describe('replaceMarkdownLinks', () => { it('does basic replace', () => { expect( replaceMarkdownLinks({ siteDir: '.', filePath: 'docs/intro.md', contentPaths: { contentPath: 'docs', contentPathLocalized: 'i18n/docs-localized', }, sourceToPermalink: { '@site/docs/intro.md': '/docs/intro', '@site/docs/foo.md': '/doc/foo', '@site/docs/bar/baz.md': '/doc/baz', '@site/docs/http.foo.md': '/doc/http', }, fileString: ` [foo](./foo.md) [baz](./bar/baz.md) [foo](foo.md) [http](http://github.com/facebook/docusaurus/README.md) [https](https://github.com/facebook/docusaurus/README.md) [asset](./foo.js) [asset as well](@site/docs/_partial.md) [looks like http...](http.foo.md) [nonexistent](hmmm.md) `, }), ).toMatchSnapshot(); }); it('replaces two links on the same line', () => { // cSpell:ignore Goooooooooo // This is a very arcane bug: if we continue matching using the previous // matching index (as is the behavior of RegExp#exec), it will go right over // the next Markdown link and fail to match the "Go" link. This only happens // when: (1) the replaced link is much shorter than the Markdown path, (2) // the next link is very close to the current one (e.g. here if it's not // "Go" but "Goooooooooo", or if every link has the /docs/ prefix, the bug // will not trigger because it won't overshoot) expect( replaceMarkdownLinks({ siteDir: '.', filePath: 'docs/intro.md', contentPaths: { contentPath: 'docs', contentPathLocalized: 'i18n/docs-localized', }, sourceToPermalink: { '@site/docs/intro.md': '/', '@site/docs/programming-languages/typescript/typescript.md': '/programming-languages/typescript/', '@site/docs/programming-languages/go/go.md': '/programming-languages/go/', }, fileString: `[TypeScript](programming-languages/typescript/typescript.md) and [Go](programming-languages/go/go.md)`, }), ).toMatchSnapshot(); }); it('replaces reference style Markdown links', () => { expect( replaceMarkdownLinks({ siteDir: '.', filePath: 'docs/intro/intro.md', contentPaths: { contentPath: 'docs', contentPathLocalized: 'i18n/docs-localized', }, sourceToPermalink: { '@site/docs/intro/intro.md': '/docs/intro', '@site/docs/api/classes/divine_uri.URI.md': '/docs/api/classes/uri', }, fileString: ` The following operations are defined for [URI]s: * [info]: Returns metadata about the resource, * [list]: Returns metadata about the resource's children (like getting the content of a local directory). [URI]: ../api/classes/divine_uri.URI.md [info]: ../api/classes/divine_uri.URI.md#info [list]: ../api/classes/divine_uri.URI.md#list `, }), ).toMatchSnapshot(); }); it('resolves absolute and relative links differently', () => { expect( replaceMarkdownLinks({ siteDir: '.', filePath: 'docs/intro/intro.md', contentPaths: { contentPath: 'docs', contentPathLocalized: 'i18n/docs-localized', }, sourceToPermalink: { '@site/docs/intro/intro.md': '/docs/intro', '@site/docs/intro/another.md': '/docs/another', '@site/docs/api/classes/divine_uri.URI.md': '/docs/api/classes/uri', }, fileString: ` [Relative link](./another.md) [Relative link 2](../api/classes/divine_uri.URI.md) [Relative link that should be absolute](./api/classes/divine_uri.URI.md) [Absolute link](/api/classes/divine_uri.URI.md) [Absolute link from site dir](/docs/api/classes/divine_uri.URI.md) [Absolute link that should be relative](/another.md) [Relative link that acts as absolute](api/classes/divine_uri.URI.md) [Relative link that acts as relative](another.md) `, }), ).toMatchSnapshot(); }); // TODO bad it('ignores links in HTML comments', () => { expect( replaceMarkdownLinks({ siteDir: '.', filePath: 'docs/intro.md', contentPaths: { contentPath: 'docs', contentPathLocalized: 'i18n/docs-localized', }, sourceToPermalink: { '@site/docs/intro.md': '/docs/intro', }, fileString: ` <!-- [foo](./foo.md) --> <!-- [foo](./foo.md) --> `, }), ).toMatchSnapshot(); }); it('ignores links in fenced blocks', () => { expect( replaceMarkdownLinks({ siteDir: '.', filePath: 'docs/intro.md', contentPaths: { contentPath: 'docs', contentPathLocalized: 'i18n/docs-localized', }, sourceToPermalink: { '@site/docs/intro.md': '/docs/intro', }, fileString: ` \`\`\` [foo](foo.md) \`\`\` \`\`\`\`js [foo](foo.md) \`\`\` [foo](foo.md) \`\`\` [foo](foo.md) \`\`\`\` \`\`\`\`js [foo](foo.md) \`\`\` [foo](foo.md) \`\`\`\` ~~~js [foo](foo.md) ~~~ ~~~js [foo](foo.md) \`\`\` [foo](foo.md) \`\`\` [foo](foo.md) ~~~ `, }), ).toMatchSnapshot(); }); // FIXME it('ignores links in inline code', () => { expect( replaceMarkdownLinks({ siteDir: '.', filePath: 'docs/intro.md', contentPaths: { contentPath: 'docs', contentPathLocalized: 'i18n/docs-localized', }, sourceToPermalink: { '@site/docs/intro.md': '/docs/intro', }, fileString: ` \`[foo](foo.md)\` `, }), ).toMatchSnapshot(); }); it('replaces links with same title as URL', () => { expect( replaceMarkdownLinks({ siteDir: '.', filePath: 'docs/intro.md', contentPaths: { contentPath: 'docs', contentPathLocalized: 'i18n/docs-localized', }, sourceToPermalink: { '@site/docs/intro.md': '/docs/intro', '@site/docs/foo.md': '/docs/foo', }, fileString: ` [foo.md](foo.md) [./foo.md](./foo.md) [foo.md](./foo.md) [./foo.md](foo.md) `, }), ).toMatchSnapshot(); }); it('replaces multiple links on same line', () => { expect( replaceMarkdownLinks({ siteDir: '.', filePath: 'docs/intro.md', contentPaths: { contentPath: 'docs', contentPathLocalized: 'i18n/docs-localized', }, sourceToPermalink: { '@site/docs/intro.md': '/docs/intro', '@site/docs/a.md': '/docs/a', '@site/docs/b.md': '/docs/b', '@site/docs/c.md': '/docs/c', }, fileString: ` [a](a.md), [a](a.md), [b](b.md), [c](c.md) `, }), ).toMatchSnapshot(); }); it('replaces Markdown links with spaces', () => { expect( replaceMarkdownLinks({ siteDir: '.', filePath: 'docs/intro.md', contentPaths: { contentPath: 'docs', contentPathLocalized: 'i18n/docs-localized', }, sourceToPermalink: { '@site/docs/doc a.md': '/docs/doc%20a', '@site/docs/my docs/doc b.md': '/docs/my%20docs/doc%20b', }, fileString: ` [doc a](./doc%20a.md) [doc a](<./doc a.md>) [doc b](./my%20docs/doc%20b.md) [doc b](<./my docs/doc b.md>) [doc]: <./my docs/doc b.md> `, }), ).toMatchSnapshot(); }); it('does not replace non-Markdown links', () => { const input = ` [asset](./file.md_asset/1.png) [URL](<https://example.com/file_(1).md>) [not a link]((foo) [not a link](foo bar) [not a link]: foo bar [not a link]: (foo [not a link]: bar) `; expect( replaceMarkdownLinks({ siteDir: '.', filePath: 'docs/file.md', contentPaths: { contentPath: 'docs', contentPathLocalized: 'i18n/docs-localized', }, sourceToPermalink: { '@site/docs/file.md': '/docs/file', }, fileString: input, }), ).toEqual({ newContent: input, brokenMarkdownLinks: [], }); }); it('handles stray spaces', () => { expect( replaceMarkdownLinks({ siteDir: '.', filePath: 'docs/file.md', contentPaths: { contentPath: 'docs', contentPathLocalized: 'i18n/docs-localized', }, sourceToPermalink: { '@site/docs/file.md': '/docs/file', }, fileString: ` [URL]( ./file.md ) [ref]: ./file.md `, }), ).toMatchSnapshot(); }); it('handles link titles', () => { expect( replaceMarkdownLinks({ siteDir: '.', filePath: 'docs/file.md', contentPaths: { contentPath: 'docs', contentPathLocalized: 'i18n/docs-localized', }, sourceToPermalink: { '@site/docs/file.md': '/docs/file', }, fileString: ` [URL](./file.md "title") [URL](./file.md 'title') [URL](./file.md (title)) `, }), ).toMatchSnapshot(); }); it('preserves query/hash', () => { expect( replaceMarkdownLinks({ siteDir: '.', filePath: 'docs/file.md', contentPaths: { contentPath: 'docs', contentPathLocalized: 'i18n/docs-localized', }, sourceToPermalink: { '@site/docs/file.md': '/docs/file', }, fileString: ` [URL](./file.md?foo=bar#baz) [URL](./file.md#a) [URL](./file.md?c) `, }), ).toMatchSnapshot(); }); it('handles unpaired fences', () => { expect( replaceMarkdownLinks({ siteDir: '.', filePath: 'docs/file.md', contentPaths: { contentPath: 'docs', contentPathLocalized: 'i18n/docs-localized', }, sourceToPermalink: { '@site/docs/file.md': '/docs/file', }, fileString: ` \`\`\`foo hello \`\`\`foo hello \`\`\` A [link](./file.md) `, }), ).toMatchSnapshot(); }); });
2,037
0
petrpan-code/facebook/docusaurus/packages/docusaurus-utils/src
petrpan-code/facebook/docusaurus/packages/docusaurus-utils/src/__tests__/markdownUtils.test.ts
/** * Copyright (c) Facebook, Inc. and its affiliates. * * This source code is licensed under the MIT license found in the * LICENSE file in the root directory of this source tree. */ import dedent from 'dedent'; import { createExcerpt, parseMarkdownContentTitle, parseMarkdownString, parseMarkdownHeadingId, writeMarkdownHeadingId, escapeMarkdownHeadingIds, unwrapMdxCodeBlocks, admonitionTitleToDirectiveLabel, } from '../markdownUtils'; describe('createExcerpt', () => { it('creates excerpt for text-only content', () => { expect( createExcerpt(dedent` Lorem ipsum dolor sit amet, consectetur adipiscing elit. Vestibulum ex urna, molestie et sagittis ut, varius ac justo. Nunc porttitor libero nec vulputate venenatis. Nam nec rhoncus mauris. Morbi tempus est et nibh maximus, tempus venenatis arcu lobortis. `), ).toBe( 'Lorem ipsum dolor sit amet, consectetur adipiscing elit. Vestibulum ex urna, molestie et sagittis ut, varius ac justo.', ); }); it('creates excerpt for regular content with regular title', () => { expect( createExcerpt(dedent` # Markdown Regular Title Lorem ipsum dolor sit amet, consectetur adipiscing elit. Vestibulum ex urna, molestie et sagittis ut, varius ac justo. Nunc porttitor libero nec vulputate venenatis. Nam nec rhoncus mauris. Morbi tempus est et nibh maximus, tempus venenatis arcu lobortis. `), ).toBe( // H1 title is skipped on purpose, because we don't want the page to have // SEO metadata title === description 'Lorem ipsum dolor sit amet, consectetur adipiscing elit. Vestibulum ex urna, molestie et sagittis ut, varius ac justo.', ); }); it('creates excerpt for regular content with alternate title', () => { expect( createExcerpt(dedent` Markdown Alternate Title ================ Lorem ipsum dolor sit amet, consectetur adipiscing elit. Vestibulum ex urna, molestie et sagittis ut, varius ac justo. Nunc porttitor libero nec vulputate venenatis. Nam nec rhoncus mauris. Morbi tempus est et nibh maximus, tempus venenatis arcu lobortis. `), ).toBe( // H1 title is skipped on purpose, because we don't want the page to have // SEO metadata title === description 'Lorem ipsum dolor sit amet, consectetur adipiscing elit. Vestibulum ex urna, molestie et sagittis ut, varius ac justo.', ); }); it('creates excerpt for content with h2 heading', () => { expect( createExcerpt(dedent` ## Lorem ipsum dolor sit amet Nunc porttitor libero nec vulputate venenatis. Nam nec rhoncus mauris. Morbi tempus est et nibh maximus, tempus venenatis arcu lobortis. `), ).toBe('Lorem ipsum dolor sit amet'); }); it('creates excerpt for content beginning with blockquote', () => { expect( createExcerpt(dedent` > Lorem ipsum dolor sit amet Nunc porttitor libero nec vulputate venenatis. Nam nec rhoncus mauris. Morbi tempus est et nibh maximus, tempus venenatis arcu lobortis. `), ).toBe('Lorem ipsum dolor sit amet'); }); it('creates excerpt for content beginning with image (eg. blog post)', () => { expect( createExcerpt(dedent` ![Lorem ipsum](/img/lorem-ipsum.svg) `), ).toBe('Lorem ipsum'); }); it('creates excerpt for content beginning with admonitions', () => { expect( createExcerpt(dedent` import Component from '@site/src/components/Component' :::caution Lorem ipsum dolor sit amet, consectetur adipiscing elit. ::: Nunc porttitor libero nec vulputate venenatis. Nam nec rhoncus mauris. Morbi tempus est et nibh maximus, tempus venenatis arcu lobortis. `), ).toBe('Lorem ipsum dolor sit amet, consectetur adipiscing elit.'); }); it('creates excerpt for content with imports/exports declarations and Markdown markup, as well as Emoji', () => { expect( createExcerpt(dedent` import Component from '@site/src/components/Component'; import Component from '@site/src/components/Component' import './styles.css'; export function ItemCol(props) { return <Item {...props} className={'col col--6 margin-bottom--lg'}/> } export function ItemCol(props) { return <Item {...props} className={'col col--6 margin-bottom--lg'}/> }; Lorem **ipsum** dolor sit \`amet\`[^1], consectetur _adipiscing_ elit. [**Vestibulum**](https://wiktionary.org/wiki/vestibulum) ex urna[^note], ~~molestie~~ et sagittis ut, varius ac justo :wink:. Nunc porttitor libero nec vulputate venenatis. Nam nec rhoncus mauris. Morbi tempus est et nibh maximus, tempus venenatis arcu lobortis. `), ).toBe( 'Lorem ipsum dolor sit amet, consectetur adipiscing elit. Vestibulum ex urna, molestie et sagittis ut, varius ac justo.', ); }); it('creates excerpt for content with imports/exports declarations, with CRLF line endings', () => { expect( createExcerpt( dedent` import Component from '@site/src/components/Component'; export function ItemCol(props) { return <Item {...props} className={'col col--6 margin-bottom--lg'}/> } Lorem **ipsum** dolor sit \`amet\`[^1], consectetur _adipiscing_ elit. [**Vestibulum**](https://wiktionary.org/wiki/vestibulum) ex urna[^note], ~~molestie~~ et sagittis ut, varius ac justo :wink:. Nunc porttitor libero nec vulputate venenatis. Nam nec rhoncus mauris. Morbi tempus est et nibh maximus, tempus venenatis arcu lobortis. `.replace(/\n/g, '\r\n'), ), ).toBe( 'Lorem ipsum dolor sit amet, consectetur adipiscing elit. Vestibulum ex urna, molestie et sagittis ut, varius ac justo.', ); }); it('creates excerpt for heading specified with anchor-id syntax', () => { expect( createExcerpt(dedent` ## Markdown title {#my-anchor-id} `), ).toBe('Markdown title'); }); it('creates excerpt for content with various code blocks', () => { expect( createExcerpt(dedent` \`\`\`jsx import React from 'react'; import Layout from '@theme/Layout'; \`\`\` Lorem \`ipsum\` dolor sit amet, consectetur \`adipiscing elit\`. `), ).toBe('Lorem ipsum dolor sit amet, consectetur adipiscing elit.'); }); it('creates excerpt after multi-line imports', () => { expect( createExcerpt(dedent` import React, { type ReactNode, } from 'react'; Lorem \`ipsum\` dolor sit amet, consectetur \`adipiscing elit\`. `), ).toBe('Lorem ipsum dolor sit amet, consectetur adipiscing elit.'); }); }); describe('parseMarkdownContentTitle', () => { it('parses markdown h1 title at the top', () => { const markdown = dedent` # Markdown Title Lorem Ipsum `; expect(parseMarkdownContentTitle(markdown)).toEqual({ content: markdown, contentTitle: 'Markdown Title', }); }); it('parses markdown h1 title at the top and remove it', () => { const markdown = dedent` # Markdown Title Lorem Ipsum `; expect( parseMarkdownContentTitle(markdown, {removeContentTitle: true}), ).toEqual({ content: 'Lorem Ipsum', contentTitle: 'Markdown Title', }); }); it('parses markdown h1 title inside backticks at the top and unwrap inline code block', () => { const markdown = dedent` # \`Markdown Title\` Lorem Ipsum `; expect(parseMarkdownContentTitle(markdown)).toEqual({ content: markdown, contentTitle: 'Markdown Title', }); }); it('parses markdown h1 title with interspersed backticks at the top and unwrap inline code block', () => { const markdown = dedent` # Markdown \`Title\` With \`Many\` Backticks! Lorem Ipsum `; expect(parseMarkdownContentTitle(markdown)).toEqual({ content: markdown, contentTitle: 'Markdown Title With Many Backticks!', }); }); it('parses markdown h1 title and trim content', () => { const markdown = ` # Markdown Title Lorem Ipsum `; expect(parseMarkdownContentTitle(markdown)).toEqual({ content: markdown.trim(), contentTitle: 'Markdown Title', }); }); it('parses not parse markdown h1 title and trim content', () => { const markdown = ` Lorem Ipsum `; expect(parseMarkdownContentTitle(markdown)).toEqual({ content: markdown.trim(), contentTitle: undefined, }); }); it('parses markdown h1 title with fixed anchor-id syntax', () => { const markdown = dedent` # Markdown Title {#my-anchor-id} Lorem Ipsum `; expect(parseMarkdownContentTitle(markdown)).toEqual({ content: markdown, contentTitle: 'Markdown Title', }); }); it('parses markdown h1 title with CRLF break', () => { const markdown = `# Markdown Title\r\n\r\nLorem Ipsum`; expect(parseMarkdownContentTitle(markdown)).toEqual({ content: markdown, contentTitle: 'Markdown Title', }); }); it('parses markdown h1 setext title with CRLF break', () => { const markdown = `Markdown Title\r\n=====\r\n\r\nLorem Ipsum`; expect(parseMarkdownContentTitle(markdown)).toEqual({ content: markdown, contentTitle: 'Markdown Title', }); }); it('parses markdown h1 title at the top (atx style with closing #)', () => { const markdown = dedent` # Markdown Title # Lorem Ipsum `; expect(parseMarkdownContentTitle(markdown)).toEqual({ content: markdown, contentTitle: 'Markdown Title', }); }); it('parses markdown h1 title at the top followed by h2 title', () => { const markdown = dedent` # Markdown Title ## Heading 2 Lorem Ipsum `; expect(parseMarkdownContentTitle(markdown)).toEqual({ content: markdown, contentTitle: 'Markdown Title', }); }); it('parses only first h1 title', () => { const markdown = dedent` # Markdown Title # Markdown Title 2 Lorem Ipsum `; expect(parseMarkdownContentTitle(markdown)).toEqual({ content: markdown, contentTitle: 'Markdown Title', }); }); it('does not parse title that is not at the top', () => { const markdown = dedent` Lorem Ipsum # Markdown Title 2 Lorem Ipsum `; expect(parseMarkdownContentTitle(markdown)).toEqual({ content: markdown, contentTitle: undefined, }); }); it('parses markdown h1 alternate title', () => { const markdown = dedent` Markdown Title ================ Lorem Ipsum `; expect(parseMarkdownContentTitle(markdown)).toEqual({ content: markdown, contentTitle: 'Markdown Title', }); }); it('parses markdown h1 alternate title and remove it', () => { const markdown = dedent` Markdown Title ================ Lorem Ipsum `; expect( parseMarkdownContentTitle(markdown, {removeContentTitle: true}), ).toEqual({ content: 'Lorem Ipsum', contentTitle: 'Markdown Title', }); }); it('parses markdown h1 title placed after import declarations', () => { const markdown = dedent` import Component1 from '@site/src/components/Component1'; import Component2 from '@site/src/components/Component2' import Component3 from '@site/src/components/Component3' import './styles.css'; # Markdown Title Lorem Ipsum `; // Remove the useless line breaks? Does not matter too much expect(parseMarkdownContentTitle(markdown)).toEqual({ content: markdown, contentTitle: 'Markdown Title', }); }); it('parses markdown h1 title placed after various import declarations', () => { const markdown = ` import DefaultComponent from '@site/src/components/Component1'; import DefaultComponent2 from '../relative/path/Component2'; import * as EntireComponent from './relative/path/Component3'; import { Component4 } from "double-quote-module-name"; import { Component51, Component52, \n Component53, \n\t\t Component54 } from "double-quote-module-name"; import { Component6 as AliasComponent6 } from "module-name"; import DefaultComponent8, { DefaultComponent81 ,\nDefaultComponent82 } from "module-name"; import DefaultComponent9, * as EntireComponent9 from "module-name"; import {Component71,\nComponent72 as AliasComponent72,\nComponent73\n} \nfrom "module-name"; import './styles.css'; import _ from 'underscore'; import "module-name" # Markdown Title Lorem Ipsum `; expect(parseMarkdownContentTitle(markdown)).toEqual({ content: markdown.trim(), contentTitle: 'Markdown Title', }); }); it('parses markdown h1 title placed after various import declarations and remove it', () => { const markdown = ` import DefaultComponent from '@site/src/components/Component1'; import DefaultComponent2 from '../relative/path/Component2'; import * as EntireComponent from './relative/path/Component3'; import { Component4 } from "double-quote-module-name"; import { Component51, Component52, \n Component53, \n\t\t Component54 } from "double-quote-module-name"; import { Component6 as AliasComponent6 } from "module-name"; import DefaultComponent8, { DefaultComponent81 ,\nDefaultComponent82 } from "module-name"; import DefaultComponent9, * as EntireComponent9 from "module-name"; import {Component71,\nComponent72 as AliasComponent72,\nComponent73\n} \nfrom "module-name"; import './styles.css'; import _ from 'underscore'; import "module-name" # Markdown Title Lorem Ipsum `; expect( parseMarkdownContentTitle(markdown, {removeContentTitle: true}), ).toEqual({ content: markdown.trim().replace('# Markdown Title\n', ''), contentTitle: 'Markdown Title', }); }); it('parses markdown h1 alternate title placed after import declarations', () => { const markdown = dedent` import Component from '@site/src/components/Component'; import Component from '@site/src/components/Component' import './styles.css'; Markdown Title ============== Lorem Ipsum `; expect(parseMarkdownContentTitle(markdown)).toEqual({ content: markdown, contentTitle: 'Markdown Title', }); }); it('parses markdown h1 alternate title placed after import declarations and remove it', () => { const markdown = dedent` import Component from '@site/src/components/Component'; import Component from '@site/src/components/Component' import './styles.css'; Markdown Title ============== Lorem Ipsum `; expect( parseMarkdownContentTitle(markdown, {removeContentTitle: true}), ).toEqual({ content: markdown.replace('Markdown Title\n==============\n', ''), contentTitle: 'Markdown Title', }); }); it('parses title-only', () => { const markdown = '# Document With Only A Title'; expect(parseMarkdownContentTitle(markdown)).toEqual({ content: markdown, contentTitle: 'Document With Only A Title', }); }); it('does not parse markdown h1 title in the middle of a doc', () => { const markdown = dedent` Lorem Ipsum # Markdown Title Lorem Ipsum `; expect(parseMarkdownContentTitle(markdown)).toEqual({ content: markdown, contentTitle: undefined, }); }); it('does not parse markdown h1 alternate title in the middle of the doc', () => { const markdown = dedent` Lorem Ipsum Markdown Title ================ Lorem Ipsum `; expect(parseMarkdownContentTitle(markdown)).toEqual({ content: markdown, contentTitle: undefined, }); }); it('parses markdown h1 title placed after multiple import declarations', () => { const markdown = dedent` import Component1 from '@site/src/components/Component1'; import Component2 from '@site/src/components/Component2'; import Component3 from '@site/src/components/Component3'; import Component4 from '@site/src/components/Component4'; import Component5 from '@site/src/components/Component5'; import Component6 from '@site/src/components/Component6'; import Component7 from '@site/src/components/Component7'; import Component8 from '@site/src/components/Component8'; import Component9 from '@site/src/components/Component9'; import Component10 from '@site/src/components/Component10'; import Component11 from '@site/src/components/Component11'; import Component12 from '@site/src/components/Component12'; import Component13 from '@site/src/components/Component13'; import Component14 from '@site/src/components/Component14'; import Component15 from '@site/src/components/Component15'; # Markdown Title Lorem Ipsum `; expect(parseMarkdownContentTitle(markdown)).toEqual({ content: markdown, contentTitle: 'Markdown Title', }); }); it('parses markdown h1 title placed after multiple import declarations and remove it', () => { const markdown = dedent` import Component1 from '@site/src/components/Component1'; import Component2 from '@site/src/components/Component2'; import Component3 from '@site/src/components/Component3'; import Component4 from '@site/src/components/Component4'; import Component5 from '@site/src/components/Component5'; import Component6 from '@site/src/components/Component6'; import Component7 from '@site/src/components/Component7'; import Component8 from '@site/src/components/Component8'; import Component9 from '@site/src/components/Component9'; import Component10 from '@site/src/components/Component10'; import Component11 from '@site/src/components/Component11'; import Component12 from '@site/src/components/Component12'; import Component13 from '@site/src/components/Component13'; import Component14 from '@site/src/components/Component14'; import Component15 from '@site/src/components/Component15'; # Markdown Title Lorem Ipsum `; expect( parseMarkdownContentTitle(markdown, {removeContentTitle: true}), ).toEqual({ content: markdown.replace('# Markdown Title\n', ''), contentTitle: 'Markdown Title', }); }); }); describe('parseMarkdownString', () => { it('parse markdown with front matter', () => { expect( parseMarkdownString(dedent` --- title: Frontmatter title --- Some text `), ).toMatchSnapshot(); }); it('parses first heading as contentTitle', () => { expect( parseMarkdownString(dedent` # Markdown Title Some text `), ).toMatchSnapshot(); }); it('warns about duplicate titles (front matter + markdown)', () => { expect( parseMarkdownString(dedent` --- title: Frontmatter title --- # Markdown Title Some text `), ).toMatchSnapshot(); }); it('warns about duplicate titles (front matter + markdown alternate)', () => { expect( parseMarkdownString(dedent` --- title: Frontmatter title --- Markdown Title alternate ================ Some text `), ).toMatchSnapshot(); }); it('does not warn for duplicate title if markdown title is not at the top', () => { expect( parseMarkdownString(dedent` --- title: Frontmatter title --- foo # Markdown Title `), ).toMatchSnapshot(); }); it('deletes only first heading', () => { expect( parseMarkdownString(dedent` # Markdown Title test test test # test bar # Markdown Title 2 ### Markdown Title h3 `), ).toMatchSnapshot(); }); it('parses front-matter and ignore h2', () => { expect( parseMarkdownString( dedent` --- title: Frontmatter title --- ## test `, ), ).toMatchSnapshot(); }); it('reads front matter only', () => { expect( parseMarkdownString(dedent` --- title: test --- `), ).toMatchSnapshot(); }); it('parses title only', () => { expect(parseMarkdownString('# test')).toMatchSnapshot(); }); it('parses title only alternate', () => { expect( parseMarkdownString(dedent` test === `), ).toMatchSnapshot(); }); it('warns about duplicate titles', () => { expect( parseMarkdownString(dedent` --- title: Frontmatter title --- # test `), ).toMatchSnapshot(); }); it('ignores markdown title if its not a first text', () => { expect( parseMarkdownString(dedent` foo # test `), ).toMatchSnapshot(); }); it('deletes only first heading 2', () => { expect( parseMarkdownString(dedent` # test test test test test test test test test test # test bar # test2 ### test test3 `), ).toMatchSnapshot(); }); it('handles code blocks', () => { expect( parseMarkdownString(dedent` \`\`\`js code \`\`\` Content `), ).toMatchSnapshot(); expect( parseMarkdownString(dedent` \`\`\`\`js Foo \`\`\`diff code \`\`\` Bar \`\`\`\` Content `), ).toMatchSnapshot(); expect( parseMarkdownString(dedent` \`\`\`\`js Foo \`\`\`diff code \`\`\`\` Content `), ).toMatchSnapshot(); }); it('throws for invalid front matter', () => { expect(() => parseMarkdownString(dedent` --- foo: f: a --- `), ).toThrowErrorMatchingInlineSnapshot(` "incomplete explicit mapping pair; a key node is missed; or followed by a non-tabulated empty line at line 2, column 7: foo: f: a ^" `); }); }); describe('parseMarkdownHeadingId', () => { it('can parse simple heading without id', () => { expect(parseMarkdownHeadingId('## Some heading')).toEqual({ text: '## Some heading', id: undefined, }); }); it('can parse simple heading with id', () => { expect(parseMarkdownHeadingId('## Some heading {#custom-_id}')).toEqual({ text: '## Some heading', id: 'custom-_id', }); }); it('can parse heading not ending with the id', () => { expect(parseMarkdownHeadingId('## {#custom-_id} Some heading')).toEqual({ text: '## {#custom-_id} Some heading', id: undefined, }); }); it('can parse heading with multiple id', () => { expect(parseMarkdownHeadingId('## Some heading {#id1} {#id2}')).toEqual({ text: '## Some heading {#id1}', id: 'id2', }); }); it('can parse heading with link and id', () => { expect( parseMarkdownHeadingId( '## Some heading [facebook](https://facebook.com) {#id}', ), ).toEqual({ text: '## Some heading [facebook](https://facebook.com)', id: 'id', }); }); it('can parse heading with only id', () => { expect(parseMarkdownHeadingId('## {#id}')).toEqual({ text: '##', id: 'id', }); }); it('does not parse empty id', () => { expect(parseMarkdownHeadingId('## a {#}')).toEqual({ text: '## a {#}', id: undefined, }); }); it('can parse id with more characters', () => { expect(parseMarkdownHeadingId('## a {#你好}')).toEqual({ text: '## a', id: '你好', }); expect(parseMarkdownHeadingId('## a {#2022.1.1}')).toEqual({ text: '## a', id: '2022.1.1', }); expect(parseMarkdownHeadingId('## a {#a#b}')).toEqual({ text: '## a', id: 'a#b', }); }); // The actual behavior is unspecified, just need to ensure it stays consistent it('handles unmatched boundaries', () => { expect(parseMarkdownHeadingId('## a {# a {#bcd}')).toEqual({ text: '## a {# a', id: 'bcd', }); expect(parseMarkdownHeadingId('## a {#bcd}}')).toEqual({ text: '## a {#bcd}}', id: undefined, }); expect(parseMarkdownHeadingId('## a {#b{cd}')).toEqual({ text: '## a', id: 'b{cd', }); expect(parseMarkdownHeadingId('## a {#b{#b}')).toEqual({ text: '## a {#b', id: 'b', }); }); }); describe('escapeMarkdownHeadingIds', () => { it('can escape simple heading id', () => { expect(escapeMarkdownHeadingIds('# title 1 {#id-1}')).toBe( '# title 1 \\{#id-1}', ); expect(escapeMarkdownHeadingIds('# title 1 {#id-1}')).toBe( '# title 1 \\{#id-1}', ); expect(escapeMarkdownHeadingIds('# title 1{#id-1}')).toBe( '# title 1\\{#id-1}', ); expect(escapeMarkdownHeadingIds('# title 1 \\{#id-1}')).toBe( '# title 1 \\{#id-1}', ); expect(escapeMarkdownHeadingIds('# title 1\\{#id-1}')).toBe( '# title 1\\{#id-1}', ); }); it('can escape level 1-6 heading ids', () => { expect( escapeMarkdownHeadingIds(dedent` # title 1 {#id-1} ## title 2 {#id-2} ### title 3 {#id-3} #### title 4 {#id-4} ##### title 5 {#id-5} ###### title 6 {#id-6} `), ).toEqual(dedent` # title 1 \{#id-1} ## title 2 \{#id-2} ### title 3 \{#id-3} #### title 4 \{#id-4} ##### title 5 \{#id-5} ###### title 6 \{#id-6} `); }); it('does not escape level 7 heading id', () => { expect( escapeMarkdownHeadingIds(dedent` ####### title 7 {#id-7} `), ).toEqual(dedent` ####### title 7 {#id-7} `); }); it('does not escape non-heading', () => { expect( escapeMarkdownHeadingIds(dedent` some text {#non-id} `), ).toEqual(dedent` some text {#non-id} `); }); it('works for realistic example', () => { expect( escapeMarkdownHeadingIds(dedent` # Support Docusaurus has a community of thousands of developers. On this page we've listed some Docusaurus-related communities that you can be a part of; see the other pages in this section for additional online and in-person learning materials. Before participating in Docusaurus' communities, [please read our Code of Conduct](https://engineering.fb.com/codeofconduct/). We have adopted the [Contributor Covenant](https://www.contributor-covenant.org/) and we expect that all community members adhere to the guidelines within. ## Stack Overflow {#stack-overflow} Stack Overflow is a popular forum to ask code-level questions or if you're stuck with a specific error. Read through the [existing questions](https://stackoverflow.com/questions/tagged/docusaurus) tagged with **docusaurus** or [ask your own](https://stackoverflow.com/questions/ask?tags=docusaurus)! ## Discussion forums \{#discussion-forums} There are many online forums for discussion about best practices and application architecture as well as the future of Docusaurus. If you have an answerable code-level question, Stack Overflow is usually a better fit. - [Docusaurus online chat](https://discord.gg/docusaurus) - [#help-and-questions](https://discord.gg/fwbcrQ3dHR) for user help - [#contributors](https://discord.gg/6g6ASPA) for contributing help - [Reddit's Docusaurus community](https://www.reddit.com/r/docusaurus/) ## Feature requests {#feature-requests} For new feature requests, you can create a post on our [feature requests board (Canny)](/feature-requests), which is a handy tool for road-mapping and allows for sorting by upvotes, which gives the core team a better indicator of what features are in high demand, as compared to GitHub issues which are harder to triage. Refrain from making a Pull Request for new features (especially large ones) as someone might already be working on it or will be part of our roadmap. Talk to us first! ## News {#news} For the latest news about Docusaurus, [follow **@docusaurus** on Twitter](https://twitter.com/docusaurus) and the [official Docusaurus blog](/blog) on this website. `), ).toEqual(dedent` # Support Docusaurus has a community of thousands of developers. On this page we've listed some Docusaurus-related communities that you can be a part of; see the other pages in this section for additional online and in-person learning materials. Before participating in Docusaurus' communities, [please read our Code of Conduct](https://engineering.fb.com/codeofconduct/). We have adopted the [Contributor Covenant](https://www.contributor-covenant.org/) and we expect that all community members adhere to the guidelines within. ## Stack Overflow \{#stack-overflow} Stack Overflow is a popular forum to ask code-level questions or if you're stuck with a specific error. Read through the [existing questions](https://stackoverflow.com/questions/tagged/docusaurus) tagged with **docusaurus** or [ask your own](https://stackoverflow.com/questions/ask?tags=docusaurus)! ## Discussion forums \{#discussion-forums} There are many online forums for discussion about best practices and application architecture as well as the future of Docusaurus. If you have an answerable code-level question, Stack Overflow is usually a better fit. - [Docusaurus online chat](https://discord.gg/docusaurus) - [#help-and-questions](https://discord.gg/fwbcrQ3dHR) for user help - [#contributors](https://discord.gg/6g6ASPA) for contributing help - [Reddit's Docusaurus community](https://www.reddit.com/r/docusaurus/) ## Feature requests \{#feature-requests} For new feature requests, you can create a post on our [feature requests board (Canny)](/feature-requests), which is a handy tool for road-mapping and allows for sorting by upvotes, which gives the core team a better indicator of what features are in high demand, as compared to GitHub issues which are harder to triage. Refrain from making a Pull Request for new features (especially large ones) as someone might already be working on it or will be part of our roadmap. Talk to us first! ## News \{#news} For the latest news about Docusaurus, [follow **@docusaurus** on Twitter](https://twitter.com/docusaurus) and the [official Docusaurus blog](/blog) on this website. `); }); }); describe('unwrapMdxCodeBlocks', () => { it('can unwrap a simple mdx code block', () => { expect( unwrapMdxCodeBlocks(dedent` # Title \`\`\`mdx-code-block import Comp, {User} from "@site/components/comp" <Comp prop="test"> <User user={{firstName: "Sébastien"}} /> </Comp> export const age = 36 \`\`\` text `), ).toEqual(dedent` # Title import Comp, {User} from "@site/components/comp" <Comp prop="test"> <User user={{firstName: "Sébastien"}} /> </Comp> export const age = 36 text `); }); it('can unwrap a nested mdx code block', () => { expect( unwrapMdxCodeBlocks(dedent` # Title \`\`\`\`mdx-code-block some content \`\`\`js export const age = 36 \`\`\` \`\`\`\` text `), ).toEqual(dedent` # Title some content \`\`\`js export const age = 36 \`\`\` text `); }); it('works for realistic example', () => { expect( unwrapMdxCodeBlocks(dedent` # Canary releases \`\`\`mdx-code-block import { VersionsProvider, } from "@site/src/components/Versions"; <VersionsProvider prop={{attr: 42}} test="yes"> \`\`\` Docusaurus has a canary releases system. It permits you to **test new unreleased features** as soon as the pull requests are merged on the [next version](./5-release-process.md#next-version) of Docusaurus. It is a good way to **give feedback to maintainers**, ensuring the newly implemented feature works as intended. :::note Using a canary release in production might seem risky, but in practice, it's not. A canary release passes all automated tests and is used in production by the Docusaurus site itself. \`\`\`mdx-code-block </VersionsProvider> \`\`\` `), ).toEqual(dedent` # Canary releases import { VersionsProvider, } from "@site/src/components/Versions"; <VersionsProvider prop={{attr: 42}} test="yes"> Docusaurus has a canary releases system. It permits you to **test new unreleased features** as soon as the pull requests are merged on the [next version](./5-release-process.md#next-version) of Docusaurus. It is a good way to **give feedback to maintainers**, ensuring the newly implemented feature works as intended. :::note Using a canary release in production might seem risky, but in practice, it's not. A canary release passes all automated tests and is used in production by the Docusaurus site itself. </VersionsProvider> `); }); }); describe('admonitionTitleToDirectiveLabel', () => { const directives = ['info', 'note', 'tip', 'caution']; it('does not transform markdown without any admonition', () => { expect( admonitionTitleToDirectiveLabel( dedent` # Title intro ## Sub Title content `, directives, ), ).toEqual(dedent` # Title intro ## Sub Title content `); }); it('transform simple admonition', () => { expect( admonitionTitleToDirectiveLabel( dedent` before :::note Title content ::: after `, directives, ), ).toEqual(dedent` before :::note[Title] content ::: after `); }); it('does not transform already transformed admonition', () => { expect( admonitionTitleToDirectiveLabel( dedent` before :::note[Title] content ::: after `, directives, ), ).toEqual(dedent` before :::note[Title] content ::: after `); }); it('does not transform non-container directives', () => { expect( admonitionTitleToDirectiveLabel( dedent` before ::note Title content ::: after `, directives, ), ).toEqual(dedent` before ::note Title content ::: after `); }); it('transforms space indented directives', () => { expect( admonitionTitleToDirectiveLabel( dedent` before :::note 1 space content ::: :::note 2 spaces content ::: after `, directives, ), ).toEqual(dedent` before :::note[1 space] content ::: :::note[2 spaces] content ::: after `); }); it('transforms tab indented directives', () => { expect( admonitionTitleToDirectiveLabel( ` before \t:::note 1 tab \tcontent \t::: \t\t:::note 2 tabs \t\tcontent \t\t::: after `, directives, ), ).toBe(` before \t:::note[1 tab] \tcontent \t::: \t\t:::note[2 tabs] \t\tcontent \t\t::: after `); }); it('transforms directives in quotes', () => { expect( admonitionTitleToDirectiveLabel( ` before > :::caution There be dragons > > This is the admonition content > > ::: > >> :::caution There be dragons >> >> This is the admonition content >> >> ::: > > :::caution There be dragons > > > > This is the admonition content > > > > ::: after `, directives, ), ).toBe(` before > :::caution[There be dragons] > > This is the admonition content > > ::: > >> :::caution[There be dragons] >> >> This is the admonition content >> >> ::: > > :::caution[There be dragons] > > > > This is the admonition content > > > > ::: after `); }); it('does not transform admonition without title', () => { expect( admonitionTitleToDirectiveLabel( dedent` before :::note content ::: after `, directives, ), ).toEqual(dedent` before :::note content ::: after `); }); it('does not transform non-admonition directive', () => { expect( admonitionTitleToDirectiveLabel( dedent` before :::whatever Title content ::: after `, directives, ), ).toEqual(dedent` before :::whatever Title content ::: after `); }); it('transform real-world nested messy admonitions', () => { expect( admonitionTitleToDirectiveLabel( dedent` --- title: "contains :::note" --- # Title intro ::::note note **title** note content ::::tip tip <span>title</span> tip content :::whatever whatever title whatever content ::: :::: ::::: ## Heading {#my-heading} ::::info weird spaced title into content :::tip[tip directiveLabel] tip content :::: ## Conclusion end `, directives, ), ).toEqual(dedent` --- title: "contains :::note" --- # Title intro ::::note[note **title**] note content ::::tip[tip <span>title</span>] tip content :::whatever whatever title whatever content ::: :::: ::::: ## Heading {#my-heading} ::::info[weird spaced title] into content :::tip[tip directiveLabel] tip content :::: ## Conclusion end `); }); }); describe('writeMarkdownHeadingId', () => { it('works for simple level-2 heading', () => { expect(writeMarkdownHeadingId('## ABC')).toBe('## ABC {#abc}'); }); it('works for simple level-3 heading', () => { expect(writeMarkdownHeadingId('### ABC')).toBe('### ABC {#abc}'); }); it('works for simple level-4 heading', () => { expect(writeMarkdownHeadingId('#### ABC')).toBe('#### ABC {#abc}'); }); it('unwraps markdown links', () => { const input = `## hello [facebook](https://facebook.com) [crowdin](https://crowdin.com/translate/docusaurus-v2/126/en-fr?filter=basic&value=0)`; expect(writeMarkdownHeadingId(input)).toBe( `${input} {#hello-facebook-crowdin}`, ); }); it('can slugify complex headings', () => { const input = '## abc [Hello] How are you %Sébastien_-_$)( ## -56756'; expect(writeMarkdownHeadingId(input)).toBe( // cSpell:ignore ébastien `${input} {#abc-hello-how-are-you-sébastien_-_---56756}`, ); }); it('does not duplicate duplicate id', () => { expect(writeMarkdownHeadingId('## hello world {#hello-world}')).toBe( '## hello world {#hello-world}', ); }); it('respects existing heading', () => { expect(writeMarkdownHeadingId('## New heading {#old-heading}')).toBe( '## New heading {#old-heading}', ); }); it('overwrites heading ID when asked to', () => { expect( writeMarkdownHeadingId('## New heading {#old-heading}', { overwrite: true, }), ).toBe('## New heading {#new-heading}'); }); it('maintains casing when asked to', () => { expect( writeMarkdownHeadingId('## getDataFromAPI()', { maintainCase: true, }), ).toBe('## getDataFromAPI() {#getDataFromAPI}'); }); it('transform the headings', () => { const input = ` # Ignored title ## abc ### Hello world \`\`\` # Heading in code block \`\`\` ## Hello world \`\`\` # Heading in escaped code block \`\`\` ### abc {#abc} `; const expected = ` # Ignored title ## abc {#abc-1} ### Hello world {#hello-world} \`\`\` # Heading in code block \`\`\` ## Hello world {#hello-world-1} \`\`\` # Heading in escaped code block \`\`\` ### abc {#abc} `; expect(writeMarkdownHeadingId(input)).toEqual(expected); }); });
2,038
0
petrpan-code/facebook/docusaurus/packages/docusaurus-utils/src
petrpan-code/facebook/docusaurus/packages/docusaurus-utils/src/__tests__/moduleUtils.test.ts
/** * Copyright (c) Facebook, Inc. and its affiliates. * * This source code is licensed under the MIT license found in the * LICENSE file in the root directory of this source tree. */ import fs from 'fs-extra'; import path from 'path'; import tmp from 'tmp-promise'; import dedent from 'dedent'; import {loadFreshModule} from '../moduleUtils'; async function createTmpDir() { return ( await tmp.dir({ prefix: 'jest-tmp-moduleUtils-tests', }) ).path; } async function moduleGraphHelpers() { const dir = await createTmpDir(); async function fileHelper(name: string, initialContent?: string) { const filePath = path.resolve(dir, name); if (initialContent) { await fs.outputFile(filePath, initialContent); } return { filePath, write: (content: string) => fs.outputFile(filePath, content), load: () => loadFreshModule(filePath), }; } return {fileHelper}; } async function loadFixtureModule(fixtureName: string) { return loadFreshModule( path.resolve(__dirname, '__fixtures__/moduleUtils', fixtureName), ); } describe('loadFreshModule', () => { describe('can load CJS user module', () => { async function testUserFixture(fixtureName: string) { const userFixturePath = `user/${fixtureName}`; const userModule = await loadFixtureModule(userFixturePath); expect(userModule).toEqual({ birthYear: 1986, firstName: 'Sebastien', lastName: 'Lorber', }); } it('for .cjs.js', async () => { await testUserFixture('user.cjs.js'); }); it('for .cjs.ts', async () => { await testUserFixture('user.cjs.ts'); }); it('for .cjs', async () => { await testUserFixture('user.cjs'); }); }); describe('can load ESM user module', () => { async function testUserFixture(fixtureName: string) { const userFixturePath = `user/${fixtureName}`; const userModule = await loadFixtureModule(userFixturePath); expect(userModule).toEqual({ birthYear: 1986, firstName: 'Sebastien', lastName: 'Lorber', someNamedExport: 42, }); } it('for .esm.js', async () => { await testUserFixture('user.esm.js'); }); it('for .esm.ts', async () => { await testUserFixture('user.esm.ts'); }); it('for .mjs', async () => { await testUserFixture('user.mjs'); }); }); describe('module graph', () => { it('can load and reload fresh module graph', async () => { const {fileHelper} = await moduleGraphHelpers(); const dependency1 = await fileHelper( 'dependency1.js', /* language=js */ dedent` export const dep1Export = "dep1 val1"; export default {dep1Val: "dep1 val2"} `, ); const dependency2 = await fileHelper( 'dependency2.ts', /* language=ts */ dedent` export default {dep2Val: "dep2 val"} satisfies {dep2Val: string} `, ); const entryFile = await fileHelper( 'entry.js', /* language=js */ dedent` import dependency1 from "./dependency1"; import dependency2 from "./dependency2"; export default { someEntryValue: "entryVal", dependency1, dependency2 }; `, ); // Should be able to read the initial module graph await expect(entryFile.load()).resolves.toEqual({ someEntryValue: 'entryVal', dependency1: { dep1Export: 'dep1 val1', dep1Val: 'dep1 val2', }, dependency2: { dep2Val: 'dep2 val', }, }); await expect(dependency1.load()).resolves.toEqual({ dep1Export: 'dep1 val1', dep1Val: 'dep1 val2', }); await expect(dependency2.load()).resolves.toEqual({ dep2Val: 'dep2 val', }); // Should be able to read the module graph again after updates await dependency1.write( /* language=js */ dedent` export const dep1Export = "dep1 val1 updated"; export default {dep1Val: "dep1 val2 updated"} `, ); await expect(entryFile.load()).resolves.toEqual({ someEntryValue: 'entryVal', dependency1: { dep1Export: 'dep1 val1 updated', dep1Val: 'dep1 val2 updated', }, dependency2: { dep2Val: 'dep2 val', }, }); await expect(dependency1.load()).resolves.toEqual({ dep1Export: 'dep1 val1 updated', dep1Val: 'dep1 val2 updated', }); await expect(dependency2.load()).resolves.toEqual({ dep2Val: 'dep2 val', }); // Should be able to read the module graph again after updates await dependency2.write( /* language=ts */ dedent` export default {dep2Val: "dep2 val updated"} satisfies {dep2Val: string} `, ); await expect(entryFile.load()).resolves.toEqual({ someEntryValue: 'entryVal', dependency1: { dep1Export: 'dep1 val1 updated', dep1Val: 'dep1 val2 updated', }, dependency2: { dep2Val: 'dep2 val updated', }, }); await expect(dependency1.load()).resolves.toEqual({ dep1Export: 'dep1 val1 updated', dep1Val: 'dep1 val2 updated', }); await expect(dependency2.load()).resolves.toEqual({ dep2Val: 'dep2 val updated', }); // Should be able to read the module graph again after updates await entryFile.write( /* language=js */ dedent` import dependency1 from "./dependency1"; import dependency2 from "./dependency2"; export default { someEntryValue: "entryVal updated", dependency1, dependency2, newAttribute: "is there" } `, ); await expect(entryFile.load()).resolves.toEqual({ someEntryValue: 'entryVal updated', newAttribute: 'is there', dependency1: { dep1Export: 'dep1 val1 updated', dep1Val: 'dep1 val2 updated', }, dependency2: { dep2Val: 'dep2 val updated', }, }); await expect(dependency1.load()).resolves.toEqual({ dep1Export: 'dep1 val1 updated', dep1Val: 'dep1 val2 updated', }); await expect(dependency2.load()).resolves.toEqual({ dep2Val: 'dep2 val updated', }); }); }); describe('invalid module path param', () => { it('throws if module path does not exist', async () => { await expect(() => loadFreshModule('/some/unknown/module/path.js')) .rejects.toThrowErrorMatchingInlineSnapshot(` "Docusaurus could not load module at path "/some/unknown/module/path.js" Cause: Cannot find module '/some/unknown/module/path.js' from 'packages/docusaurus-utils/src/moduleUtils.ts'" `); }); it('throws if module path is undefined', async () => { await expect(() => // @ts-expect-error: undefined is invalid loadFreshModule(undefined), ).rejects.toThrowErrorMatchingInlineSnapshot(` "Docusaurus could not load module at path "undefined" Cause: Invalid module path of type undefined" `); }); it('throws if module path is null', async () => { await expect(() => // @ts-expect-error: null is invalid loadFreshModule(null), ).rejects.toThrowErrorMatchingInlineSnapshot(` "Docusaurus could not load module at path "null" Cause: Invalid module path of type null" `); }); it('throws if module path is number', async () => { await expect(() => // @ts-expect-error: number is invalid loadFreshModule(42), ).rejects.toThrowErrorMatchingInlineSnapshot(` "Docusaurus could not load module at path "42" Cause: Invalid module path of type 42" `); }); it('throws if module path is object', async () => { await expect(() => // @ts-expect-error: object is invalid loadFreshModule({}), ).rejects.toThrowErrorMatchingInlineSnapshot(` "Docusaurus could not load module at path "[object Object]" Cause: Invalid module path of type [object Object]" `); }); }); });
2,039
0
petrpan-code/facebook/docusaurus/packages/docusaurus-utils/src
petrpan-code/facebook/docusaurus/packages/docusaurus-utils/src/__tests__/pathUtils.test.ts
/** * Copyright (c) Facebook, Inc. and its affiliates. * * This source code is licensed under the MIT license found in the * LICENSE file in the root directory of this source tree. */ import {jest} from '@jest/globals'; import path from 'path'; import { isNameTooLong, shortName, escapePath, posixPath, aliasedSitePath, toMessageRelativeFilePath, addTrailingPathSeparator, } from '../pathUtils'; describe('isNameTooLong', () => { it('works', () => { const asserts = { '': false, 'foo-bar-096': false, 'foo-bar-1df': false, 'endi-lie-9fa': false, 'endi-lie-fd3': false, 'yangshun-tay-48d': false, 'yangshun-tay-f3b': false, 'foo-bar-foo-bar-foo-bar-foo-bar-foo-bar-foo-bar-foo-bar-foo-bar-foo-bar-foo-bar-foo-bar-foo-bar-foo-bar-foo-bar-foo-bar-foo-bar-foo-bar-foo-bar-foo-bar-foo-bar-foo-bar-foo-bar-foo-bar-foo-bar-foo-bar-foo-bar-foo-bar-foo-bar-foo-bar-foo-bar-foo-bar-foo-bar-d46': true, 'foo-bar-foo-bar-foo-bar-foo-bar-foo-bar-foo-bar-foo-bar-foo-bar-foo-bar-foo-bar-foo-bar-foo-bar-foo-bar-foo-bar-foo-bar-foo-bar-foo-bar-foo-bar-foo-bar-foo-bar-foo-bar-foo-bar-foo-bar-foo-bar-foo-bar-foo-bar-foo-bar-foo-bar-foo-bar-test-1-test-2-787': true, // Every Han zi is three bytes 字字字字字字字字字字字字字字字字字字字字字字字字字字字字字字字字字字字字字字字字字字字字字字字字字字字字字字字字字字字字字字字字字字字字字字字字字字字字字字字字字字字字字字字: {apfs: false, xfs: true}, }; const oldProcessPlatform = process.platform; Object.defineProperty(process, 'platform', {value: 'darwin'}); (Object.keys(asserts) as (keyof typeof asserts)[]).forEach((file) => { const expected = asserts[file]; expect(isNameTooLong(file)).toBe( typeof expected === 'boolean' ? expected : expected.apfs, ); }); Object.defineProperty(process, 'platform', {value: 'win32'}); (Object.keys(asserts) as (keyof typeof asserts)[]).forEach((file) => { const expected = asserts[file]; expect(isNameTooLong(file)).toBe( typeof expected === 'boolean' ? expected : expected.apfs, ); }); Object.defineProperty(process, 'platform', {value: 'android'}); (Object.keys(asserts) as (keyof typeof asserts)[]).forEach((file) => { const expected = asserts[file]; expect(isNameTooLong(file)).toBe( typeof expected === 'boolean' ? expected : expected.xfs, ); }); Object.defineProperty(process, 'platform', {value: oldProcessPlatform}); }); }); describe('shortName', () => { it('works', () => { const asserts = { '': '', 'foo-bar': 'foo-bar', 'endi-lie': 'endi-lie', 'yangshun-tay': 'yangshun-tay', 'foo-bar-foo-bar-foo-bar-foo-bar-foo-bar-foo-bar-foo-bar-foo-bar-foo-bar-foo-bar-foo-bar-foo-bar-foo-bar-foo-bar-foo-bar-foo-bar-foo-bar-foo-bar-foo-bar-foo-bar-foo-bar-foo-bar-foo-bar-foo-bar-foo-bar-foo-bar-foo-bar-foo-bar-foo-bar-foo-bar-foo-bar-foo-bar': 'foo-bar-foo-bar-foo-bar-foo-bar-foo-bar-foo-bar-foo-bar-foo-bar-foo-bar-foo-bar-foo-bar-foo-bar-foo-bar-foo-bar-foo-bar-foo-bar-foo-bar-foo-bar-foo-bar-foo-bar-foo-bar-foo-bar-foo-bar-foo-bar-foo-bar-foo-bar-foo-bar-foo-bar-foo-bar-foo-bar-foo-', 'foo-bar-foo-bar-foo-bar-foo-bar-foo-bar-foo-bar-foo-bar-foo-bar-foo-bar-foo-bar-foo-bar-foo-bar-foo-bar-foo-bar-foo-bar-foo-bar-foo-bar-foo-bar-foo-bar-foo-bar-foo-bar-foo-bar-foo-bar-foo-bar-foo-bar-foo-bar-foo-bar-foo-bar-foo-bar-test-1-test-2': 'foo-bar-foo-bar-foo-bar-foo-bar-foo-bar-foo-bar-foo-bar-foo-bar-foo-bar-foo-bar-foo-bar-foo-bar-foo-bar-foo-bar-foo-bar-foo-bar-foo-bar-foo-bar-foo-bar-foo-bar-foo-bar-foo-bar-foo-bar-foo-bar-foo-bar-foo-bar-foo-bar-foo-bar-foo-bar-test-1-test-', 字字字字字字字字字字字字字字字字字字字字字字字字字字字字字字字字字字字字字字字字字字字字字字字字字字字字字字字字字字字字字字字字字字字字字字字字字字字字字字字字字字字字字字字: { apfs: '字字字字字字字字字字字字字字字字字字字字字字字字字字字字字字字字字字字字字字字字字字字字字字字字字字字字字字字字字字字字字字字字字字字字字字字字字字字字字字字字字字字字字字字', // This is pretty bad (a character clipped in half), but I doubt if it // ever happens xfs: '字字字字字字字字字字字字字字字字字字字字字字字字字字字字字字字字字字字字字字字字字字字字字字字字字字字字字字字字字字字字字字字字字字字字字字字字字字字字字字字字字�', }, }; const oldProcessPlatform = process.platform; Object.defineProperty(process, 'platform', {value: 'darwin'}); (Object.keys(asserts) as (keyof typeof asserts)[]).forEach((file) => { const expected = asserts[file]; expect(shortName(file)).toBe( typeof expected === 'string' ? expected : expected.apfs, ); }); Object.defineProperty(process, 'platform', {value: 'win32'}); (Object.keys(asserts) as (keyof typeof asserts)[]).forEach((file) => { const expected = asserts[file]; expect(shortName(file)).toBe( typeof expected === 'string' ? expected : expected.apfs, ); }); Object.defineProperty(process, 'platform', {value: 'android'}); (Object.keys(asserts) as (keyof typeof asserts)[]).forEach((file) => { const expected = asserts[file]; expect(shortName(file)).toBe( typeof expected === 'string' ? expected : expected.xfs, ); }); Object.defineProperty(process, 'platform', {value: oldProcessPlatform}); }); // Based on https://github.com/gatsbyjs/gatsby/pull/21518/files const SHORT_PATH = `/short/path/without/trailing/slash`; const VERY_LONG_PATH = `/${`x`.repeat(256)}/`; const VERY_LONG_PATH_NON_LATIN = `/${`あ`.repeat(255)}/`; it('truncates long paths correctly', () => { const truncatedPathLatin = shortName(VERY_LONG_PATH); const truncatedPathNonLatin = shortName(VERY_LONG_PATH_NON_LATIN); expect(truncatedPathLatin.length).toBeLessThanOrEqual(255); expect(truncatedPathNonLatin.length).toBeLessThanOrEqual(255); }); it('does not truncate short paths', () => { const truncatedPath = shortName(SHORT_PATH); expect(truncatedPath).toEqual(SHORT_PATH); }); }); describe('toMessageRelativeFilePath', () => { it('works', () => { jest .spyOn(process, 'cwd') .mockImplementationOnce(() => path.join(__dirname, '..')); expect(toMessageRelativeFilePath(path.join(__dirname, 'foo/bar.js'))).toBe( '__tests__/foo/bar.js', ); }); }); describe('escapePath', () => { it('works', () => { const asserts: {[key: string]: string} = { 'c:/aaaa\\bbbb': 'c:/aaaa\\\\bbbb', 'c:\\aaaa\\bbbb\\★': 'c:\\\\aaaa\\\\bbbb\\\\★', '\\\\?\\c:\\aaaa\\bbbb': '\\\\\\\\?\\\\c:\\\\aaaa\\\\bbbb', 'c:\\aaaa\\bbbb': 'c:\\\\aaaa\\\\bbbb', 'foo\\bar': 'foo\\\\bar', 'foo\\bar/lol': 'foo\\\\bar/lol', 'website\\docs/**/*.{md,mdx}': 'website\\\\docs/**/*.{md,mdx}', }; Object.keys(asserts).forEach((file) => { expect(escapePath(file)).toBe(asserts[file]); }); }); }); describe('posixPath', () => { it('works', () => { const asserts: {[key: string]: string} = { 'c:/aaaa\\bbbb': 'c:/aaaa/bbbb', 'c:\\aaaa\\bbbb\\★': 'c:/aaaa/bbbb/★', '\\\\?\\c:\\aaaa\\bbbb': '\\\\?\\c:\\aaaa\\bbbb', 'c:\\aaaa\\bbbb': 'c:/aaaa/bbbb', 'foo\\bar': 'foo/bar', 'foo\\bar/lol': 'foo/bar/lol', 'website\\docs/**/*.{md,mdx}': 'website/docs/**/*.{md,mdx}', }; Object.keys(asserts).forEach((file) => { expect(posixPath(file)).toBe(asserts[file]); }); }); }); describe('aliasedSitePath', () => { it('works', () => { const asserts: {[key: string]: string} = { 'user/website/docs/asd.md': '@site/docs/asd.md', 'user/website/versioned_docs/foo/bar.md': '@site/versioned_docs/foo/bar.md', 'user/docs/test.md': '@site/../docs/test.md', }; Object.keys(asserts).forEach((file) => { expect(posixPath(aliasedSitePath(file, 'user/website'))).toBe( asserts[file], ); }); }); }); describe('addTrailingPathSeparator', () => { it('works', () => { expect(addTrailingPathSeparator('foo')).toEqual( process.platform === 'win32' ? 'foo\\' : 'foo/', ); expect(addTrailingPathSeparator('foo/')).toEqual( process.platform === 'win32' ? 'foo\\' : 'foo/', ); }); });
2,040
0
petrpan-code/facebook/docusaurus/packages/docusaurus-utils/src
petrpan-code/facebook/docusaurus/packages/docusaurus-utils/src/__tests__/shellUtils.test.ts
/** * Copyright (c) Facebook, Inc. and its affiliates. * * This source code is licensed under the MIT license found in the * LICENSE file in the root directory of this source tree. */ import {escapeShellArg} from '../shellUtils'; describe('shellUtils', () => { it('escapeShellArg', () => { expect(escapeShellArg('hello')).toBe("'hello'"); expect(escapeShellArg('*')).toBe("'*'"); expect(escapeShellArg('hello world')).toBe("'hello world'"); expect(escapeShellArg("'hello'")).toBe("\\''hello'\\'"); expect(escapeShellArg('$(pwd)')).toBe("'$(pwd)'"); expect(escapeShellArg('hello$(pwd)')).toBe("'hello$(pwd)'"); }); });
2,041
0
petrpan-code/facebook/docusaurus/packages/docusaurus-utils/src
petrpan-code/facebook/docusaurus/packages/docusaurus-utils/src/__tests__/slugger.test.ts
/** * Copyright (c) Facebook, Inc. and its affiliates. * * This source code is licensed under the MIT license found in the * LICENSE file in the root directory of this source tree. */ import {createSlugger} from '../slugger'; describe('createSlugger', () => { it('can create unique slugs', () => { const slugger = createSlugger(); // cSpell:ignore somevalue expect(slugger.slug('Some$/vaLue$!^')).toBe('somevalue'); expect(slugger.slug('Some$/vaLue$!^')).toBe('somevalue-1'); expect(slugger.slug('Some$/vaLue$!^')).toBe('somevalue-2'); expect(slugger.slug('Some$/vaLue$!^-1')).toBe('somevalue-1-1'); }); it('can create unique slugs respecting case', () => { const slugger = createSlugger(); const opt = {maintainCase: true}; expect(slugger.slug('Some$/vaLue$!^', opt)).toBe('SomevaLue'); expect(slugger.slug('Some$/vaLue$!^', opt)).toBe('SomevaLue-1'); expect(slugger.slug('Some$/vaLue$!^', opt)).toBe('SomevaLue-2'); expect(slugger.slug('Some$/vaLue$!^-1', opt)).toBe('SomevaLue-1-1'); }); });
2,042
0
petrpan-code/facebook/docusaurus/packages/docusaurus-utils/src
petrpan-code/facebook/docusaurus/packages/docusaurus-utils/src/__tests__/tags.test.ts
/** * Copyright (c) Facebook, Inc. and its affiliates. * * This source code is licensed under the MIT license found in the * LICENSE file in the root directory of this source tree. */ import { normalizeFrontMatterTags, groupTaggedItems, type Tag, getTagVisibility, } from '../tags'; describe('normalizeFrontMatterTags', () => { it('normalizes simple string tag', () => { const tagsPath = '/all/tags'; const input = 'tag'; const expectedOutput = { label: 'tag', permalink: `${tagsPath}/tag`, }; expect(normalizeFrontMatterTags(tagsPath, [input])).toEqual([ expectedOutput, ]); }); it('normalizes complex string tag', () => { const tagsPath = '/all/tags'; const input = 'some more Complex_tag'; const expectedOutput = { label: 'some more Complex_tag', permalink: `${tagsPath}/some-more-complex-tag`, }; expect(normalizeFrontMatterTags(tagsPath, [input])).toEqual([ expectedOutput, ]); }); it('normalizes simple object tag', () => { const tagsPath = '/all/tags'; const input = {label: 'tag', permalink: 'tagPermalink'}; const expectedOutput = { label: 'tag', permalink: `${tagsPath}/tagPermalink`, }; expect(normalizeFrontMatterTags(tagsPath, [input])).toEqual([ expectedOutput, ]); }); it('normalizes complex string tag with object tag', () => { const tagsPath = '/all/tags'; const input = { label: 'tag complex Label', permalink: '/MoreComplex/Permalink', }; const expectedOutput = { label: 'tag complex Label', permalink: `${tagsPath}/MoreComplex/Permalink`, }; expect(normalizeFrontMatterTags(tagsPath, [input])).toEqual([ expectedOutput, ]); }); type Input = Parameters<typeof normalizeFrontMatterTags>[1]; type Output = ReturnType<typeof normalizeFrontMatterTags>; it('normalizes string list', () => { const tagsPath = '/all/tags'; const input: Input = ['tag 1', 'tag-1', 'tag 3', 'tag1', 'tag-2']; // Keep user input order but remove tags that lead to same permalink const expectedOutput: Output = [ { label: 'tag 1', permalink: `${tagsPath}/tag-1`, }, { label: 'tag 3', permalink: `${tagsPath}/tag-3`, }, { label: 'tag-2', permalink: `${tagsPath}/tag-2`, }, ]; expect(normalizeFrontMatterTags(tagsPath, input)).toEqual(expectedOutput); }); it('succeeds for empty list', () => { expect(normalizeFrontMatterTags('/foo')).toEqual([]); }); it('normalizes complex mixed list', () => { const tagsPath = '/all/tags'; const input: Input = [ 'tag 1', {label: 'tag-1', permalink: '/tag-1'}, 'tag 3', 'tag1', {label: 'tag 4', permalink: '/tag4Permalink'}, ]; // Keep user input order but remove tags that lead to same permalink const expectedOutput: Output = [ { label: 'tag 1', permalink: `${tagsPath}/tag-1`, }, { label: 'tag 3', permalink: `${tagsPath}/tag-3`, }, { label: 'tag 4', permalink: `${tagsPath}/tag4Permalink`, }, ]; expect(normalizeFrontMatterTags(tagsPath, input)).toEqual(expectedOutput); }); }); describe('groupTaggedItems', () => { type SomeTaggedItem = { id: string; nested: { tags: Tag[]; }; }; function groupItems(items: SomeTaggedItem[]) { return groupTaggedItems(items, (item) => item.nested.tags); } type Input = Parameters<typeof groupItems>[0]; type Output = ReturnType<typeof groupItems>; it('groups items by tag permalink', () => { const tagGuide = {label: 'Guide', permalink: '/guide'}; const tagTutorial = {label: 'Tutorial', permalink: '/tutorial'}; const tagAPI = {label: 'API', permalink: '/api'}; // This one will be grouped under same permalink and label is ignored const tagTutorialOtherLabel = { label: 'TutorialOtherLabel', permalink: '/tutorial', }; const item1: SomeTaggedItem = { id: '1', nested: { tags: [ tagGuide, tagTutorial, tagAPI, // Add some duplicates on purpose: they should be filtered tagGuide, tagTutorialOtherLabel, ], }, }; const item2: SomeTaggedItem = { id: '2', nested: { tags: [tagAPI], }, }; const item3: SomeTaggedItem = { id: '3', nested: { tags: [tagTutorial], }, }; const item4: SomeTaggedItem = { id: '4', nested: { tags: [tagTutorialOtherLabel], }, }; const input: Input = [item1, item2, item3, item4]; const expectedOutput: Output = { '/guide': {tag: tagGuide, items: [item1]}, '/tutorial': {tag: tagTutorial, items: [item1, item3, item4]}, '/api': {tag: tagAPI, items: [item1, item2]}, }; expect(groupItems(input)).toEqual(expectedOutput); }); }); describe('getTagVisibility', () => { type Item = {id: string; unlisted: boolean}; function isUnlisted(item: Item): boolean { return item.unlisted; } const item1: Item = {id: '1', unlisted: false}; const item2: Item = {id: '2', unlisted: true}; const item3: Item = {id: '3', unlisted: false}; const item4: Item = {id: '4', unlisted: true}; it('works for some unlisted', () => { expect( getTagVisibility({ items: [item1, item2, item3, item4], isUnlisted, }), ).toEqual({ listedItems: [item1, item3], unlisted: false, }); }); it('works for all unlisted', () => { expect( getTagVisibility({ items: [item2, item4], isUnlisted, }), ).toEqual({ listedItems: [item2, item4], unlisted: true, }); }); it('works for all listed', () => { expect( getTagVisibility({ items: [item1, item3], isUnlisted, }), ).toEqual({ listedItems: [item1, item3], unlisted: false, }); }); });
2,043
0
petrpan-code/facebook/docusaurus/packages/docusaurus-utils/src
petrpan-code/facebook/docusaurus/packages/docusaurus-utils/src/__tests__/urlUtils.test.ts
/** * Copyright (c) Facebook, Inc. and its affiliates. * * This source code is licensed under the MIT license found in the * LICENSE file in the root directory of this source tree. */ import { normalizeUrl, getEditUrl, fileToPath, isValidPathname, addTrailingSlash, addLeadingSlash, removeTrailingSlash, resolvePathname, encodePath, buildSshUrl, buildHttpsUrl, hasSSHProtocol, } from '../urlUtils'; describe('normalizeUrl', () => { it('normalizes urls correctly', () => { const asserts = [ { input: [], output: '', }, { input: ['/', ''], output: '/', }, { input: ['', '/'], output: '/', }, { input: ['/'], output: '/', }, { input: [''], output: '', }, { input: ['/', '/'], output: '/', }, { input: ['/', 'docs'], output: '/docs', }, { input: ['/', 'docs', 'en', 'next', 'blog'], output: '/docs/en/next/blog', }, { input: ['/test/', '/docs', 'ro', 'doc1'], output: '/test/docs/ro/doc1', }, { input: ['/test/', '/', 'ro', 'doc1'], output: '/test/ro/doc1', }, { input: ['/', '/', '2020/02/29/leap-day'], output: '/2020/02/29/leap-day', }, { input: ['', '/', 'ko', 'hello'], output: '/ko/hello', }, { input: ['hello', 'world'], output: 'hello/world', }, { input: ['http://www.google.com/', 'foo/bar', '?test=123'], output: 'http://www.google.com/foo/bar?test=123', }, { input: ['http:', 'www.google.com///', 'foo/bar', '?test=123'], output: 'http://www.google.com/foo/bar?test=123', }, { input: ['http://foobar.com', '', 'test'], output: 'http://foobar.com/test', }, { input: ['http://foobar.com', '', 'test', '/'], output: 'http://foobar.com/test/', }, { input: ['/', '', 'hello', '', '/', '/', '', '/', '/world'], output: '/hello/world', }, { input: ['', '', '/tt', 'ko', 'hello'], output: '/tt/ko/hello', }, { input: ['', '///hello///', '', '///world'], output: '/hello/world', }, { input: ['', '/hello/', ''], output: '/hello/', }, { input: ['', '/', ''], output: '/', }, { input: ['///', '///'], output: '/', }, { input: ['/', '/hello/world/', '///'], output: '/hello/world/', }, { input: ['file://', '//hello/world/'], output: 'file:///hello/world/', }, { input: ['file:', '/hello/world/'], output: 'file:///hello/world/', }, { input: ['file://', '/hello/world/'], output: 'file:///hello/world/', }, { input: ['file:', 'hello/world/'], output: 'file://hello/world/', }, ]; asserts.forEach((testCase) => { expect(normalizeUrl(testCase.input)).toBe(testCase.output); }); expect(() => // @ts-expect-error undefined for test normalizeUrl(['http:example.com', undefined]), ).toThrowErrorMatchingInlineSnapshot( `"Url must be a string. Received undefined"`, ); }); }); describe('getEditUrl', () => { it('returns right path', () => { expect( getEditUrl('foo/bar.md', 'https://github.com/facebook/docusaurus'), ).toBe('https://github.com/facebook/docusaurus/foo/bar.md'); expect( getEditUrl('foo/你好.md', 'https://github.com/facebook/docusaurus'), ).toBe('https://github.com/facebook/docusaurus/foo/你好.md'); }); it('always returns valid URL', () => { expect( getEditUrl('foo\\你好.md', 'https://github.com/facebook/docusaurus'), ).toBe('https://github.com/facebook/docusaurus/foo/你好.md'); }); it('returns undefined for undefined', () => { expect(getEditUrl('foo/bar.md')).toBeUndefined(); }); }); describe('fileToPath', () => { it('works', () => { const asserts: {[key: string]: string} = { 'index.md': '/', 'hello/index.md': '/hello/', 'foo.md': '/foo', 'foo/bar.md': '/foo/bar', 'index.js': '/', 'hello/index.js': '/hello/', 'foo.js': '/foo', 'foo/bar.js': '/foo/bar', }; Object.keys(asserts).forEach((file) => { expect(fileToPath(file)).toBe(asserts[file]); }); }); }); describe('isValidPathname', () => { it('works', () => { expect(isValidPathname('/')).toBe(true); expect(isValidPathname('/hey')).toBe(true); expect(isValidPathname('/hey/ho')).toBe(true); expect(isValidPathname('/hey/ho/')).toBe(true); expect(isValidPathname('/hey/h%C3%B4/')).toBe(true); expect(isValidPathname('/hey///ho///')).toBe(true); // Unexpected but valid expect(isValidPathname('/hey/héllô you')).toBe(true); expect(isValidPathname('')).toBe(false); expect(isValidPathname('hey')).toBe(false); expect(isValidPathname('/hey?qs=ho')).toBe(false); expect(isValidPathname('https://fb.com/hey')).toBe(false); expect(isValidPathname('//hey')).toBe(false); expect(isValidPathname('////')).toBe(false); }); }); describe('addTrailingSlash', () => { it('is no-op for path with trailing slash', () => { expect(addTrailingSlash('/abcd/')).toBe('/abcd/'); }); it('adds / for path without trailing slash', () => { expect(addTrailingSlash('/abcd')).toBe('/abcd/'); }); }); describe('addLeadingSlash', () => { it('is no-op for path with leading slash', () => { expect(addLeadingSlash('/abc')).toBe('/abc'); }); it('adds / for path without leading slash', () => { expect(addLeadingSlash('abc')).toBe('/abc'); }); }); describe('removeTrailingSlash', () => { it('is no-op for path without trailing slash', () => { expect(removeTrailingSlash('/abcd')).toBe('/abcd'); }); it('removes / for path with trailing slash', () => { expect(removeTrailingSlash('/abcd/')).toBe('/abcd'); }); }); describe('resolvePathname', () => { it('works', () => { // These tests are directly copied from https://github.com/mjackson/resolve-pathname/blob/master/modules/__tests__/resolvePathname-test.js // Maybe we want to wrap that logic in the future? expect(resolvePathname('c')).toBe('c'); expect(resolvePathname('c', 'a/b')).toBe('a/c'); expect(resolvePathname('/c', '/a/b')).toBe('/c'); expect(resolvePathname('', '/a/b')).toBe('/a/b'); expect(resolvePathname('../c', '/a/b')).toBe('/c'); expect(resolvePathname('c', '/a/b')).toBe('/a/c'); expect(resolvePathname('c', '/a/')).toBe('/a/c'); expect(resolvePathname('..', '/a/b')).toBe('/'); }); }); describe('encodePath', () => { it('works', () => { expect(encodePath('a/foo/')).toBe('a/foo/'); // cSpell:ignore cfoo expect(encodePath('a/<foo>/')).toBe('a/%3Cfoo%3E/'); expect(encodePath('a/你好/')).toBe('a/%E4%BD%A0%E5%A5%BD/'); }); }); describe('buildSshUrl', () => { it('builds a normal ssh url', () => { const url = buildSshUrl('github.com', 'facebook', 'docusaurus'); expect(url).toBe('[email protected]:facebook/docusaurus.git'); }); it('builds a ssh url with port', () => { const url = buildSshUrl('github.com', 'facebook', 'docusaurus', '422'); expect(url).toBe('ssh://[email protected]:422/facebook/docusaurus.git'); }); }); describe('buildHttpsUrl', () => { it('builds a normal http url', () => { const url = buildHttpsUrl( 'user:pass', 'github.com', 'facebook', 'docusaurus', ); expect(url).toBe('https://user:[email protected]/facebook/docusaurus.git'); }); it('builds a normal http url with port', () => { const url = buildHttpsUrl( 'user:pass', 'github.com', 'facebook', 'docusaurus', '5433', ); expect(url).toBe( 'https://user:[email protected]:5433/facebook/docusaurus.git', ); }); }); describe('hasSSHProtocol', () => { it('recognizes explicit SSH protocol', () => { const url = 'ssh://[email protected]:422/facebook/docusaurus.git'; expect(hasSSHProtocol(url)).toBe(true); }); it('recognizes implied SSH protocol', () => { const url = '[email protected]:facebook/docusaurus.git'; expect(hasSSHProtocol(url)).toBe(true); }); it('does not recognize HTTPS with credentials', () => { const url = 'https://user:[email protected]/facebook/docusaurus.git'; expect(hasSSHProtocol(url)).toBe(false); }); it('does not recognize plain HTTPS URL', () => { const url = 'https://github.com:5433/facebook/docusaurus.git'; expect(hasSSHProtocol(url)).toBe(false); }); });
2,044
0
petrpan-code/facebook/docusaurus/packages/docusaurus-utils/src
petrpan-code/facebook/docusaurus/packages/docusaurus-utils/src/__tests__/webpackUtils.test.ts
/** * Copyright (c) Facebook, Inc. and its affiliates. * * This source code is licensed under the MIT license found in the * LICENSE file in the root directory of this source tree. */ import {getFileLoaderUtils} from '../webpackUtils'; describe('getFileLoaderUtils()', () => { it('plugin svgo/removeViewBox and removeTitle should be disabled', () => { const {oneOf} = getFileLoaderUtils().rules.svg(); expect(oneOf![0]!.use).toContainEqual( expect.objectContaining({ loader: require.resolve('@svgr/webpack'), options: expect.objectContaining({ svgoConfig: { plugins: [ { name: 'preset-default', params: { overrides: { removeTitle: false, removeViewBox: false, }, }, }, ], }, }), }), ); }); });
2,059
0
petrpan-code/facebook/docusaurus/packages/docusaurus-utils/src/__tests__
petrpan-code/facebook/docusaurus/packages/docusaurus-utils/src/__tests__/__snapshots__/markdownLinks.test.ts.snap
// Jest Snapshot v1, https://goo.gl/fbAQLP exports[`replaceMarkdownLinks does basic replace 1`] = ` { "brokenMarkdownLinks": [ { "contentPaths": { "contentPath": "docs", "contentPathLocalized": "i18n/docs-localized", }, "filePath": "docs/intro.md", "link": "hmmm.md", }, ], "newContent": " [foo](/doc/foo) [baz](/doc/baz) [foo](/doc/foo) [http](http://github.com/facebook/docusaurus/README.md) [https](https://github.com/facebook/docusaurus/README.md) [asset](./foo.js) [asset as well](@site/docs/_partial.md) [looks like http...](/doc/http) [nonexistent](hmmm.md) ", } `; exports[`replaceMarkdownLinks handles link titles 1`] = ` { "brokenMarkdownLinks": [], "newContent": " [URL](/docs/file "title") [URL](/docs/file 'title') [URL](/docs/file (title)) ", } `; exports[`replaceMarkdownLinks handles stray spaces 1`] = ` { "brokenMarkdownLinks": [], "newContent": " [URL]( /docs/file ) [ref]: /docs/file ", } `; exports[`replaceMarkdownLinks handles unpaired fences 1`] = ` { "brokenMarkdownLinks": [], "newContent": " \`\`\`foo hello \`\`\`foo hello \`\`\` A [link](/docs/file) ", } `; exports[`replaceMarkdownLinks ignores links in HTML comments 1`] = ` { "brokenMarkdownLinks": [ { "contentPaths": { "contentPath": "docs", "contentPathLocalized": "i18n/docs-localized", }, "filePath": "docs/intro.md", "link": "./foo.md", }, { "contentPaths": { "contentPath": "docs", "contentPathLocalized": "i18n/docs-localized", }, "filePath": "docs/intro.md", "link": "./foo.md", }, ], "newContent": " <!-- [foo](./foo.md) --> <!-- [foo](./foo.md) --> ", } `; exports[`replaceMarkdownLinks ignores links in fenced blocks 1`] = ` { "brokenMarkdownLinks": [], "newContent": " \`\`\` [foo](foo.md) \`\`\` \`\`\`\`js [foo](foo.md) \`\`\` [foo](foo.md) \`\`\` [foo](foo.md) \`\`\`\` \`\`\`\`js [foo](foo.md) \`\`\` [foo](foo.md) \`\`\`\` ~~~js [foo](foo.md) ~~~ ~~~js [foo](foo.md) \`\`\` [foo](foo.md) \`\`\` [foo](foo.md) ~~~ ", } `; exports[`replaceMarkdownLinks ignores links in inline code 1`] = ` { "brokenMarkdownLinks": [ { "contentPaths": { "contentPath": "docs", "contentPathLocalized": "i18n/docs-localized", }, "filePath": "docs/intro.md", "link": "foo.md", }, ], "newContent": " \`[foo](foo.md)\` ", } `; exports[`replaceMarkdownLinks preserves query/hash 1`] = ` { "brokenMarkdownLinks": [], "newContent": " [URL](/docs/file?foo=bar#baz) [URL](/docs/file#a) [URL](/docs/file?c) ", } `; exports[`replaceMarkdownLinks replaces Markdown links with spaces 1`] = ` { "brokenMarkdownLinks": [], "newContent": " [doc a](/docs/doc%20a) [doc a](</docs/doc%20a>) [doc b](/docs/my%20docs/doc%20b) [doc b](</docs/my%20docs/doc%20b>) [doc]: </docs/my%20docs/doc%20b> ", } `; exports[`replaceMarkdownLinks replaces links with same title as URL 1`] = ` { "brokenMarkdownLinks": [], "newContent": " [foo.md](/docs/foo) [./foo.md](/docs/foo) [foo.md](/docs/foo) [./foo.md](/docs/foo) ", } `; exports[`replaceMarkdownLinks replaces multiple links on same line 1`] = ` { "brokenMarkdownLinks": [], "newContent": " [a](/docs/a), [a](/docs/a), [b](/docs/b), [c](/docs/c) ", } `; exports[`replaceMarkdownLinks replaces reference style Markdown links 1`] = ` { "brokenMarkdownLinks": [], "newContent": " The following operations are defined for [URI]s: * [info]: Returns metadata about the resource, * [list]: Returns metadata about the resource's children (like getting the content of a local directory). [URI]: /docs/api/classes/uri [info]: /docs/api/classes/uri#info [list]: /docs/api/classes/uri#list ", } `; exports[`replaceMarkdownLinks replaces two links on the same line 1`] = ` { "brokenMarkdownLinks": [], "newContent": "[TypeScript](/programming-languages/typescript/) and [Go](/programming-languages/go/)", } `; exports[`replaceMarkdownLinks resolves absolute and relative links differently 1`] = ` { "brokenMarkdownLinks": [ { "contentPaths": { "contentPath": "docs", "contentPathLocalized": "i18n/docs-localized", }, "filePath": "docs/intro/intro.md", "link": "./api/classes/divine_uri.URI.md", }, { "contentPaths": { "contentPath": "docs", "contentPathLocalized": "i18n/docs-localized", }, "filePath": "docs/intro/intro.md", "link": "/another.md", }, ], "newContent": " [Relative link](/docs/another) [Relative link 2](/docs/api/classes/uri) [Relative link that should be absolute](./api/classes/divine_uri.URI.md) [Absolute link](/docs/api/classes/uri) [Absolute link from site dir](/docs/api/classes/uri) [Absolute link that should be relative](/another.md) [Relative link that acts as absolute](/docs/api/classes/uri) [Relative link that acts as relative](/docs/another) ", } `;
2,060
0
petrpan-code/facebook/docusaurus/packages/docusaurus-utils/src/__tests__
petrpan-code/facebook/docusaurus/packages/docusaurus-utils/src/__tests__/__snapshots__/markdownUtils.test.ts.snap
// Jest Snapshot v1, https://goo.gl/fbAQLP exports[`parseMarkdownString deletes only first heading 1`] = ` { "content": "# Markdown Title test test test # test bar # Markdown Title 2 ### Markdown Title h3", "contentTitle": "Markdown Title", "excerpt": "test test test # test bar", "frontMatter": {}, } `; exports[`parseMarkdownString deletes only first heading 2 1`] = ` { "content": "# test test test test test test test test test test # test bar # test2 ### test test3", "contentTitle": "test", "excerpt": "test test test test test test", "frontMatter": {}, } `; exports[`parseMarkdownString does not warn for duplicate title if markdown title is not at the top 1`] = ` { "content": "foo # Markdown Title", "contentTitle": undefined, "excerpt": "foo", "frontMatter": { "title": "Frontmatter title", }, } `; exports[`parseMarkdownString handles code blocks 1`] = ` { "content": "\`\`\`js code \`\`\` Content", "contentTitle": undefined, "excerpt": "Content", "frontMatter": {}, } `; exports[`parseMarkdownString handles code blocks 2`] = ` { "content": "\`\`\`\`js Foo \`\`\`diff code \`\`\` Bar \`\`\`\` Content", "contentTitle": undefined, "excerpt": "Content", "frontMatter": {}, } `; exports[`parseMarkdownString handles code blocks 3`] = ` { "content": "\`\`\`\`js Foo \`\`\`diff code \`\`\`\` Content", "contentTitle": undefined, "excerpt": "Content", "frontMatter": {}, } `; exports[`parseMarkdownString ignores markdown title if its not a first text 1`] = ` { "content": "foo # test", "contentTitle": undefined, "excerpt": "foo", "frontMatter": {}, } `; exports[`parseMarkdownString parse markdown with front matter 1`] = ` { "content": "Some text", "contentTitle": undefined, "excerpt": "Some text", "frontMatter": { "title": "Frontmatter title", }, } `; exports[`parseMarkdownString parses first heading as contentTitle 1`] = ` { "content": "# Markdown Title Some text", "contentTitle": "Markdown Title", "excerpt": "Some text", "frontMatter": {}, } `; exports[`parseMarkdownString parses front-matter and ignore h2 1`] = ` { "content": "## test", "contentTitle": undefined, "excerpt": "test", "frontMatter": { "title": "Frontmatter title", }, } `; exports[`parseMarkdownString parses title only 1`] = ` { "content": "# test", "contentTitle": "test", "excerpt": undefined, "frontMatter": {}, } `; exports[`parseMarkdownString parses title only alternate 1`] = ` { "content": "test ===", "contentTitle": "test", "excerpt": undefined, "frontMatter": {}, } `; exports[`parseMarkdownString reads front matter only 1`] = ` { "content": "", "contentTitle": undefined, "excerpt": undefined, "frontMatter": { "title": "test", }, } `; exports[`parseMarkdownString warns about duplicate titles (front matter + markdown alternate) 1`] = ` { "content": "Markdown Title alternate ================ Some text", "contentTitle": "Markdown Title alternate", "excerpt": "Some text", "frontMatter": { "title": "Frontmatter title", }, } `; exports[`parseMarkdownString warns about duplicate titles (front matter + markdown) 1`] = ` { "content": "# Markdown Title Some text", "contentTitle": "Markdown Title", "excerpt": "Some text", "frontMatter": { "title": "Frontmatter title", }, } `; exports[`parseMarkdownString warns about duplicate titles 1`] = ` { "content": "# test", "contentTitle": "test", "excerpt": undefined, "frontMatter": { "title": "Frontmatter title", }, } `;
2,092
0
petrpan-code/facebook/docusaurus/packages/docusaurus/src/client
petrpan-code/facebook/docusaurus/packages/docusaurus/src/client/__tests__/browserContext.test.tsx
/** * Copyright (c) Facebook, Inc. and its affiliates. * * This source code is licensed under the MIT license found in the * LICENSE file in the root directory of this source tree. * * @jest-environment jsdom */ // Jest doesn't allow pragma below other comments. https://github.com/facebook/jest/issues/12573 // eslint-disable-next-line header/header import React from 'react'; // TODO migrate to @testing-library/react when SSR rendering possible // See https://github.com/testing-library/react-testing-library/issues/1120 import {renderHook} from '@testing-library/react-hooks/server'; import {BrowserContextProvider} from '../browserContext'; import useIsBrowser from '../exports/useIsBrowser'; describe('BrowserContextProvider', () => { const {result, hydrate} = renderHook(() => useIsBrowser(), { wrapper: ({children}) => ( <BrowserContextProvider>{children}</BrowserContextProvider> ), }); it('has value false on first render', () => { expect(result.current).toBe(false); }); it('has value true on hydration', () => { hydrate(); expect(result.current).toBe(true); }); });
2,093
0
petrpan-code/facebook/docusaurus/packages/docusaurus/src/client
petrpan-code/facebook/docusaurus/packages/docusaurus/src/client/__tests__/docusaurusContext.test.tsx
/** * Copyright (c) Facebook, Inc. and its affiliates. * * This source code is licensed under the MIT license found in the * LICENSE file in the root directory of this source tree. * * @jest-environment jsdom */ // Jest doesn't allow pragma below other comments. https://github.com/facebook/jest/issues/12573 // eslint-disable-next-line header/header import React from 'react'; // TODO migrate to @testing-library/react when SSR rendering possible // See https://github.com/testing-library/react-testing-library/issues/1120 import {renderHook} from '@testing-library/react-hooks/server'; import {DocusaurusContextProvider} from '../docusaurusContext'; import useDocusaurusContext from '../exports/useDocusaurusContext'; // This test currently isn't quite useful because the @generated aliases point // to the empty modules. Maybe we can point that to fixtures in the future. describe('DocusaurusContextProvider', () => { const {result, hydrate} = renderHook(() => useDocusaurusContext(), { wrapper: ({children}) => ( <DocusaurusContextProvider>{children}</DocusaurusContextProvider> ), }); const value = result.current; it('returns right value', () => { expect(value).toMatchInlineSnapshot(` { "codeTranslations": {}, "globalData": {}, "i18n": {}, "siteConfig": {}, "siteMetadata": {}, } `); }); it('has reference-equal value on hydration', () => { hydrate(); expect(result.current).toBe(value); }); });
2,094
0
petrpan-code/facebook/docusaurus/packages/docusaurus/src/client
petrpan-code/facebook/docusaurus/packages/docusaurus/src/client/__tests__/flat.test.ts
/** * Copyright (c) Facebook, Inc. and its affiliates. * * This source code is licensed under the MIT license found in the * LICENSE file in the root directory of this source tree. */ import flat from '../flat'; describe('flat', () => { it('nested', () => { expect( flat({ foo: { bar: { baz: 'lorem ipsum', }, }, }), ).toEqual({ 'foo.bar.baz': 'lorem ipsum', }); expect( flat({ foo: { bar: 'baz', }, }), ).toEqual({ 'foo.bar': 'baz', }); }); it('primitives', () => { const primitives = { String: 'good morning', Number: 1234.99, Boolean: true, Date: new Date(), null: null, undefined, }; (Object.keys(primitives) as (keyof typeof primitives)[]).forEach((key) => { const value = primitives[key]; expect( flat({ foo: { bar: value as string, }, }), ).toEqual({ 'foo.bar': value, }); }); }); it('multiple keys', () => { expect( flat({ foo: { bar: 'baz', endi: 'lie', }, }), ).toEqual({ 'foo.bar': 'baz', 'foo.endi': 'lie', }); }); it('empty object', () => { expect( flat({ foo: { bar: {}, }, }), ).toEqual({ 'foo.bar': {}, }); }); it('array', () => { expect( flat({ hello: [{world: {again: 'foo'}}, {lorem: 'ipsum'}], }), ).toEqual({ 'hello.0.world.again': 'foo', 'hello.1.lorem': 'ipsum', }); }); });
2,095
0
petrpan-code/facebook/docusaurus/packages/docusaurus/src/client
petrpan-code/facebook/docusaurus/packages/docusaurus/src/client/__tests__/normalizeLocation.test.ts
/** * Copyright (c) Facebook, Inc. and its affiliates. * * This source code is licensed under the MIT license found in the * LICENSE file in the root directory of this source tree. */ import {jest} from '@jest/globals'; import normalizeLocation from '../normalizeLocation'; import type {Location} from 'history'; describe('normalizeLocation', () => { it('rewrites locations with index.html', () => { expect( normalizeLocation({ pathname: '/index.html', } as Location), ).toEqual({ pathname: '/', }); expect( normalizeLocation({ pathname: '/docs/introduction/index.html', search: '?search=foo', hash: '#features', } as Location), ).toEqual({ pathname: '/docs/introduction', search: '?search=foo', hash: '#features', }); expect( normalizeLocation({ pathname: '/index.html', search: '', hash: '#features', } as Location), ).toEqual({ pathname: '/', search: '', hash: '#features', }); }); it('removes html extension', () => { expect( normalizeLocation({ pathname: '/docs/installation.html', } as Location), ).toEqual({ pathname: '/docs/installation', }); expect( normalizeLocation({ pathname: '/docs/introduction/foo.html', search: '', hash: '#bar', } as Location), ).toEqual({ pathname: '/docs/introduction/foo', search: '', hash: '#bar', }); }); it('does not strip extension if the route location has one', () => { expect(normalizeLocation({pathname: '/page.html'} as Location)).toEqual({ pathname: '/page.html', }); }); it('leaves pathnames untouched', () => { const replaceMock = jest.spyOn(String.prototype, 'replace'); expect( normalizeLocation({ pathname: '/docs/introduction', search: '', hash: '#features', } as Location), ).toEqual({ pathname: '/docs/introduction', search: '', hash: '#features', }); // For the sake of testing memoization expect( normalizeLocation({ pathname: '/docs/introduction', search: '', hash: '#features', } as Location), ).toEqual({ pathname: '/docs/introduction', search: '', hash: '#features', }); expect(replaceMock).toHaveBeenCalledTimes(1); expect( normalizeLocation({ pathname: '/', } as Location), ).toEqual({ pathname: '/', }); }); });
2,096
0
petrpan-code/facebook/docusaurus/packages/docusaurus/src/client
petrpan-code/facebook/docusaurus/packages/docusaurus/src/client/__tests__/routeContext.test.tsx
/** * Copyright (c) Facebook, Inc. and its affiliates. * * This source code is licensed under the MIT license found in the * LICENSE file in the root directory of this source tree. */ import React from 'react'; // TODO migrate to @testing-library/react when SSR rendering possible // See https://github.com/testing-library/react-testing-library/issues/1120 import {renderHook} from '@testing-library/react-hooks/server'; import {RouteContextProvider} from '../routeContext'; import useRouteContext from '../exports/useRouteContext'; describe('RouteContextProvider', () => { it('creates root route context registered by plugin', () => { expect( renderHook(() => useRouteContext(), { wrapper: ({children}) => ( <RouteContextProvider value={{plugin: {id: 'test', name: 'test'}}}> {children} </RouteContextProvider> ), }).result.current, ).toEqual({plugin: {id: 'test', name: 'test'}}); }); it('throws if there is no route context at all', () => { expect( () => renderHook(() => useRouteContext(), { wrapper: ({children}) => ( <RouteContextProvider value={null}>{children}</RouteContextProvider> ), }).result.current, ).toThrowErrorMatchingInlineSnapshot( `"Unexpected: no Docusaurus route context found"`, ); }); it('throws if there is no parent context created by plugin', () => { expect( () => renderHook(() => useRouteContext(), { wrapper: ({children}) => ( <RouteContextProvider value={{data: {some: 'data'}}}> {children} </RouteContextProvider> ), }).result.current, ).toThrowErrorMatchingInlineSnapshot( `"Unexpected: Docusaurus topmost route context has no \`plugin\` attribute"`, ); }); it('merges route context created by parent', () => { expect( renderHook(() => useRouteContext(), { wrapper: ({children}) => ( <RouteContextProvider value={{plugin: {id: 'test', name: 'test'}, data: {some: 'data'}}}> <RouteContextProvider value={{data: {someMore: 'data'}}}> {children} </RouteContextProvider> </RouteContextProvider> ), }).result.current, ).toEqual({ data: {some: 'data', someMore: 'data'}, plugin: {id: 'test', name: 'test'}, }); }); it('never overrides the plugin attribute', () => { expect( renderHook(() => useRouteContext(), { wrapper: ({children}) => ( <RouteContextProvider value={{plugin: {id: 'test', name: 'test'}, data: {some: 'data'}}}> <RouteContextProvider value={{ plugin: {id: 'adversary', name: 'adversary'}, data: {someMore: 'data'}, }}> {children} </RouteContextProvider> </RouteContextProvider> ), }).result.current, ).toEqual({ data: {some: 'data', someMore: 'data'}, plugin: {id: 'test', name: 'test'}, }); }); });
2,117
0
petrpan-code/facebook/docusaurus/packages/docusaurus/src/client/exports
petrpan-code/facebook/docusaurus/packages/docusaurus/src/client/exports/__tests__/BrowserOnly.test.tsx
/** * Copyright (c) Facebook, Inc. and its affiliates. * * This source code is licensed under the MIT license found in the * LICENSE file in the root directory of this source tree. * * @jest-environment jsdom */ // Jest doesn't allow pragma below other comments. https://github.com/facebook/jest/issues/12573 // eslint-disable-next-line header/header import React from 'react'; import renderer from 'react-test-renderer'; import BrowserOnly from '../BrowserOnly'; import {Context} from '../../browserContext'; describe('<BrowserOnly>', () => { const originalEnv = process.env; beforeEach(() => { jest.resetModules(); process.env = {...originalEnv}; }); afterAll(() => { process.env = originalEnv; }); it('rejects react element children', () => { process.env.NODE_ENV = 'development'; expect(() => renderer .create( <Context.Provider value> <BrowserOnly> {/* @ts-expect-error test */} <span>{window.location.href}</span> </BrowserOnly> </Context.Provider>, ) .toJSON(), ).toThrowErrorMatchingInlineSnapshot(` "Docusaurus error: The children of <BrowserOnly> must be a "render function", e.g. <BrowserOnly>{() => <span>{window.location.href}</span>}</BrowserOnly>. Current type: React element" `); }); it('rejects string children', () => { process.env.NODE_ENV = 'development'; expect(() => { renderer.create( <Context.Provider value> {/* @ts-expect-error test */} <BrowserOnly> </BrowserOnly> </Context.Provider>, ); }).toThrowErrorMatchingInlineSnapshot(` "Docusaurus error: The children of <BrowserOnly> must be a "render function", e.g. <BrowserOnly>{() => <span>{window.location.href}</span>}</BrowserOnly>. Current type: string" `); }); it('accepts valid children', () => { expect( renderer .create( <Context.Provider value> <BrowserOnly fallback={<span>Loading</span>}> {() => <span>{window.location.href}</span>} </BrowserOnly> </Context.Provider>, ) .toJSON(), ).toMatchInlineSnapshot(` <span> https://docusaurus.io/ </span> `); }); it('returns fallback when not in browser', () => { expect( renderer .create( <Context.Provider value={false}> <BrowserOnly fallback={<span>Loading</span>}> {() => <span>{window.location.href}</span>} </BrowserOnly> </Context.Provider>, ) .toJSON(), ).toMatchInlineSnapshot(` <span> Loading </span> `); }); it('gracefully falls back', () => { expect( renderer .create( <Context.Provider value={false}> <BrowserOnly> {() => <span>{window.location.href}</span>} </BrowserOnly> </Context.Provider>, ) .toJSON(), ).toMatchInlineSnapshot(`null`); }); });
2,118
0
petrpan-code/facebook/docusaurus/packages/docusaurus/src/client/exports
petrpan-code/facebook/docusaurus/packages/docusaurus/src/client/exports/__tests__/Head.test.tsx
/** * Copyright (c) Facebook, Inc. and its affiliates. * * This source code is licensed under the MIT license found in the * LICENSE file in the root directory of this source tree. */ import React from 'react'; import {type FilledContext, HelmetProvider} from 'react-helmet-async'; import renderer from 'react-test-renderer'; import Head from '../Head'; describe('Head', () => { it('does exactly what Helmet does', () => { const context = {}; expect( renderer .create( <HelmetProvider context={context}> <Head> <meta property="og:type" content="article" /> <meta property="og:description" content="some description" /> </Head> <Head> <meta property="og:description" content="some description overridden" /> </Head> <Head> <meta property="duplicated?" content="this property is duplicated" /> <meta property="duplicated?" content="another one" /> </Head> <div>Content</div> </HelmetProvider>, ) .toJSON(), ).toMatchSnapshot(); expect((context as FilledContext).helmet).toMatchSnapshot(); }); });
2,119
0
petrpan-code/facebook/docusaurus/packages/docusaurus/src/client/exports
petrpan-code/facebook/docusaurus/packages/docusaurus/src/client/exports/__tests__/Interpolate.test.tsx
/** * Copyright (c) Facebook, Inc. and its affiliates. * * This source code is licensed under the MIT license found in the * LICENSE file in the root directory of this source tree. */ import React from 'react'; import renderer from 'react-test-renderer'; import Interpolate, {interpolate} from '../Interpolate'; describe('interpolate', () => { it('without placeholders', () => { const text = 'Hello how are you?'; expect(interpolate(text)).toEqual(text); }); it('placeholders with string values', () => { const text = 'Hello {name} how are you {day}?'; const values = {name: 'Sébastien', day: 'today'}; expect(interpolate(text, values)).toMatchInlineSnapshot( `"Hello Sébastien how are you today?"`, ); }); it('placeholders with string values 2', () => { const text = '{number} {string} {object} {array}'; const values = { number: 42, string: 'Hello', object: {hello: 'world'}, array: ['Hello'], }; expect(interpolate(text, values)).toMatchInlineSnapshot( `"42 Hello [object Object] Hello"`, ); }); it('placeholders with falsy values', () => { const text = '{number} {string} {boolean}'; const values = { number: 0, string: '', boolean: false, }; // Do we need to improve the JS type -> String conversion logic here? expect(interpolate(text, values)).toMatchInlineSnapshot(`"0 false"`); }); it('placeholders with string values mismatch', () => { // Should we emit warnings in such case? const text = 'Hello {name} how are you {unprovidedValue}?'; const values = {name: 'Sébastien', extraValue: 'today'}; expect(interpolate(text, values)).toMatchInlineSnapshot( `"Hello Sébastien how are you {unprovidedValue}?"`, ); }); it('placeholders with values not provided', () => { // Should we emit warnings in such case? const text = 'Hello {name} how are you {day}?'; expect(interpolate(text)).toEqual(text); expect(interpolate(text, {})).toEqual(text); }); it('placeholders with JSX values', () => { const text = 'Hello {name} how are you {day}?'; const values = {name: <b>Sébastien</b>, day: <span>today</span>}; expect(interpolate(text, values)).toMatchSnapshot(); }); it('placeholders with mixed vales', () => { const text = 'Hello {name} how are you {day}?'; const values = {name: 'Sébastien', day: <span>today</span>}; expect(interpolate(text, values)).toMatchSnapshot(); }); it('acceptance test', () => { const text = 'Hello {name} how are you {day}? Another {unprovidedValue}!'; const values = { name: 'Sébastien', day: <span>today</span>, extraUselessValue1: <div>test</div>, extraUselessValue2: 'hi', }; expect(interpolate(text, values)).toMatchSnapshot(); }); }); describe('<Interpolate>', () => { it('without placeholders', () => { const text = 'Hello how are you?'; expect(renderer.create(<Interpolate>{text}</Interpolate>).toJSON()).toEqual( text, ); }); it('placeholders with string values', () => { const text = 'Hello {name} how are you {day}?'; const values = {name: 'Sébastien', day: 'today'}; expect( renderer .create(<Interpolate values={values}>{text}</Interpolate>) .toJSON(), ).toMatchInlineSnapshot(`"Hello Sébastien how are you today?"`); }); it('acceptance test', () => { const text = 'Hello {name} how are you {day}? Another {unprovidedValue}!'; const values = { name: 'Sébastien', day: <span>today</span>, extraUselessValue1: <div>test</div>, extraUselessValue2: 'hi', }; expect( renderer .create(<Interpolate values={values}>{text}</Interpolate>) .toJSON(), ).toMatchSnapshot(); }); it('rejects when children is not string', () => { expect(() => renderer.create( <Interpolate> <span>aaa</span> </Interpolate>, ), ).toThrowErrorMatchingInlineSnapshot( `"The Docusaurus <Interpolate> component only accept simple string values. Received: React element"`, ); expect(() => renderer.create(<Interpolate>{null}</Interpolate>), ).toThrowErrorMatchingInlineSnapshot( `"The Docusaurus <Interpolate> component only accept simple string values. Received: object"`, ); }); });
2,120
0
petrpan-code/facebook/docusaurus/packages/docusaurus/src/client/exports
petrpan-code/facebook/docusaurus/packages/docusaurus/src/client/exports/__tests__/Translate.test.tsx
/** * Copyright (c) Facebook, Inc. and its affiliates. * * This source code is licensed under the MIT license found in the * LICENSE file in the root directory of this source tree. */ import React from 'react'; import renderer from 'react-test-renderer'; import Translate, {translate} from '../Translate'; describe('translate', () => { it('accepts id and uses it as fallback', () => { expect(translate({id: 'some-id'})).toBe('some-id'); }); it('accepts message and uses it as fallback', () => { expect(translate({message: 'some-message'})).toBe('some-message'); }); it('accepts id+message and uses message as fallback', () => { expect(translate({id: 'some-id', message: 'some-message'})).toBe( 'some-message', ); }); it('rejects when no id or message', () => { // TODO tests are not resolving type defs correctly. We need to include test // files in a tsconfig file // @ts-expect-error: TS should protect when both id/message are missing expect(() => translate({})).toThrowErrorMatchingInlineSnapshot( `"Docusaurus translation declarations must have at least a translation id or a default translation message"`, ); }); }); describe('<Translate>', () => { it('accepts id and uses it as fallback', () => { expect(renderer.create(<Translate id="some-id" />).toJSON()).toBe( 'some-id', ); }); it('accepts message and uses it as fallback', () => { expect(renderer.create(<Translate>some-message</Translate>).toJSON()).toBe( 'some-message', ); }); it('accepts id+message and uses message as fallback', () => { expect( renderer .create(<Translate id="some-id">some-message</Translate>) .toJSON(), ).toBe('some-message'); }); it('rejects when no id or message', () => { expect(() => // @ts-expect-error: TS should protect when both id/message are missing renderer.create(<Translate />), ).toThrowErrorMatchingInlineSnapshot( `"Docusaurus translation declarations must have at least a translation id or a default translation message"`, ); }); it('rejects when children is not a string', () => { expect(() => renderer.create( // eslint-disable-next-line @docusaurus/string-literal-i18n-messages <Translate id="foo"> {/* @ts-expect-error: for test */} <span>aaa</span> </Translate>, ), ).toThrowErrorMatchingInlineSnapshot( `"The Docusaurus <Translate> component only accept simple string values"`, ); }); });
2,121
0
petrpan-code/facebook/docusaurus/packages/docusaurus/src/client/exports
petrpan-code/facebook/docusaurus/packages/docusaurus/src/client/exports/__tests__/isInternalUrl.test.ts
/** * Copyright (c) Facebook, Inc. and its affiliates. * * This source code is licensed under the MIT license found in the * LICENSE file in the root directory of this source tree. */ import isInternalUrl from '../isInternalUrl'; describe('isInternalUrl', () => { it('returns true for empty links', () => { expect(isInternalUrl('')).toBeTruthy(); }); it('returns true for root relative links', () => { expect(isInternalUrl('/foo/bar')).toBeTruthy(); }); it('returns true for relative links', () => { expect(isInternalUrl('foo/bar')).toBeTruthy(); }); it('returns false for HTTP links', () => { expect(isInternalUrl('http://foo.com')).toBeFalsy(); }); it('returns false for HTTPS links', () => { expect(isInternalUrl('https://foo.com')).toBeFalsy(); }); it('returns false for whatever protocol links', () => { expect(isInternalUrl('//foo.com')).toBeFalsy(); }); it('returns false for telephone links', () => { expect(isInternalUrl('tel:+1234567890')).toBeFalsy(); }); it('returns false for mailto links', () => { expect(isInternalUrl('mailto:[email protected]')).toBeFalsy(); }); it('returns false for undefined links', () => { expect(isInternalUrl(undefined)).toBeFalsy(); }); });
2,122
0
petrpan-code/facebook/docusaurus/packages/docusaurus/src/client/exports
petrpan-code/facebook/docusaurus/packages/docusaurus/src/client/exports/__tests__/useBaseUrl.test.tsx
/** * Copyright (c) Facebook, Inc. and its affiliates. * * This source code is licensed under the MIT license found in the * LICENSE file in the root directory of this source tree. */ import React from 'react'; import {renderHook} from '@testing-library/react-hooks'; import useBaseUrl, {useBaseUrlUtils} from '../useBaseUrl'; import {Context} from '../../docusaurusContext'; import type {DocusaurusContext} from '@docusaurus/types'; import type {BaseUrlOptions} from '@docusaurus/useBaseUrl'; const forcePrepend = {forcePrependBaseUrl: true}; describe('useBaseUrl', () => { const createUseBaseUrlMock = (context: DocusaurusContext) => (url: string, options?: BaseUrlOptions) => renderHook(() => useBaseUrl(url, options), { wrapper: ({children}) => ( <Context.Provider value={context}>{children}</Context.Provider> ), }).result.current; it('works with empty base URL', () => { const mockUseBaseUrl = createUseBaseUrlMock({ siteConfig: { baseUrl: '/', url: 'https://docusaurus.io', }, } as DocusaurusContext); expect(mockUseBaseUrl('hello')).toBe('/hello'); expect(mockUseBaseUrl('/hello')).toBe('/hello'); expect(mockUseBaseUrl('hello/')).toBe('/hello/'); expect(mockUseBaseUrl('/hello/')).toBe('/hello/'); expect(mockUseBaseUrl('hello/foo')).toBe('/hello/foo'); expect(mockUseBaseUrl('/hello/foo')).toBe('/hello/foo'); expect(mockUseBaseUrl('hello/foo/')).toBe('/hello/foo/'); expect(mockUseBaseUrl('/hello/foo/')).toBe('/hello/foo/'); expect(mockUseBaseUrl('https://github.com')).toBe('https://github.com'); expect(mockUseBaseUrl('//reactjs.org')).toBe('//reactjs.org'); expect(mockUseBaseUrl('//reactjs.org', forcePrepend)).toBe('//reactjs.org'); expect(mockUseBaseUrl('https://site.com', forcePrepend)).toBe( 'https://site.com', ); expect(mockUseBaseUrl('/hello/foo', {absolute: true})).toBe( 'https://docusaurus.io/hello/foo', ); expect(mockUseBaseUrl('#hello')).toBe('#hello'); }); it('works with non-empty base URL', () => { const mockUseBaseUrl = createUseBaseUrlMock({ siteConfig: { baseUrl: '/docusaurus/', url: 'https://docusaurus.io', }, } as DocusaurusContext); expect(mockUseBaseUrl('')).toBe(''); expect(mockUseBaseUrl('hello')).toBe('/docusaurus/hello'); expect(mockUseBaseUrl('/hello')).toBe('/docusaurus/hello'); expect(mockUseBaseUrl('hello/')).toBe('/docusaurus/hello/'); expect(mockUseBaseUrl('/hello/')).toBe('/docusaurus/hello/'); expect(mockUseBaseUrl('hello/foo')).toBe('/docusaurus/hello/foo'); expect(mockUseBaseUrl('/hello/foo')).toBe('/docusaurus/hello/foo'); expect(mockUseBaseUrl('hello/foo/')).toBe('/docusaurus/hello/foo/'); expect(mockUseBaseUrl('/hello/foo/')).toBe('/docusaurus/hello/foo/'); expect(mockUseBaseUrl('https://github.com')).toBe('https://github.com'); expect(mockUseBaseUrl('//reactjs.org')).toBe('//reactjs.org'); expect(mockUseBaseUrl('//reactjs.org', forcePrepend)).toBe('//reactjs.org'); expect(mockUseBaseUrl('/hello', forcePrepend)).toBe('/docusaurus/hello'); expect(mockUseBaseUrl('https://site.com', forcePrepend)).toBe( 'https://site.com', ); expect(mockUseBaseUrl('/hello/foo', {absolute: true})).toBe( 'https://docusaurus.io/docusaurus/hello/foo', ); expect(mockUseBaseUrl('/docusaurus')).toBe('/docusaurus/'); expect(mockUseBaseUrl('/docusaurus/')).toBe('/docusaurus/'); expect(mockUseBaseUrl('/docusaurus/hello')).toBe('/docusaurus/hello'); expect(mockUseBaseUrl('#hello')).toBe('#hello'); }); }); describe('useBaseUrlUtils().withBaseUrl()', () => { const mockUseBaseUrlUtils = (context: DocusaurusContext) => renderHook(() => useBaseUrlUtils(), { wrapper: ({children}) => ( <Context.Provider value={context}>{children}</Context.Provider> ), }).result.current; it('empty base URL', () => { const {withBaseUrl} = mockUseBaseUrlUtils({ siteConfig: { baseUrl: '/', url: 'https://docusaurus.io', }, } as DocusaurusContext); expect(withBaseUrl('hello')).toBe('/hello'); expect(withBaseUrl('/hello')).toBe('/hello'); expect(withBaseUrl('hello/')).toBe('/hello/'); expect(withBaseUrl('/hello/')).toBe('/hello/'); expect(withBaseUrl('hello/foo')).toBe('/hello/foo'); expect(withBaseUrl('/hello/foo')).toBe('/hello/foo'); expect(withBaseUrl('hello/foo/')).toBe('/hello/foo/'); expect(withBaseUrl('/hello/foo/')).toBe('/hello/foo/'); expect(withBaseUrl('https://github.com')).toBe('https://github.com'); expect(withBaseUrl('//reactjs.org')).toBe('//reactjs.org'); expect(withBaseUrl('//reactjs.org', forcePrepend)).toBe('//reactjs.org'); expect(withBaseUrl('https://site.com', forcePrepend)).toBe( 'https://site.com', ); expect(withBaseUrl('/hello/foo', {absolute: true})).toBe( 'https://docusaurus.io/hello/foo', ); expect(withBaseUrl('#hello')).toBe('#hello'); }); it('non-empty base URL', () => { const {withBaseUrl} = mockUseBaseUrlUtils({ siteConfig: { baseUrl: '/docusaurus/', url: 'https://docusaurus.io', }, } as DocusaurusContext); expect(withBaseUrl('hello')).toBe('/docusaurus/hello'); expect(withBaseUrl('/hello')).toBe('/docusaurus/hello'); expect(withBaseUrl('hello/')).toBe('/docusaurus/hello/'); expect(withBaseUrl('/hello/')).toBe('/docusaurus/hello/'); expect(withBaseUrl('hello/foo')).toBe('/docusaurus/hello/foo'); expect(withBaseUrl('/hello/foo')).toBe('/docusaurus/hello/foo'); expect(withBaseUrl('hello/foo/')).toBe('/docusaurus/hello/foo/'); expect(withBaseUrl('/hello/foo/')).toBe('/docusaurus/hello/foo/'); expect(withBaseUrl('https://github.com')).toBe('https://github.com'); expect(withBaseUrl('//reactjs.org')).toBe('//reactjs.org'); expect(withBaseUrl('//reactjs.org', forcePrepend)).toBe('//reactjs.org'); expect(withBaseUrl('https://site.com', forcePrepend)).toBe( 'https://site.com', ); expect(withBaseUrl('/hello/foo', {absolute: true})).toBe( 'https://docusaurus.io/docusaurus/hello/foo', ); expect(withBaseUrl('/docusaurus')).toBe('/docusaurus/'); expect(withBaseUrl('/docusaurus/')).toBe('/docusaurus/'); expect(withBaseUrl('/docusaurus/hello')).toBe('/docusaurus/hello'); expect(withBaseUrl('#hello')).toBe('#hello'); }); });
2,123
0
petrpan-code/facebook/docusaurus/packages/docusaurus/src/client/exports
petrpan-code/facebook/docusaurus/packages/docusaurus/src/client/exports/__tests__/useGlobalData.test.tsx
/** * Copyright (c) Facebook, Inc. and its affiliates. * * This source code is licensed under the MIT license found in the * LICENSE file in the root directory of this source tree. */ import React from 'react'; import {renderHook} from '@testing-library/react-hooks'; import useGlobalData, { useAllPluginInstancesData, usePluginData, } from '../useGlobalData'; import {Context} from '../../docusaurusContext'; import type {DocusaurusContext} from '@docusaurus/types'; describe('useGlobalData', () => { it('returns global data from context', () => { expect( renderHook(() => useGlobalData(), { wrapper: ({children}) => ( <Context.Provider value={{globalData: {foo: 'bar'}} as unknown as DocusaurusContext}> {children} </Context.Provider> ), }).result.current, ).toEqual({foo: 'bar'}); }); }); describe('useAllPluginInstancesData', () => { it('returns plugin data namespace', () => { expect( renderHook(() => useAllPluginInstancesData('foo'), { wrapper: ({children}) => ( <Context.Provider value={ { globalData: {foo: {default: 'default', bar: 'bar'}}, } as unknown as DocusaurusContext }> {children} </Context.Provider> ), }).result.current, ).toEqual({default: 'default', bar: 'bar'}); }); it('throws when plugin data not found', () => { expect( () => renderHook(() => useAllPluginInstancesData('bar', {failfast: true}), { wrapper: ({children}) => ( <Context.Provider value={ { globalData: {foo: {default: 'default', bar: 'bar'}}, } as unknown as DocusaurusContext }> {children} </Context.Provider> ), }).result.current, ).toThrowErrorMatchingInlineSnapshot( `"Docusaurus plugin global data not found for "bar" plugin."`, ); }); }); describe('usePluginData', () => { it('returns plugin instance data', () => { expect( renderHook(() => usePluginData('foo', 'bar'), { wrapper: ({children}) => ( <Context.Provider value={ { globalData: {foo: {default: 'default', bar: 'bar'}}, } as unknown as DocusaurusContext }> {children} </Context.Provider> ), }).result.current, ).toBe('bar'); }); it('defaults to default ID', () => { expect( renderHook(() => usePluginData('foo'), { wrapper: ({children}) => ( <Context.Provider value={ { globalData: {foo: {default: 'default', bar: 'bar'}}, } as unknown as DocusaurusContext }> {children} </Context.Provider> ), }).result.current, ).toBe('default'); }); it('throws when plugin instance data not found', () => { expect( () => renderHook(() => usePluginData('foo', 'baz', {failfast: true}), { wrapper: ({children}) => ( <Context.Provider value={ { globalData: {foo: {default: 'default', bar: 'bar'}}, } as unknown as DocusaurusContext }> {children} </Context.Provider> ), }).result.current, ).toThrowErrorMatchingInlineSnapshot( `"Docusaurus plugin global data not found for "foo" plugin with id "baz"."`, ); }); });
2,124
0
petrpan-code/facebook/docusaurus/packages/docusaurus/src/client/exports
petrpan-code/facebook/docusaurus/packages/docusaurus/src/client/exports/__tests__/useRouteContext.test.tsx
/** * Copyright (c) Facebook, Inc. and its affiliates. * * This source code is licensed under the MIT license found in the * LICENSE file in the root directory of this source tree. */ import React from 'react'; // TODO migrate to @testing-library/react when SSR rendering possible // See https://github.com/testing-library/react-testing-library/issues/1120 import {renderHook} from '@testing-library/react-hooks/server'; import {RouteContextProvider} from '../../routeContext'; import useRouteContext from '../useRouteContext'; describe('useRouteContext', () => { it('throws when there is no route context at all', () => { expect( () => renderHook(() => useRouteContext()).result.current, ).toThrowErrorMatchingInlineSnapshot( `"Unexpected: no Docusaurus route context found"`, ); }); it('returns merged route contexts', () => { expect( renderHook(() => useRouteContext(), { wrapper: ({children}) => ( <RouteContextProvider value={{plugin: {id: 'test', name: 'test'}, data: {some: 'data'}}}> <RouteContextProvider value={{data: {someMore: 'data'}}}> {children} </RouteContextProvider> </RouteContextProvider> ), }).result.current, ).toEqual({ data: {some: 'data', someMore: 'data'}, plugin: {id: 'test', name: 'test'}, }); }); });
2,125
0
petrpan-code/facebook/docusaurus/packages/docusaurus/src/client/exports/__tests__
petrpan-code/facebook/docusaurus/packages/docusaurus/src/client/exports/__tests__/__snapshots__/Head.test.tsx.snap
// Jest Snapshot v1, https://goo.gl/fbAQLP exports[`Head does exactly what Helmet does 1`] = ` <div> Content </div> `; exports[`Head does exactly what Helmet does 2`] = ` <html> <head> <meta content="article" data-rh={true} property="og:type" /> <meta content="some description overridden" data-rh={true} property="og:description" /> <meta content="this property is duplicated" data-rh={true} property="duplicated?" /> <meta content="another one" data-rh={true} property="duplicated?" /> <title data-rh={true} > </title> </head> <body /> </html> `;
2,126
0
petrpan-code/facebook/docusaurus/packages/docusaurus/src/client/exports/__tests__
petrpan-code/facebook/docusaurus/packages/docusaurus/src/client/exports/__tests__/__snapshots__/Interpolate.test.tsx.snap
// Jest Snapshot v1, https://goo.gl/fbAQLP exports[`<Interpolate> acceptance test 1`] = ` [ "Hello ", "Sébastien", " how are you ", <span> today </span>, "? Another ", "{unprovidedValue}", "!", ] `; exports[`interpolate acceptance test 1`] = ` [ "Hello ", "Sébastien", " how are you ", <span> today </span>, "? Another ", "{unprovidedValue}", "!", ] `; exports[`interpolate placeholders with JSX values 1`] = ` [ "Hello ", <b> Sébastien </b>, " how are you ", <span> today </span>, "?", ] `; exports[`interpolate placeholders with mixed vales 1`] = ` [ "Hello ", "Sébastien", " how are you ", <span> today </span>, "?", ] `;
2,150
0
petrpan-code/facebook/docusaurus/packages/docusaurus/src/commands/swizzle
petrpan-code/facebook/docusaurus/packages/docusaurus/src/commands/swizzle/__tests__/actions.test.ts
/** * Copyright (c) Facebook, Inc. and its affiliates. * * This source code is licensed under the MIT license found in the * LICENSE file in the root directory of this source tree. */ import path from 'path'; import fs from 'fs-extra'; import tree from 'tree-node-cli'; import {posixPath} from '@docusaurus/utils'; import {eject, wrap} from '../actions'; import {ThemePath, Components, createTempSiteDir} from './testUtils'; import type {SwizzleAction} from '@docusaurus/types'; // Use relative paths and sort files for tests function stableCreatedFiles( siteThemePath: string, createdFiles: string[], ): string[] { return createdFiles .map((file) => posixPath(path.relative(siteThemePath, file))) .sort(); } describe('eject', () => { async function testEject( action: SwizzleAction, componentName: string, {typescript}: {typescript: boolean} = {typescript: true}, ) { const siteDir = await createTempSiteDir(); const siteThemePath = path.join(siteDir, 'src/theme'); const result = await eject({ siteDir, componentName, themePath: ThemePath, typescript, }); return { siteDir, siteThemePath, createdFiles: stableCreatedFiles(siteThemePath, result.createdFiles), tree: tree(siteThemePath), }; } it(`eject ${Components.FirstLevelComponent}`, async () => { const result = await testEject('eject', Components.FirstLevelComponent); expect(result.createdFiles).toEqual([ 'FirstLevelComponent.css', 'FirstLevelComponent.tsx', ]); expect(result.tree).toMatchInlineSnapshot(` "theme ├── FirstLevelComponent.css └── FirstLevelComponent.tsx" `); }); it(`eject ${Components.JsComponent} JS`, async () => { const result = await testEject('eject', Components.JsComponent, { typescript: false, }); expect(result.createdFiles).toEqual([ 'JsComponent/index.css', 'JsComponent/index.js', ]); expect(result.tree).toMatchInlineSnapshot(` "theme └── JsComponent ├── index.css └── index.js" `); }); it(`eject ${Components.ComponentInSubFolder}`, async () => { const result = await testEject('eject', Components.ComponentInSubFolder); expect(result.createdFiles).toEqual([ 'ComponentInFolder/ComponentInSubFolder/index.css', 'ComponentInFolder/ComponentInSubFolder/index.tsx', 'ComponentInFolder/ComponentInSubFolder/styles.css', 'ComponentInFolder/ComponentInSubFolder/styles.module.css', ]); expect(result.tree).toMatchInlineSnapshot(` "theme └── ComponentInFolder └── ComponentInSubFolder ├── index.css ├── index.tsx ├── styles.css └── styles.module.css" `); }); it(`eject ${Components.Sibling}`, async () => { const result = await testEject('eject', Components.Sibling); expect(result.createdFiles).toEqual([ 'ComponentInFolder/Sibling.css', 'ComponentInFolder/Sibling.tsx', ]); expect(result.tree).toMatchInlineSnapshot(` "theme └── ComponentInFolder ├── Sibling.css └── Sibling.tsx" `); }); it(`eject ${Components.ComponentInFolder}`, async () => { const result = await testEject('eject', Components.ComponentInFolder); expect(result.createdFiles).toEqual([ 'ComponentInFolder/ComponentInSubFolder/index.css', 'ComponentInFolder/ComponentInSubFolder/index.tsx', 'ComponentInFolder/ComponentInSubFolder/styles.css', 'ComponentInFolder/ComponentInSubFolder/styles.module.css', 'ComponentInFolder/Sibling.css', 'ComponentInFolder/Sibling.tsx', 'ComponentInFolder/index.css', 'ComponentInFolder/index.tsx', ]); expect(result.tree).toMatchInlineSnapshot(` "theme └── ComponentInFolder ├── ComponentInSubFolder │ ├── index.css │ ├── index.tsx │ ├── styles.css │ └── styles.module.css ├── Sibling.css ├── Sibling.tsx ├── index.css └── index.tsx" `); }); }); describe('wrap', () => { async function testWrap( action: SwizzleAction, componentName: string, {typescript}: {typescript: boolean} = {typescript: false}, ) { const siteDir = await createTempSiteDir(); const siteThemePath = path.join(siteDir, 'src/theme'); const result = await wrap({ siteDir, componentName, themePath: ThemePath, typescript, }); return { siteDir, siteThemePath, createdFiles: stableCreatedFiles(siteThemePath, result.createdFiles), firstFileContent: () => fs.readFile(result.createdFiles[0]!, 'utf8'), tree: tree(siteThemePath), }; } describe('JavaScript', () => { async function doWrap(componentName: string) { return testWrap('wrap', componentName, { typescript: false, }); } it(`wrap ${Components.FirstLevelComponent}`, async () => { const result = await doWrap(Components.FirstLevelComponent); expect(result.createdFiles).toEqual(['FirstLevelComponent.js']); expect(result.tree).toMatchInlineSnapshot(` "theme └── FirstLevelComponent.js" `); await expect(result.firstFileContent()).resolves.toMatchSnapshot(); }); it(`wrap ${Components.ComponentInSubFolder}`, async () => { const result = await doWrap(Components.ComponentInSubFolder); expect(result.createdFiles).toEqual([ 'ComponentInFolder/ComponentInSubFolder/index.js', ]); expect(result.tree).toMatchInlineSnapshot(` "theme └── ComponentInFolder └── ComponentInSubFolder └── index.js" `); await expect(result.firstFileContent()).resolves.toMatchSnapshot(); }); it(`wrap ${Components.ComponentInFolder}`, async () => { const result = await doWrap(Components.ComponentInFolder); expect(result.createdFiles).toEqual(['ComponentInFolder/index.js']); expect(result.tree).toMatchInlineSnapshot(` "theme └── ComponentInFolder └── index.js" `); await expect(result.firstFileContent()).resolves.toMatchSnapshot(); }); }); describe('TypeScript', () => { async function doWrap(componentName: string) { return testWrap('wrap', componentName, { typescript: true, }); } it(`wrap ${Components.FirstLevelComponent}`, async () => { const result = await doWrap(Components.FirstLevelComponent); expect(result.createdFiles).toEqual(['FirstLevelComponent.tsx']); expect(result.tree).toMatchInlineSnapshot(` "theme └── FirstLevelComponent.tsx" `); await expect(result.firstFileContent()).resolves.toMatchSnapshot(); }); it(`wrap ${Components.ComponentInSubFolder}`, async () => { const result = await doWrap(Components.ComponentInSubFolder); expect(result.createdFiles).toEqual([ 'ComponentInFolder/ComponentInSubFolder/index.tsx', ]); expect(result.tree).toMatchInlineSnapshot(` "theme └── ComponentInFolder └── ComponentInSubFolder └── index.tsx" `); await expect(result.firstFileContent()).resolves.toMatchSnapshot(); }); it(`wrap ${Components.ComponentInFolder}`, async () => { const result = await doWrap(Components.ComponentInFolder); expect(result.createdFiles).toEqual(['ComponentInFolder/index.tsx']); expect(result.tree).toMatchInlineSnapshot(` "theme └── ComponentInFolder └── index.tsx" `); await expect(result.firstFileContent()).resolves.toMatchSnapshot(); }); }); });
2,151
0
petrpan-code/facebook/docusaurus/packages/docusaurus/src/commands/swizzle
petrpan-code/facebook/docusaurus/packages/docusaurus/src/commands/swizzle/__tests__/components.test.ts
/** * Copyright (c) Facebook, Inc. and its affiliates. * * This source code is licensed under the MIT license found in the * LICENSE file in the root directory of this source tree. */ import path from 'path'; import {getThemeComponents, readComponentNames} from '../components'; import {Components} from './testUtils'; import type {SwizzleConfig} from '@docusaurus/types'; const FixtureThemePath = path.join(__dirname, '__fixtures__/theme'); describe('readComponentNames', () => { it('read theme', async () => { await expect(readComponentNames(FixtureThemePath)).resolves.toEqual([ Components.ComponentInFolder, Components.ComponentInSubFolder, Components.Sibling, Components.FirstLevelComponent, Components.JsComponent, Components.NoIndexComp1, Components.NoIndexComp2, Components.NoIndexSubComp, ]); }); }); describe('getThemeComponents', () => { const themeName = 'myThemeName'; const themePath = FixtureThemePath; const swizzleConfig: SwizzleConfig = { components: { [Components.ComponentInSubFolder]: { actions: { eject: 'safe', wrap: 'unsafe', }, }, [Components.ComponentInFolder]: { actions: { wrap: 'safe', eject: 'unsafe', }, description: 'ComponentInFolder description', }, }, }; it('read name', async () => { const themeComponents = await getThemeComponents({ themeName, themePath, swizzleConfig, }); expect(themeComponents.themeName).toEqual(themeName); }); it('read all', async () => { const themeComponents = await getThemeComponents({ themeName, themePath, swizzleConfig, }); expect(themeComponents.all).toEqual([ // Order matters! Components.ComponentInFolder, Components.ComponentInSubFolder, Components.Sibling, Components.FirstLevelComponent, Components.JsComponent, Components.NoIndex, Components.NoIndexComp1, Components.NoIndexComp2, Components.NoIndexSub, Components.NoIndexSubComp, ]); }); it('getConfig', async () => { const themeComponents = await getThemeComponents({ themeName, themePath, swizzleConfig, }); expect(themeComponents.getConfig(Components.ComponentInFolder)) .toMatchInlineSnapshot(` { "actions": { "eject": "unsafe", "wrap": "safe", }, "description": "ComponentInFolder description", } `); expect(themeComponents.getConfig(Components.ComponentInSubFolder)) .toMatchInlineSnapshot(` { "actions": { "eject": "safe", "wrap": "unsafe", }, } `); expect(themeComponents.getConfig(Components.FirstLevelComponent)) .toMatchInlineSnapshot(` { "actions": { "eject": "unsafe", "wrap": "unsafe", }, "description": "N/A", } `); expect(() => themeComponents.getConfig('DoesNotExistComp'), ).toThrowErrorMatchingInlineSnapshot( `"Can't get component config: component doesn't exist: DoesNotExistComp"`, ); }); it('getDescription', async () => { const themeComponents = await getThemeComponents({ themeName, themePath, swizzleConfig, }); expect(themeComponents.getDescription(Components.ComponentInFolder)).toBe( 'ComponentInFolder description', ); expect( themeComponents.getDescription(Components.ComponentInSubFolder), ).toBe('N/A'); expect(themeComponents.getDescription(Components.FirstLevelComponent)).toBe( 'N/A', ); }); it('getActionStatus', async () => { const themeComponents = await getThemeComponents({ themeName, themePath, swizzleConfig, }); expect( themeComponents.getActionStatus(Components.ComponentInFolder, 'wrap'), ).toBe('safe'); expect( themeComponents.getActionStatus(Components.ComponentInFolder, 'eject'), ).toBe('unsafe'); expect( themeComponents.getActionStatus(Components.ComponentInSubFolder, 'wrap'), ).toBe('unsafe'); expect( themeComponents.getActionStatus(Components.ComponentInSubFolder, 'eject'), ).toBe('safe'); expect( themeComponents.getActionStatus(Components.FirstLevelComponent, 'wrap'), ).toBe('unsafe'); expect( themeComponents.getActionStatus(Components.FirstLevelComponent, 'eject'), ).toBe('unsafe'); expect( themeComponents.getActionStatus(Components.NoIndexComp1, 'wrap'), ).toBe('unsafe'); expect( themeComponents.getActionStatus(Components.NoIndexComp1, 'eject'), ).toBe('unsafe'); expect( themeComponents.getActionStatus(Components.NoIndexComp2, 'wrap'), ).toBe('unsafe'); expect( themeComponents.getActionStatus(Components.NoIndexComp2, 'eject'), ).toBe('unsafe'); expect( themeComponents.getActionStatus(Components.NoIndexSubComp, 'wrap'), ).toBe('unsafe'); expect( themeComponents.getActionStatus(Components.NoIndexSubComp, 'eject'), ).toBe('unsafe'); // Intermediate folders are not real components: forbidden to wrap! expect(themeComponents.getActionStatus(Components.NoIndex, 'wrap')).toBe( 'forbidden', ); expect(themeComponents.getActionStatus(Components.NoIndex, 'eject')).toBe( 'unsafe', ); expect(themeComponents.getActionStatus(Components.NoIndexSub, 'wrap')).toBe( 'forbidden', ); expect( themeComponents.getActionStatus(Components.NoIndexSub, 'eject'), ).toBe('unsafe'); }); it('isSafeAction', async () => { const themeComponents = await getThemeComponents({ themeName, themePath, swizzleConfig, }); expect( themeComponents.isSafeAction(Components.ComponentInFolder, 'wrap'), ).toBe(true); expect( themeComponents.isSafeAction(Components.ComponentInFolder, 'eject'), ).toBe(false); expect( themeComponents.isSafeAction(Components.ComponentInSubFolder, 'wrap'), ).toBe(false); expect( themeComponents.isSafeAction(Components.ComponentInSubFolder, 'eject'), ).toBe(true); expect( themeComponents.isSafeAction(Components.FirstLevelComponent, 'wrap'), ).toBe(false); expect( themeComponents.isSafeAction(Components.FirstLevelComponent, 'eject'), ).toBe(false); }); it('hasAnySafeAction', async () => { const themeComponents = await getThemeComponents({ themeName, themePath, swizzleConfig, }); expect(themeComponents.hasAnySafeAction(Components.ComponentInFolder)).toBe( true, ); expect( themeComponents.hasAnySafeAction(Components.ComponentInSubFolder), ).toBe(true); expect( themeComponents.hasAnySafeAction(Components.FirstLevelComponent), ).toBe(false); }); });
2,152
0
petrpan-code/facebook/docusaurus/packages/docusaurus/src/commands/swizzle
petrpan-code/facebook/docusaurus/packages/docusaurus/src/commands/swizzle/__tests__/config.test.ts
/** * Copyright (c) Facebook, Inc. and its affiliates. * * This source code is licensed under the MIT license found in the * LICENSE file in the root directory of this source tree. */ import {normalizeSwizzleConfig} from '../config'; import type {SwizzleConfig} from '@docusaurus/types'; describe('normalizeSwizzleConfig', () => { it(`validate no components config`, () => { const config: SwizzleConfig = { components: {}, }; expect(normalizeSwizzleConfig(config)).toEqual(config); }); it(`validate complete config`, () => { const config: SwizzleConfig = { components: { SomeComponent: { actions: { wrap: 'safe', eject: 'unsafe', }, description: 'SomeComponent description', }, 'Other/Component': { actions: { wrap: 'forbidden', eject: 'unsafe', }, description: 'Other/Component description', }, }, }; expect(normalizeSwizzleConfig(config)).toEqual(config); }); it(`normalize partial config`, () => { const config: SwizzleConfig = { components: { SomeComponent: { // @ts-expect-error: incomplete actions map actions: { eject: 'safe', }, description: 'SomeComponent description', }, 'Other/Component': { // @ts-expect-error: incomplete actions map actions: { wrap: 'forbidden', }, }, }, }; expect(normalizeSwizzleConfig(config)).toMatchSnapshot(); }); it(`reject missing components`, () => { // @ts-expect-error: incomplete actions map const config: SwizzleConfig = {}; expect(() => normalizeSwizzleConfig(config), ).toThrowErrorMatchingInlineSnapshot( `"Swizzle config does not match expected schema: "components" is required"`, ); }); it(`reject invalid action name`, () => { const config: SwizzleConfig = { components: { MyComponent: { actions: { wrap: 'safe', eject: 'unsafe', // @ts-expect-error: on purpose bad: 'safe', }, }, }, }; expect(() => normalizeSwizzleConfig(config), ).toThrowErrorMatchingInlineSnapshot( `"Swizzle config does not match expected schema: "components.MyComponent.actions.bad" is not allowed"`, ); }); it(`reject invalid action status`, () => { const config: SwizzleConfig = { components: { MyComponent: { actions: { wrap: 'safe', // @ts-expect-error: on purpose eject: 'invalid-status', }, }, }, }; expect(() => normalizeSwizzleConfig(config), ).toThrowErrorMatchingInlineSnapshot( `"Swizzle config does not match expected schema: "components.MyComponent.actions.eject" must be one of [safe, unsafe, forbidden]"`, ); }); });
2,153
0
petrpan-code/facebook/docusaurus/packages/docusaurus/src/commands/swizzle
petrpan-code/facebook/docusaurus/packages/docusaurus/src/commands/swizzle/__tests__/index.test.ts
/** * Copyright (c) Facebook, Inc. and its affiliates. * * This source code is licensed under the MIT license found in the * LICENSE file in the root directory of this source tree. */ import {jest} from '@jest/globals'; import path from 'path'; import fs from 'fs-extra'; import tree from 'tree-node-cli'; import {escapePath, Globby, posixPath} from '@docusaurus/utils'; import {ThemePath, createTempSiteDir, Components} from './testUtils'; import {swizzle} from '../index'; const FixtureThemeName = 'fixture-theme-name'; // TODO is it really worth it to duplicate fixtures? const ThemePathJS = ThemePath; const ThemePathTS = ThemePath; async function createTestSiteConfig(siteDir: string) { const configPath = path.join(siteDir, 'docusaurus.config.js'); await fs.writeFile( configPath, ` module.exports = { title: 'My Site', tagline: 'Dinosaurs are cool', url: 'https://your-docusaurus-site.example.com', baseUrl: '/', themes: [ function fixtureTheme() { return { name: '${FixtureThemeName}', getThemePath() { return '${escapePath(ThemePathJS)}'; }, getTypeScriptThemePath() { return '${escapePath(ThemePathTS)}'; }, }; }, ], }`, ); } class MockExitError extends Error { constructor(public code: number) { super(`Exit with code ${code}`); this.code = code; } } function createExitMock() { let mock: jest.SpyInstance<(code?: number) => never>; // eslint-disable-next-line jest/require-top-level-describe beforeEach(async () => { mock = jest.spyOn(process, 'exit').mockImplementation((code) => { throw new MockExitError(code!); }) as jest.SpyInstance<(code?: number) => never>; }); // eslint-disable-next-line jest/require-top-level-describe afterEach(async () => { mock.mockRestore(); }); return { expectExitCode: (code: number) => { expect(mock).toHaveBeenCalledWith(code); }, }; } const swizzleWithExit: typeof swizzle = async (...args) => { await expect(() => swizzle(...args)).rejects.toThrow(MockExitError); }; async function createTestSite() { const siteDir = await createTempSiteDir(); await createTestSiteConfig(siteDir); const siteThemePath = path.join(siteDir, 'src/theme'); await fs.ensureDir(siteThemePath); async function snapshotThemeDir() { const siteThemePathPosix = posixPath(siteThemePath); expect(tree(siteThemePathPosix)).toMatchSnapshot('theme dir tree'); const files = (await Globby(siteThemePathPosix)) .map((file) => path.posix.relative(siteThemePathPosix, file)) .sort(); for (const file of files) { const fileContent = await fs.readFile( path.posix.join(siteThemePath, file), 'utf-8', ); expect(fileContent).toMatchSnapshot(file); } } function testWrap({ component, typescript, }: { component: string; typescript?: boolean; }) { return swizzleWithExit(FixtureThemeName, component, siteDir, { wrap: true, danger: true, typescript, }); } function testEject({ component, typescript, }: { component: string; typescript?: boolean; }) { return swizzleWithExit(FixtureThemeName, component, siteDir, { eject: true, danger: true, typescript, }); } return { siteDir, siteThemePath, snapshotThemeDir, testWrap, testEject, }; } describe('swizzle wrap', () => { const exitMock = createExitMock(); it(`${Components.FirstLevelComponent} JS`, async () => { const {snapshotThemeDir, testWrap} = await createTestSite(); await testWrap({ component: Components.FirstLevelComponent, }); exitMock.expectExitCode(0); await snapshotThemeDir(); }); it(`${Components.FirstLevelComponent} TS`, async () => { const {snapshotThemeDir, testWrap} = await createTestSite(); await testWrap({ component: Components.FirstLevelComponent, typescript: true, }); await snapshotThemeDir(); }); it(`${Components.ComponentInFolder} JS`, async () => { const {snapshotThemeDir, testWrap} = await createTestSite(); await testWrap({ component: Components.ComponentInFolder, }); exitMock.expectExitCode(0); await snapshotThemeDir(); }); it(`${Components.ComponentInFolder} TS`, async () => { const {snapshotThemeDir, testWrap} = await createTestSite(); await testWrap({ component: Components.ComponentInFolder, typescript: true, }); exitMock.expectExitCode(0); await snapshotThemeDir(); }); it(`${Components.ComponentInSubFolder} JS`, async () => { const {snapshotThemeDir, testWrap} = await createTestSite(); await testWrap({ component: Components.ComponentInSubFolder, }); exitMock.expectExitCode(0); await snapshotThemeDir(); }); it(`${Components.ComponentInSubFolder} TS`, async () => { const {snapshotThemeDir, testWrap} = await createTestSite(); await testWrap({ component: Components.ComponentInSubFolder, typescript: true, }); exitMock.expectExitCode(0); await snapshotThemeDir(); }); it(`${Components.Sibling} JS`, async () => { const {snapshotThemeDir, testWrap} = await createTestSite(); await testWrap({ component: Components.Sibling, }); exitMock.expectExitCode(0); await snapshotThemeDir(); }); it(`${Components.Sibling} TS`, async () => { const {snapshotThemeDir, testWrap} = await createTestSite(); await testWrap({ component: Components.Sibling, typescript: true, }); exitMock.expectExitCode(0); await snapshotThemeDir(); }); }); describe('swizzle eject', () => { const exitMock = createExitMock(); it(`${Components.FirstLevelComponent} JS`, async () => { const {snapshotThemeDir, testEject} = await createTestSite(); await testEject({ component: Components.FirstLevelComponent, }); exitMock.expectExitCode(0); await snapshotThemeDir(); }); it(`${Components.FirstLevelComponent} TS`, async () => { const {snapshotThemeDir, testEject} = await createTestSite(); await testEject({ component: Components.FirstLevelComponent, typescript: true, }); await snapshotThemeDir(); }); it(`${Components.ComponentInFolder} JS`, async () => { const {snapshotThemeDir, testEject} = await createTestSite(); await testEject({ component: Components.ComponentInFolder, }); exitMock.expectExitCode(0); await snapshotThemeDir(); }); it(`${Components.ComponentInFolder} TS`, async () => { const {snapshotThemeDir, testEject} = await createTestSite(); await testEject({ component: Components.ComponentInFolder, typescript: true, }); exitMock.expectExitCode(0); await snapshotThemeDir(); }); it(`${Components.ComponentInSubFolder} JS`, async () => { const {snapshotThemeDir, testEject} = await createTestSite(); await testEject({ component: Components.ComponentInSubFolder, }); exitMock.expectExitCode(0); await snapshotThemeDir(); }); it(`${Components.ComponentInSubFolder} TS`, async () => { const {snapshotThemeDir, testEject} = await createTestSite(); await testEject({ component: Components.ComponentInSubFolder, typescript: true, }); exitMock.expectExitCode(0); await snapshotThemeDir(); }); it(`${Components.Sibling} JS`, async () => { const {snapshotThemeDir, testEject} = await createTestSite(); await testEject({ component: Components.Sibling, }); exitMock.expectExitCode(0); await snapshotThemeDir(); }); it(`${Components.Sibling} TS`, async () => { const {snapshotThemeDir, testEject} = await createTestSite(); await testEject({ component: Components.Sibling, typescript: true, }); exitMock.expectExitCode(0); await snapshotThemeDir(); }); });
2,157
0
petrpan-code/facebook/docusaurus/packages/docusaurus/src/commands/swizzle/__tests__/__fixtures__
petrpan-code/facebook/docusaurus/packages/docusaurus/src/commands/swizzle/__tests__/__fixtures__/theme/FirstLevelComponent.test.tsx
// fake test file export {}
2,160
0
petrpan-code/facebook/docusaurus/packages/docusaurus/src/commands/swizzle/__tests__/__fixtures__
petrpan-code/facebook/docusaurus/packages/docusaurus/src/commands/swizzle/__tests__/__fixtures__/theme/JustATest.test.ts
// fake storybook file export {}
2,167
0
petrpan-code/facebook/docusaurus/packages/docusaurus/src/commands/swizzle/__tests__/__fixtures__/theme
petrpan-code/facebook/docusaurus/packages/docusaurus/src/commands/swizzle/__tests__/__fixtures__/theme/ComponentInFolder/index.test.tsx
// fake test file export {}
2,171
0
petrpan-code/facebook/docusaurus/packages/docusaurus/src/commands/swizzle/__tests__/__fixtures__/theme/ComponentInFolder
petrpan-code/facebook/docusaurus/packages/docusaurus/src/commands/swizzle/__tests__/__fixtures__/theme/ComponentInFolder/ComponentInSubFolder/index.test.tsx
// fake test file export {}
2,187
0
petrpan-code/facebook/docusaurus/packages/docusaurus/src/commands/swizzle/__tests__
petrpan-code/facebook/docusaurus/packages/docusaurus/src/commands/swizzle/__tests__/__snapshots__/actions.test.ts.snap
// Jest Snapshot v1, https://goo.gl/fbAQLP exports[`wrap JavaScript wrap ComponentInFolder 2`] = ` "import React from 'react'; import ComponentInFolder from '@theme-original/ComponentInFolder'; export default function ComponentInFolderWrapper(props) { return ( <> <ComponentInFolder {...props} /> </> ); } " `; exports[`wrap JavaScript wrap ComponentInFolder/ComponentInSubFolder 2`] = ` "import React from 'react'; import ComponentInSubFolder from '@theme-original/ComponentInFolder/ComponentInSubFolder'; export default function ComponentInSubFolderWrapper(props) { return ( <> <ComponentInSubFolder {...props} /> </> ); } " `; exports[`wrap JavaScript wrap FirstLevelComponent 2`] = ` "import React from 'react'; import FirstLevelComponent from '@theme-original/FirstLevelComponent'; export default function FirstLevelComponentWrapper(props) { return ( <> <FirstLevelComponent {...props} /> </> ); } " `; exports[`wrap TypeScript wrap ComponentInFolder 2`] = ` "import React from 'react'; import ComponentInFolder from '@theme-original/ComponentInFolder'; import type ComponentInFolderType from '@theme/ComponentInFolder'; import type {WrapperProps} from '@docusaurus/types'; type Props = WrapperProps<typeof ComponentInFolderType>; export default function ComponentInFolderWrapper(props: Props): JSX.Element { return ( <> <ComponentInFolder {...props} /> </> ); } " `; exports[`wrap TypeScript wrap ComponentInFolder/ComponentInSubFolder 2`] = ` "import React from 'react'; import ComponentInSubFolder from '@theme-original/ComponentInFolder/ComponentInSubFolder'; import type ComponentInSubFolderType from '@theme/ComponentInFolder/ComponentInSubFolder'; import type {WrapperProps} from '@docusaurus/types'; type Props = WrapperProps<typeof ComponentInSubFolderType>; export default function ComponentInSubFolderWrapper(props: Props): JSX.Element { return ( <> <ComponentInSubFolder {...props} /> </> ); } " `; exports[`wrap TypeScript wrap FirstLevelComponent 2`] = ` "import React from 'react'; import FirstLevelComponent from '@theme-original/FirstLevelComponent'; import type FirstLevelComponentType from '@theme/FirstLevelComponent'; import type {WrapperProps} from '@docusaurus/types'; type Props = WrapperProps<typeof FirstLevelComponentType>; export default function FirstLevelComponentWrapper(props: Props): JSX.Element { return ( <> <FirstLevelComponent {...props} /> </> ); } " `;
2,188
0
petrpan-code/facebook/docusaurus/packages/docusaurus/src/commands/swizzle/__tests__
petrpan-code/facebook/docusaurus/packages/docusaurus/src/commands/swizzle/__tests__/__snapshots__/config.test.ts.snap
// Jest Snapshot v1, https://goo.gl/fbAQLP exports[`normalizeSwizzleConfig normalize partial config 1`] = ` { "components": { "Other/Component": { "actions": { "eject": "unsafe", "wrap": "forbidden", }, }, "SomeComponent": { "actions": { "eject": "safe", "wrap": "unsafe", }, "description": "SomeComponent description", }, }, } `;
2,189
0
petrpan-code/facebook/docusaurus/packages/docusaurus/src/commands/swizzle/__tests__
petrpan-code/facebook/docusaurus/packages/docusaurus/src/commands/swizzle/__tests__/__snapshots__/index.test.ts.snap
// Jest Snapshot v1, https://goo.gl/fbAQLP exports[`swizzle eject ComponentInFolder JS: ComponentInFolder/ComponentInSubFolder/index.css 1`] = ` ".testClass { background: black; } " `; exports[`swizzle eject ComponentInFolder JS: ComponentInFolder/ComponentInSubFolder/styles.css 1`] = ` ".testClass { background: black; } " `; exports[`swizzle eject ComponentInFolder JS: ComponentInFolder/ComponentInSubFolder/styles.module.css 1`] = ` ".testClass { background: black; } " `; exports[`swizzle eject ComponentInFolder JS: ComponentInFolder/Sibling.css 1`] = ` ".testClass { background: black; } " `; exports[`swizzle eject ComponentInFolder JS: ComponentInFolder/index.css 1`] = ` ".testClass { background: black; } " `; exports[`swizzle eject ComponentInFolder JS: theme dir tree 1`] = ` "theme └── ComponentInFolder ├── ComponentInSubFolder │ ├── index.css │ ├── styles.css │ └── styles.module.css ├── Sibling.css └── index.css" `; exports[`swizzle eject ComponentInFolder TS: ComponentInFolder/ComponentInSubFolder/index.css 1`] = ` ".testClass { background: black; } " `; exports[`swizzle eject ComponentInFolder TS: ComponentInFolder/ComponentInSubFolder/index.tsx 1`] = ` "import React from 'react'; export default function ComponentInSubFolder() { return <div>ComponentInSubFolder</div>; } " `; exports[`swizzle eject ComponentInFolder TS: ComponentInFolder/ComponentInSubFolder/styles.css 1`] = ` ".testClass { background: black; } " `; exports[`swizzle eject ComponentInFolder TS: ComponentInFolder/ComponentInSubFolder/styles.module.css 1`] = ` ".testClass { background: black; } " `; exports[`swizzle eject ComponentInFolder TS: ComponentInFolder/Sibling.css 1`] = ` ".testClass { background: black; } " `; exports[`swizzle eject ComponentInFolder TS: ComponentInFolder/Sibling.tsx 1`] = ` "import React from 'react'; export default function Sibling() { return <div>Sibling</div>; } " `; exports[`swizzle eject ComponentInFolder TS: ComponentInFolder/index.css 1`] = ` ".testClass { background: black; } " `; exports[`swizzle eject ComponentInFolder TS: ComponentInFolder/index.tsx 1`] = ` "import React from 'react'; export default function ComponentInFolder() { return <div>ComponentInFolder</div>; } " `; exports[`swizzle eject ComponentInFolder TS: theme dir tree 1`] = ` "theme └── ComponentInFolder ├── ComponentInSubFolder │ ├── index.css │ ├── index.tsx │ ├── styles.css │ └── styles.module.css ├── Sibling.css ├── Sibling.tsx ├── index.css └── index.tsx" `; exports[`swizzle eject ComponentInFolder/ComponentInSubFolder JS: ComponentInFolder/ComponentInSubFolder/index.css 1`] = ` ".testClass { background: black; } " `; exports[`swizzle eject ComponentInFolder/ComponentInSubFolder JS: ComponentInFolder/ComponentInSubFolder/styles.css 1`] = ` ".testClass { background: black; } " `; exports[`swizzle eject ComponentInFolder/ComponentInSubFolder JS: ComponentInFolder/ComponentInSubFolder/styles.module.css 1`] = ` ".testClass { background: black; } " `; exports[`swizzle eject ComponentInFolder/ComponentInSubFolder JS: theme dir tree 1`] = ` "theme └── ComponentInFolder └── ComponentInSubFolder ├── index.css ├── styles.css └── styles.module.css" `; exports[`swizzle eject ComponentInFolder/ComponentInSubFolder TS: ComponentInFolder/ComponentInSubFolder/index.css 1`] = ` ".testClass { background: black; } " `; exports[`swizzle eject ComponentInFolder/ComponentInSubFolder TS: ComponentInFolder/ComponentInSubFolder/index.tsx 1`] = ` "import React from 'react'; export default function ComponentInSubFolder() { return <div>ComponentInSubFolder</div>; } " `; exports[`swizzle eject ComponentInFolder/ComponentInSubFolder TS: ComponentInFolder/ComponentInSubFolder/styles.css 1`] = ` ".testClass { background: black; } " `; exports[`swizzle eject ComponentInFolder/ComponentInSubFolder TS: ComponentInFolder/ComponentInSubFolder/styles.module.css 1`] = ` ".testClass { background: black; } " `; exports[`swizzle eject ComponentInFolder/ComponentInSubFolder TS: theme dir tree 1`] = ` "theme └── ComponentInFolder └── ComponentInSubFolder ├── index.css ├── index.tsx ├── styles.css └── styles.module.css" `; exports[`swizzle eject ComponentInFolder/Sibling JS: ComponentInFolder/Sibling.css 1`] = ` ".testClass { background: black; } " `; exports[`swizzle eject ComponentInFolder/Sibling JS: theme dir tree 1`] = ` "theme └── ComponentInFolder └── Sibling.css" `; exports[`swizzle eject ComponentInFolder/Sibling TS: ComponentInFolder/Sibling.css 1`] = ` ".testClass { background: black; } " `; exports[`swizzle eject ComponentInFolder/Sibling TS: ComponentInFolder/Sibling.tsx 1`] = ` "import React from 'react'; export default function Sibling() { return <div>Sibling</div>; } " `; exports[`swizzle eject ComponentInFolder/Sibling TS: theme dir tree 1`] = ` "theme └── ComponentInFolder ├── Sibling.css └── Sibling.tsx" `; exports[`swizzle eject FirstLevelComponent JS: FirstLevelComponent.css 1`] = ` ".testClass { background: black; } " `; exports[`swizzle eject FirstLevelComponent JS: theme dir tree 1`] = ` "theme └── FirstLevelComponent.css" `; exports[`swizzle eject FirstLevelComponent TS: FirstLevelComponent.css 1`] = ` ".testClass { background: black; } " `; exports[`swizzle eject FirstLevelComponent TS: FirstLevelComponent.tsx 1`] = ` "import React from 'react'; export default function FirstLevelComponent() { return <div>First level component</div>; } " `; exports[`swizzle eject FirstLevelComponent TS: theme dir tree 1`] = ` "theme ├── FirstLevelComponent.css └── FirstLevelComponent.tsx" `; exports[`swizzle wrap ComponentInFolder JS: ComponentInFolder/index.js 1`] = ` "import React from 'react'; import ComponentInFolder from '@theme-original/ComponentInFolder'; export default function ComponentInFolderWrapper(props) { return ( <> <ComponentInFolder {...props} /> </> ); } " `; exports[`swizzle wrap ComponentInFolder JS: theme dir tree 1`] = ` "theme └── ComponentInFolder └── index.js" `; exports[`swizzle wrap ComponentInFolder TS: ComponentInFolder/index.tsx 1`] = ` "import React from 'react'; import ComponentInFolder from '@theme-original/ComponentInFolder'; import type ComponentInFolderType from '@theme/ComponentInFolder'; import type {WrapperProps} from '@docusaurus/types'; type Props = WrapperProps<typeof ComponentInFolderType>; export default function ComponentInFolderWrapper(props: Props): JSX.Element { return ( <> <ComponentInFolder {...props} /> </> ); } " `; exports[`swizzle wrap ComponentInFolder TS: theme dir tree 1`] = ` "theme └── ComponentInFolder └── index.tsx" `; exports[`swizzle wrap ComponentInFolder/ComponentInSubFolder JS: ComponentInFolder/ComponentInSubFolder/index.js 1`] = ` "import React from 'react'; import ComponentInSubFolder from '@theme-original/ComponentInFolder/ComponentInSubFolder'; export default function ComponentInSubFolderWrapper(props) { return ( <> <ComponentInSubFolder {...props} /> </> ); } " `; exports[`swizzle wrap ComponentInFolder/ComponentInSubFolder JS: theme dir tree 1`] = ` "theme └── ComponentInFolder └── ComponentInSubFolder └── index.js" `; exports[`swizzle wrap ComponentInFolder/ComponentInSubFolder TS: ComponentInFolder/ComponentInSubFolder/index.tsx 1`] = ` "import React from 'react'; import ComponentInSubFolder from '@theme-original/ComponentInFolder/ComponentInSubFolder'; import type ComponentInSubFolderType from '@theme/ComponentInFolder/ComponentInSubFolder'; import type {WrapperProps} from '@docusaurus/types'; type Props = WrapperProps<typeof ComponentInSubFolderType>; export default function ComponentInSubFolderWrapper(props: Props): JSX.Element { return ( <> <ComponentInSubFolder {...props} /> </> ); } " `; exports[`swizzle wrap ComponentInFolder/ComponentInSubFolder TS: theme dir tree 1`] = ` "theme └── ComponentInFolder └── ComponentInSubFolder └── index.tsx" `; exports[`swizzle wrap ComponentInFolder/Sibling JS: ComponentInFolder/Sibling.js 1`] = ` "import React from 'react'; import Sibling from '@theme-original/ComponentInFolder/Sibling'; export default function SiblingWrapper(props) { return ( <> <Sibling {...props} /> </> ); } " `; exports[`swizzle wrap ComponentInFolder/Sibling JS: theme dir tree 1`] = ` "theme └── ComponentInFolder └── Sibling.js" `; exports[`swizzle wrap ComponentInFolder/Sibling TS: ComponentInFolder/Sibling.tsx 1`] = ` "import React from 'react'; import Sibling from '@theme-original/ComponentInFolder/Sibling'; import type SiblingType from '@theme/ComponentInFolder/Sibling'; import type {WrapperProps} from '@docusaurus/types'; type Props = WrapperProps<typeof SiblingType>; export default function SiblingWrapper(props: Props): JSX.Element { return ( <> <Sibling {...props} /> </> ); } " `; exports[`swizzle wrap ComponentInFolder/Sibling TS: theme dir tree 1`] = ` "theme └── ComponentInFolder └── Sibling.tsx" `; exports[`swizzle wrap FirstLevelComponent JS: FirstLevelComponent.js 1`] = ` "import React from 'react'; import FirstLevelComponent from '@theme-original/FirstLevelComponent'; export default function FirstLevelComponentWrapper(props) { return ( <> <FirstLevelComponent {...props} /> </> ); } " `; exports[`swizzle wrap FirstLevelComponent JS: theme dir tree 1`] = ` "theme └── FirstLevelComponent.js" `; exports[`swizzle wrap FirstLevelComponent TS: FirstLevelComponent.tsx 1`] = ` "import React from 'react'; import FirstLevelComponent from '@theme-original/FirstLevelComponent'; import type FirstLevelComponentType from '@theme/FirstLevelComponent'; import type {WrapperProps} from '@docusaurus/types'; type Props = WrapperProps<typeof FirstLevelComponentType>; export default function FirstLevelComponentWrapper(props: Props): JSX.Element { return ( <> <FirstLevelComponent {...props} /> </> ); } " `; exports[`swizzle wrap FirstLevelComponent TS: theme dir tree 1`] = ` "theme └── FirstLevelComponent.tsx" `;
2,202
0
petrpan-code/facebook/docusaurus/packages/docusaurus/src/server
petrpan-code/facebook/docusaurus/packages/docusaurus/src/server/__tests__/brokenLinks.test.ts
/** * Copyright (c) Facebook, Inc. and its affiliates. * * This source code is licensed under the MIT license found in the * LICENSE file in the root directory of this source tree. */ import {jest} from '@jest/globals'; import path from 'path'; import _ from 'lodash'; import {handleBrokenLinks} from '../brokenLinks'; import type {RouteConfig} from '@docusaurus/types'; describe('handleBrokenLinks', () => { const routes: RouteConfig[] = [ { path: '/community', component: '', }, { path: '/docs', component: '', routes: [ {path: '/docs/goodDoc', component: ''}, {path: '/docs/anotherGoodDoc', component: ''}, {path: '/docs/good doc with space', component: ''}, {path: '/docs/another good doc with space', component: ''}, {path: '/docs/weird%20but%20good', component: ''}, ], }, { path: '*', component: '', }, ]; const link1 = '/link1'; const link2 = '/docs/link2'; const link3 = '/hey/link3'; const linkToJavadoc1 = '/javadoc'; const linkToJavadoc2 = '/javadoc/'; const linkToJavadoc3 = '/javadoc/index.html'; const linkToJavadoc4 = '/javadoc/index.html#foo'; const linkToZipFile = '/files/file.zip'; const linkToHtmlFile1 = '/files/hey.html'; const linkToHtmlFile2 = '/files/hey'; const linkToEmptyFolder1 = '/emptyFolder'; const linkToEmptyFolder2 = '/emptyFolder/'; const allCollectedLinks = { '/docs/good doc with space': [ // Good - valid file with spaces in name './another%20good%20doc%20with%20space', // Good - valid file with percent-20 in its name './weird%20but%20good', // Bad - non-existent file with spaces in name './some%20other%20non-existent%20doc1', // Evil - trying to use ../../ but '/' won't get decoded // cSpell:ignore Fout './break%2F..%2F..%2Fout2', ], '/docs/goodDoc': [ // Good links './anotherGoodDoc#someHash', '/docs/anotherGoodDoc?someQueryString=true#someHash', '../docs/anotherGoodDoc?someQueryString=true', '../docs/anotherGoodDoc#someHash', // Bad links '../anotherGoodDoc#reported-because-of-bad-relative-path1', './docThatDoesNotExist2', './badRelativeLink3', '../badRelativeLink4', ], '/community': [ // Good links '/docs/goodDoc', '/docs/anotherGoodDoc#someHash', './docs/goodDoc#someHash', './docs/anotherGoodDoc', // Bad links '/someNonExistentDoc1', '/badLink2', './badLink3', ], '/page1': [ link1, linkToHtmlFile1, linkToJavadoc1, linkToHtmlFile2, linkToJavadoc3, linkToJavadoc4, linkToEmptyFolder1, // Not filtered! ], '/page2': [ link2, linkToEmptyFolder2, // Not filtered! linkToJavadoc2, link3, linkToJavadoc3, linkToZipFile, ], }; const outDir = path.resolve(__dirname, '__fixtures__/brokenLinks/outDir'); it('do not report anything for correct paths', async () => { const consoleMock = jest .spyOn(console, 'warn') .mockImplementation(() => {}); const allCollectedCorrectLinks = { '/docs/good doc with space': [ './another%20good%20doc%20with%20space', './weird%20but%20good', ], '/docs/goodDoc': [ './anotherGoodDoc#someHash', '/docs/anotherGoodDoc?someQueryString=true#someHash', '../docs/anotherGoodDoc?someQueryString=true', '../docs/anotherGoodDoc#someHash', ], '/community': [ '/docs/goodDoc', '/docs/anotherGoodDoc#someHash', './docs/goodDoc#someHash', './docs/anotherGoodDoc', ], '/page1': [ linkToHtmlFile1, linkToJavadoc1, linkToHtmlFile2, linkToJavadoc3, linkToJavadoc4, ], }; await handleBrokenLinks({ allCollectedLinks: allCollectedCorrectLinks, onBrokenLinks: 'warn', routes, baseUrl: '/', outDir, }); expect(consoleMock).toHaveBeenCalledTimes(0); }); it('reports all broken links', async () => { await expect(() => handleBrokenLinks({ allCollectedLinks, onBrokenLinks: 'throw', routes, baseUrl: '/', outDir, }), ).rejects.toThrowErrorMatchingSnapshot(); }); it('no-op for ignore', async () => { // In any case, _.mapValues will always be called, unless handleBrokenLinks // has already bailed const lodashMock = jest.spyOn(_, 'mapValues'); await handleBrokenLinks({ allCollectedLinks, onBrokenLinks: 'ignore', routes, baseUrl: '/', outDir, }); expect(lodashMock).toHaveBeenCalledTimes(0); lodashMock.mockRestore(); }); it('reports frequent broken links', async () => { Object.values(allCollectedLinks).forEach((links) => links.push( '/frequent', // This is in the gray area of what should be reported. Relative paths // may be resolved to different slugs on different locations. But if // this comes from a layout link, it should be reported anyways './maybe-not', ), ); await expect(() => handleBrokenLinks({ allCollectedLinks, onBrokenLinks: 'throw', routes, baseUrl: '/', outDir, }), ).rejects.toThrowErrorMatchingSnapshot(); }); });
2,203
0
petrpan-code/facebook/docusaurus/packages/docusaurus/src/server
petrpan-code/facebook/docusaurus/packages/docusaurus/src/server/__tests__/clientModules.test.ts
/** * Copyright (c) Facebook, Inc. and its affiliates. * * This source code is licensed under the MIT license found in the * LICENSE file in the root directory of this source tree. */ import {loadClientModules} from '../clientModules'; import type {LoadedPlugin} from '@docusaurus/types'; const pluginEmpty = { name: 'plugin-empty', path: __dirname, } as LoadedPlugin; const pluginFooBar = { name: 'plugin-foo-bar', path: __dirname, getClientModules() { return ['foo', 'bar']; }, } as LoadedPlugin; const pluginHelloWorld = { plugin: 'plugin-hello-world', path: __dirname, getClientModules() { return [ // Absolute path '/hello', 'world', ]; }, } as unknown as LoadedPlugin; describe('loadClientModules', () => { it('loads an empty plugin', () => { const clientModules = loadClientModules([pluginEmpty]); expect(clientModules).toMatchInlineSnapshot(`[]`); }); it('loads a non-empty plugin', () => { const clientModules = loadClientModules([pluginFooBar]); expect(clientModules).toMatchInlineSnapshot(` [ "<PROJECT_ROOT>/packages/docusaurus/src/server/__tests__/foo", "<PROJECT_ROOT>/packages/docusaurus/src/server/__tests__/bar", ] `); }); it('loads multiple non-empty plugins', () => { const clientModules = loadClientModules([pluginFooBar, pluginHelloWorld]); expect(clientModules).toMatchInlineSnapshot(` [ "<PROJECT_ROOT>/packages/docusaurus/src/server/__tests__/foo", "<PROJECT_ROOT>/packages/docusaurus/src/server/__tests__/bar", "/hello", "<PROJECT_ROOT>/packages/docusaurus/src/server/__tests__/world", ] `); }); it('loads multiple non-empty plugins in different order', () => { const clientModules = loadClientModules([pluginHelloWorld, pluginFooBar]); expect(clientModules).toMatchInlineSnapshot(` [ "/hello", "<PROJECT_ROOT>/packages/docusaurus/src/server/__tests__/world", "<PROJECT_ROOT>/packages/docusaurus/src/server/__tests__/foo", "<PROJECT_ROOT>/packages/docusaurus/src/server/__tests__/bar", ] `); }); it('loads both empty and non-empty plugins', () => { const clientModules = loadClientModules([ pluginHelloWorld, pluginEmpty, pluginFooBar, ]); expect(clientModules).toMatchInlineSnapshot(` [ "/hello", "<PROJECT_ROOT>/packages/docusaurus/src/server/__tests__/world", "<PROJECT_ROOT>/packages/docusaurus/src/server/__tests__/foo", "<PROJECT_ROOT>/packages/docusaurus/src/server/__tests__/bar", ] `); }); it('loads empty and non-empty in a different order', () => { const clientModules = loadClientModules([ pluginHelloWorld, pluginFooBar, pluginEmpty, ]); expect(clientModules).toMatchInlineSnapshot(` [ "/hello", "<PROJECT_ROOT>/packages/docusaurus/src/server/__tests__/world", "<PROJECT_ROOT>/packages/docusaurus/src/server/__tests__/foo", "<PROJECT_ROOT>/packages/docusaurus/src/server/__tests__/bar", ] `); }); });
2,204
0
petrpan-code/facebook/docusaurus/packages/docusaurus/src/server
petrpan-code/facebook/docusaurus/packages/docusaurus/src/server/__tests__/config.test.ts
/** * Copyright (c) Facebook, Inc. and its affiliates. * * This source code is licensed under the MIT license found in the * LICENSE file in the root directory of this source tree. */ import path from 'path'; import {loadSiteConfig} from '../config'; describe('loadSiteConfig', () => { const siteDir = path.join(__dirname, '__fixtures__', 'config'); it('website with valid siteConfig', async () => { const config = await loadSiteConfig({ siteDir: path.join(__dirname, '__fixtures__', 'simple-site'), }); expect(config).toMatchSnapshot(); expect(config).not.toEqual({}); }); it('website with ts + js config', async () => { const config = await loadSiteConfig({ siteDir: path.join( __dirname, '__fixtures__', 'config/sites/ts-and-js-site', ), }); expect(config).toMatchSnapshot(); // Docusaurus uses in priority a TS config expect(config.siteConfig.title).toBe('TS title'); expect(config).not.toEqual({}); }); it('website with .cjs siteConfig', async () => { const config = await loadSiteConfig({siteDir}); expect(config).toMatchSnapshot(); expect(config).not.toEqual({}); }); it('website with valid config creator function', async () => { const config = await loadSiteConfig({ siteDir, customConfigFilePath: 'createConfig.config.js', }); expect(config).toMatchSnapshot(); expect(config).not.toEqual({}); }); it('website with valid async config', async () => { const config = await loadSiteConfig({ siteDir, customConfigFilePath: 'configAsync.config.js', }); expect(config).toMatchSnapshot(); expect(config).not.toEqual({}); }); it('website with valid async config creator function', async () => { const config = await loadSiteConfig({ siteDir, customConfigFilePath: 'createConfigAsync.config.js', }); expect(config).toMatchSnapshot(); expect(config).not.toEqual({}); }); it('website with valid JS CJS config', async () => { const config = await loadSiteConfig({ siteDir, customConfigFilePath: 'configCJS.js', }); expect(config).toMatchSnapshot(); expect(config).not.toEqual({}); }); it('website with valid JS ESM config', async () => { const config = await loadSiteConfig({ siteDir, customConfigFilePath: 'configESM.js', }); expect(config).toMatchSnapshot(); expect(config).not.toEqual({}); }); it('website with valid TypeScript CJS config', async () => { const config = await loadSiteConfig({ siteDir, customConfigFilePath: 'configCJS.ts', }); expect(config).toMatchSnapshot(); expect(config).not.toEqual({}); }); it('website with valid TypeScript ESM config', async () => { const config = await loadSiteConfig({ siteDir, customConfigFilePath: 'configESM.ts', }); expect(config).toMatchSnapshot(); expect(config).not.toEqual({}); }); it('website with incomplete siteConfig', async () => { await expect( loadSiteConfig({ siteDir, customConfigFilePath: 'incomplete.config.js', }), ).rejects.toThrowErrorMatchingInlineSnapshot(` ""url" is required " `); }); it('website with useless field (wrong field) in siteConfig', async () => { await expect( loadSiteConfig({ siteDir, customConfigFilePath: 'wrong.config.js', }), ).rejects.toThrowErrorMatchingInlineSnapshot(` "These field(s) ("useLessField",) are not recognized in wrong.config.js. If you still want these fields to be in your configuration, put them in the "customFields" field. See https://docusaurus.io/docs/api/docusaurus-config/#customfields" `); }); it('website with no siteConfig', async () => { await expect( loadSiteConfig({ siteDir, customConfigFilePath: 'nonExistent.config.js', }), ).rejects.toThrowErrorMatchingInlineSnapshot( `"Config file at "<PROJECT_ROOT>/packages/docusaurus/src/server/__tests__/__fixtures__/config/nonExistent.config.js" not found."`, ); }); });
2,205
0
petrpan-code/facebook/docusaurus/packages/docusaurus/src/server
petrpan-code/facebook/docusaurus/packages/docusaurus/src/server/__tests__/configValidation.test.ts
/** * Copyright (c) Facebook, Inc. and its affiliates. * * This source code is licensed under the MIT license found in the * LICENSE file in the root directory of this source tree. */ import { ConfigSchema, DEFAULT_CONFIG, validateConfig, } from '../configValidation'; import type {Config, DocusaurusConfig} from '@docusaurus/types'; import type {DeepPartial} from 'utility-types'; const baseConfig = { baseUrl: '/', title: 'my site', url: 'https://mysite.com', } as Config; const normalizeConfig = (config: DeepPartial<Config>) => validateConfig({...baseConfig, ...config}, 'docusaurus.config.js'); describe('normalizeConfig', () => { it('normalizes empty config', () => { const value = normalizeConfig({}); expect(value).toEqual({ ...DEFAULT_CONFIG, ...baseConfig, }); }); it('accepts correctly defined config options', () => { const userConfig: Config = { ...DEFAULT_CONFIG, ...baseConfig, tagline: 'my awesome site', organizationName: 'facebook', projectName: 'docusaurus', githubHost: 'github.com', githubPort: '8000', customFields: { myCustomField: '42', }, scripts: [ { src: `/analytics.js`, async: true, defer: true, 'data-domain': 'xyz', // See https://github.com/facebook/docusaurus/issues/3378 }, ], stylesheets: [ { href: '/katex/katex.min.css', type: 'text/css', crossorigin: 'anonymous', }, ], markdown: { format: 'md', mermaid: true, preprocessor: ({fileContent}) => fileContent, mdx1Compat: { comments: true, admonitions: false, headingIds: true, }, }, }; const normalizedConfig = normalizeConfig(userConfig); expect(normalizedConfig).toEqual(userConfig); }); it('accepts custom field in config', () => { const value = normalizeConfig({ customFields: { author: 'anshul', }, }); expect(value).toEqual({ ...DEFAULT_CONFIG, ...baseConfig, customFields: { author: 'anshul', }, }); }); it('throws error for unknown field', () => { expect(() => { normalizeConfig({ // @ts-expect-error: test invalid: true, }); }).toThrowErrorMatchingSnapshot(); }); it('throws for non-string URLs', () => { expect(() => normalizeConfig({ // @ts-expect-error: test url: 1, }), ).toThrowErrorMatchingInlineSnapshot(` ""url" must be a string " `); }); it('throws for invalid URL', () => { expect(() => normalizeConfig({ url: 'mysite.com', }), ).toThrowErrorMatchingInlineSnapshot(` ""mysite.com" does not look like a valid URL. Make sure it has a protocol; for example, "https://example.com". " `); }); it('normalizes URL', () => { expect( normalizeConfig({ url: 'https://mysite.com/', }).url, ).toBe('https://mysite.com'); }); it('throws for non-string base URLs', () => { expect(() => normalizeConfig({ // @ts-expect-error: test baseUrl: 1, }), ).toThrowErrorMatchingInlineSnapshot(` ""baseUrl" must be a string " `); }); it('normalizes various base URLs', () => { expect( normalizeConfig({ baseUrl: '', }).baseUrl, ).toBe('/'); expect( normalizeConfig({ baseUrl: 'noSlash', }).baseUrl, ).toBe('/noSlash/'); expect( normalizeConfig({ baseUrl: '/noSlash', }).baseUrl, ).toBe('/noSlash/'); expect( normalizeConfig({ baseUrl: 'noSlash/foo', }).baseUrl, ).toBe('/noSlash/foo/'); }); it.each([ ['should throw error if plugins is not array', {}], [ "should throw error if plugins is not a string and it's not an array #1", [123], ], [ 'should throw error if plugins is not an array of [string, object][] #1', [['example/path', 'wrong parameter here']], ], [ 'should throw error if plugins is not an array of [string, object][] #2', [[{}, 'example/path']], ], [ 'should throw error if plugins is not an array of [string, object][] #3', [[{}, {}]], ], ])(`%s for the input of: %p`, (_message, plugins) => { expect(() => { normalizeConfig({ // @ts-expect-error: test plugins, }); }).toThrowErrorMatchingSnapshot(); }); it.each([ ['should throw error if themes is not array', {}], [ "should throw error if themes is not a string and it's not an array #1", [123], ], [ 'should throw error if themes is not an array of [string, object][] #1', [['example/path', 'wrong parameter here']], ], [ 'should throw error if themes is not an array of [string, object][] #2', [[{}, 'example/path']], ], [ 'should throw error if themes is not an array of [string, object][] #3', [[{}, {}]], ], ])(`%s for the input of: %p`, (_message, themes) => { expect(() => { normalizeConfig({ // @ts-expect-error: test themes, }); }).toThrowErrorMatchingSnapshot(); }); it.each([ ['should accept [string] for plugins', ['plain/string']], [ 'should accept string[] for plugins', ['plain/string', 'another/plain/string/path'], ], [ 'should accept [string, object] for plugins', [['plain/string', {it: 'should work'}]], ], [ 'should accept [string, object][] for plugins', [ ['plain/string', {it: 'should work'}], ['this/should/work', {too: 'yes'}], ], ], [ 'should accept ([string, object]|string)[] for plugins', [ 'plain/string', ['plain', {it: 'should work'}], ['this/should/work', {too: 'yes'}], ], ], ['should accept function for plugin', [function plugin() {}]], [ 'should accept [function, object] for plugin', [[() => {}, {it: 'should work'}]], ], ['should accept false/null for plugin', [false as const, null, 'classic']], ])(`%s for the input of: %p`, (_message, plugins) => { expect(() => { normalizeConfig({ plugins, } as Config); }).not.toThrow(); }); it.each([ ['should accept [string] for themes', ['plain/string']], [ 'should accept string[] for themes', ['plain/string', 'another/plain/string/path'], ], [ 'should accept [string, object] for themes', [['plain/string', {it: 'should work'}]], ], [ 'should accept [string, object][] for themes', [ ['plain/string', {it: 'should work'}], ['this/should/work', {too: 'yes'}], ], ], [ 'should accept ([string, object]|string)[] for themes', [ 'plain/string', ['plain', {it: 'should work'}], ['this/should/work', {too: 'yes'}], ], ], ['should accept function for theme', [function theme() {}]], [ 'should accept [function, object] for theme', [[function theme() {}, {it: 'should work'}]], ], ['should accept false/null for themes', [false, null, 'classic']], ])(`%s for the input of: %p`, (_message, themes) => { expect(() => { normalizeConfig({ themes, } as Config); }).not.toThrow(); }); it('throws error if themes is not array', () => { expect(() => { normalizeConfig({ // @ts-expect-error: test themes: {}, }); }).toThrowErrorMatchingInlineSnapshot(` ""themes" must be an array " `); }); it('throws error if presets is not array', () => { expect(() => { normalizeConfig({ // @ts-expect-error: test presets: {}, }); }).toThrowErrorMatchingInlineSnapshot(` ""presets" must be an array " `); }); it('throws error if presets looks invalid', () => { expect(() => { normalizeConfig({ // @ts-expect-error: test presets: [() => {}], }); }).toThrowErrorMatchingInlineSnapshot(` ""presets[0]" does not look like a valid preset config. A preset config entry should be one of: - A tuple of [presetName, options], like \`["classic", { blog: false }]\`, or - A simple string, like \`"classic"\` " `); }); it('accepts presets as false / null', () => { expect(() => { normalizeConfig({ presets: [false, null, 'classic'], }); }).not.toThrow(); }); it("throws error if scripts doesn't have src", () => { expect(() => { normalizeConfig({ scripts: ['https://some.com', {}], }); }).toThrowErrorMatchingInlineSnapshot(` ""scripts[1]" is invalid. A script must be a plain string (the src), or an object with at least a "src" property. " `); }); it('accepts headTags with tagName and attributes', () => { expect(() => { normalizeConfig({ headTags: [ { tagName: 'link', attributes: { rel: 'icon', href: 'img/docusaurus.png', }, }, ], }); }).not.toThrow(); }); it("throws error if headTags doesn't have tagName", () => { expect(() => { normalizeConfig({ headTags: [ { attributes: { rel: 'icon', href: 'img/docusaurus.png', }, }, ], }); }).toThrowErrorMatchingInlineSnapshot(` ""headTags[0].tagName" is required " `); }); it("throws error if headTags doesn't have attributes", () => { expect(() => { normalizeConfig({ headTags: [ { tagName: 'link', }, ], }); }).toThrowErrorMatchingInlineSnapshot(` ""headTags[0].attributes" is required " `); }); it("throws error if headTags doesn't have string attributes", () => { expect(() => { normalizeConfig({ headTags: [ { tagName: 'link', attributes: { rel: false, href: 'img/docusaurus.png', }, }, ], }); }).toThrowErrorMatchingInlineSnapshot(` ""headTags[0].attributes.rel" must be a string " `); }); it("throws error if css doesn't have href", () => { expect(() => { normalizeConfig({ stylesheets: ['https://somescript.com', {type: 'text/css'}], }); }).toThrowErrorMatchingInlineSnapshot(` ""stylesheets[1]" is invalid. A stylesheet must be a plain string (the href), or an object with at least a "href" property. " `); }); it('throws error for required fields', () => { expect(() => validateConfig( { invalidField: true, presets: {}, stylesheets: {}, themes: {}, scripts: {}, }, 'docusaurus.config.js', ), ).toThrowErrorMatchingSnapshot(); }); it('throws for "error" reporting severity', () => { expect(() => validateConfig( { title: 'Site', url: 'https://example.com', baseUrl: '/', onBrokenLinks: 'error', }, 'docusaurus.config.js', ), ).toThrowErrorMatchingSnapshot(); }); }); describe('config warning and error', () => { function getWarning(config: unknown) { return ConfigSchema.validate(config).warning; } it('baseConfig has no warning', () => { const warning = getWarning(baseConfig); expect(warning).toBeUndefined(); }); it('site url fails validation when using subpath', () => { const {error} = ConfigSchema.validate({ ...baseConfig, url: 'https://mysite.com/someSubpath', }); expect(error).toBeDefined(); expect(error?.message).toBe( 'The url is not supposed to contain a sub-path like "/someSubpath". Please use the baseUrl field for sub-paths.', ); }); }); describe('markdown', () => { it('accepts undefined object', () => { expect( normalizeConfig({ markdown: undefined, }), ).toEqual(expect.objectContaining({markdown: DEFAULT_CONFIG.markdown})); }); it('accepts empty object', () => { expect( normalizeConfig({ markdown: {}, }), ).toEqual(expect.objectContaining({markdown: DEFAULT_CONFIG.markdown})); }); it('accepts valid markdown object', () => { const markdown: DocusaurusConfig['markdown'] = { format: 'md', mermaid: true, preprocessor: ({fileContent}) => fileContent, mdx1Compat: { comments: false, admonitions: true, headingIds: false, }, }; expect( normalizeConfig({ markdown, }), ).toEqual(expect.objectContaining({markdown})); }); it('accepts partial markdown object', () => { const markdown: DeepPartial<DocusaurusConfig['markdown']> = { mdx1Compat: { admonitions: true, headingIds: false, }, }; expect( normalizeConfig({ markdown, }), ).toEqual( expect.objectContaining({ markdown: { ...DEFAULT_CONFIG.markdown, ...markdown, mdx1Compat: { ...DEFAULT_CONFIG.markdown.mdx1Compat, ...markdown.mdx1Compat, }, }, }), ); }); it('throw for preprocessor bad arity', () => { expect(() => normalizeConfig({ markdown: {preprocessor: () => 'content'}, }), ).toThrowErrorMatchingInlineSnapshot(` ""markdown.preprocessor" must have an arity of 1 " `); expect(() => normalizeConfig({ // @ts-expect-error: types forbid this markdown: {preprocessor: (arg1, arg2) => String(arg1) + String(arg2)}, }), ).toThrowErrorMatchingInlineSnapshot(` ""markdown.preprocessor" must have an arity of 1 " `); }); it('accepts undefined markdown format', () => { expect( normalizeConfig({markdown: {format: undefined}}).markdown.format, ).toBe('mdx'); }); it('throw for bad markdown format', () => { expect(() => normalizeConfig( // @ts-expect-error: bad value {markdown: {format: null}}, ), ).toThrowErrorMatchingInlineSnapshot(` ""markdown.format" must be one of [mdx, md, detect] "markdown.format" must be a string " `); expect(() => normalizeConfig( // @ts-expect-error: bad value {markdown: {format: 'xyz'}}, ), ).toThrowErrorMatchingInlineSnapshot(` ""markdown.format" must be one of [mdx, md, detect] " `); }); it('throw for null object', () => { expect(() => { normalizeConfig({ // @ts-expect-error: test markdown: null, }); }).toThrowErrorMatchingInlineSnapshot(` ""markdown" must be of type object " `); }); });
2,206
0
petrpan-code/facebook/docusaurus/packages/docusaurus/src/server
petrpan-code/facebook/docusaurus/packages/docusaurus/src/server/__tests__/htmlTags.test.ts
/** * Copyright (c) Facebook, Inc. and its affiliates. * * This source code is licensed under the MIT license found in the * LICENSE file in the root directory of this source tree. */ import {loadHtmlTags} from '../htmlTags'; import type {LoadedPlugin} from '@docusaurus/types'; const pluginEmpty = { name: 'plugin-empty', } as LoadedPlugin; const pluginPreBodyTags = { name: 'plugin-preBodyTags', injectHtmlTags() { return { preBodyTags: { tagName: 'script', attributes: { type: 'text/javascript', async: false, }, innerHTML: 'window.foo = null;', }, }; }, } as unknown as LoadedPlugin; const pluginHeadTags = { name: 'plugin-headTags-only', injectHtmlTags() { return { headTags: [ { tagName: 'link', attributes: { rel: 'preconnect', href: 'www.google-analytics.com', }, }, { tagName: 'meta', attributes: { name: 'generator', content: 'Docusaurus', }, }, { tagName: 'script', attributes: { type: 'text/javascript', src: 'https://cdnjs.cloudflare.com/ajax/libs/clipboard.js/2.0.0/clipboard.min.js', async: true, 'data-options': '{"prop":true}', }, }, ], }; }, } as unknown as LoadedPlugin; const pluginPostBodyTags = { name: 'plugin-postBody-tags', injectHtmlTags() { return { postBodyTags: [ { tagName: 'div', innerHTML: 'Test content', }, '<script>window.alert(1);</script>', ], }; }, } as unknown as LoadedPlugin; const pluginMaybeInjectHeadTags = { name: 'plugin-postBody-tags', injectHtmlTags() { return undefined; }, } as unknown as LoadedPlugin; describe('loadHtmlTags', () => { it('works for an empty plugin', () => { const htmlTags = loadHtmlTags([pluginEmpty]); expect(htmlTags).toMatchInlineSnapshot(` { "headTags": "", "postBodyTags": "", "preBodyTags": "", } `); }); it('only injects headTags', () => { const htmlTags = loadHtmlTags([pluginHeadTags]); expect(htmlTags).toMatchInlineSnapshot(` { "headTags": "<link rel="preconnect" href="www.google-analytics.com"> <meta name="generator" content="Docusaurus"> <script type="text/javascript" src="https://cdnjs.cloudflare.com/ajax/libs/clipboard.js/2.0.0/clipboard.min.js" async data-options="{&quot;prop&quot;:true}"></script>", "postBodyTags": "", "preBodyTags": "", } `); }); it('only injects preBodyTags', () => { const htmlTags = loadHtmlTags([pluginPreBodyTags]); expect(htmlTags).toMatchInlineSnapshot(` { "headTags": "", "postBodyTags": "", "preBodyTags": "<script type="text/javascript">window.foo = null;</script>", } `); }); it('only injects postBodyTags', () => { const htmlTags = loadHtmlTags([pluginPostBodyTags]); expect(htmlTags).toMatchInlineSnapshot(` { "headTags": "", "postBodyTags": "<div>Test content</div> <script>window.alert(1);</script>", "preBodyTags": "", } `); }); it('allows multiple plugins that inject different part of html tags', () => { const htmlTags = loadHtmlTags([ pluginHeadTags, pluginPostBodyTags, pluginPreBodyTags, ]); expect(htmlTags).toMatchInlineSnapshot(` { "headTags": "<link rel="preconnect" href="www.google-analytics.com"> <meta name="generator" content="Docusaurus"> <script type="text/javascript" src="https://cdnjs.cloudflare.com/ajax/libs/clipboard.js/2.0.0/clipboard.min.js" async data-options="{&quot;prop&quot;:true}"></script>", "postBodyTags": "<div>Test content</div> <script>window.alert(1);</script>", "preBodyTags": "<script type="text/javascript">window.foo = null;</script>", } `); }); it('allows multiple plugins that might/might not inject html tags', () => { const htmlTags = loadHtmlTags([ pluginEmpty, pluginHeadTags, pluginPostBodyTags, pluginMaybeInjectHeadTags, ]); expect(htmlTags).toMatchInlineSnapshot(` { "headTags": "<link rel="preconnect" href="www.google-analytics.com"> <meta name="generator" content="Docusaurus"> <script type="text/javascript" src="https://cdnjs.cloudflare.com/ajax/libs/clipboard.js/2.0.0/clipboard.min.js" async data-options="{&quot;prop&quot;:true}"></script>", "postBodyTags": "<div>Test content</div> <script>window.alert(1);</script>", "preBodyTags": "", } `); }); it('throws for invalid tag', () => { expect(() => loadHtmlTags([ // @ts-expect-error: test { injectHtmlTags() { return { headTags: { tagName: 'endiliey', attributes: { this: 'is invalid', }, }, }; }, }, ]), ).toThrowErrorMatchingInlineSnapshot( `"Error loading {"tagName":"endiliey","attributes":{"this":"is invalid"}}, "endiliey" is not a valid HTML tag."`, ); }); it('throws for invalid tagName', () => { expect(() => loadHtmlTags([ { // @ts-expect-error: test injectHtmlTags() { return { headTags: { tagName: true, }, }; }, }, ]), ).toThrowErrorMatchingInlineSnapshot( `"{"tagName":true} is not a valid HTML tag object. "tagName" must be defined as a string."`, ); }); it('throws for invalid tag object', () => { expect(() => loadHtmlTags([ { // @ts-expect-error: test injectHtmlTags() { return { headTags: 2, }; }, }, ]), ).toThrowErrorMatchingInlineSnapshot( `""2" is not a valid HTML tag object."`, ); }); });
2,207
0
petrpan-code/facebook/docusaurus/packages/docusaurus/src/server
petrpan-code/facebook/docusaurus/packages/docusaurus/src/server/__tests__/i18n.test.ts
/** * Copyright (c) Facebook, Inc. and its affiliates. * * This source code is licensed under the MIT license found in the * LICENSE file in the root directory of this source tree. */ import {jest} from '@jest/globals'; import {loadI18n, getDefaultLocaleConfig} from '../i18n'; import {DEFAULT_I18N_CONFIG} from '../configValidation'; import type {DocusaurusConfig, I18nConfig} from '@docusaurus/types'; function testLocaleConfigsFor(locales: string[]) { return Object.fromEntries( locales.map((locale) => [locale, getDefaultLocaleConfig(locale)]), ); } function loadI18nTest(i18nConfig: I18nConfig, locale?: string) { return loadI18n( { i18n: i18nConfig, } as DocusaurusConfig, {locale}, ); } describe('defaultLocaleConfig', () => { it('returns correct labels', () => { expect(getDefaultLocaleConfig('fr')).toEqual({ label: 'Français', direction: 'ltr', htmlLang: 'fr', calendar: 'gregory', path: 'fr', }); expect(getDefaultLocaleConfig('fr-FR')).toEqual({ label: 'Français (France)', direction: 'ltr', htmlLang: 'fr-FR', calendar: 'gregory', path: 'fr-FR', }); expect(getDefaultLocaleConfig('en')).toEqual({ label: 'English', direction: 'ltr', htmlLang: 'en', calendar: 'gregory', path: 'en', }); expect(getDefaultLocaleConfig('en-US')).toEqual({ label: 'American English', direction: 'ltr', htmlLang: 'en-US', calendar: 'gregory', path: 'en-US', }); expect(getDefaultLocaleConfig('zh')).toEqual({ label: '中文', direction: 'ltr', htmlLang: 'zh', calendar: 'gregory', path: 'zh', }); expect(getDefaultLocaleConfig('zh-CN')).toEqual({ label: '中文(中国)', direction: 'ltr', htmlLang: 'zh-CN', calendar: 'gregory', path: 'zh-CN', }); expect(getDefaultLocaleConfig('en-US')).toEqual({ label: 'American English', direction: 'ltr', htmlLang: 'en-US', calendar: 'gregory', path: 'en-US', }); expect(getDefaultLocaleConfig('fa')).toEqual({ // cSpell:ignore فارسی label: 'فارسی', direction: 'rtl', htmlLang: 'fa', calendar: 'gregory', path: 'fa', }); expect(getDefaultLocaleConfig('fa-IR')).toEqual({ // cSpell:ignore ایران فارسیا label: 'فارسی (ایران)', direction: 'rtl', htmlLang: 'fa-IR', calendar: 'gregory', path: 'fa-IR', }); expect(getDefaultLocaleConfig('en-US-u-ca-buddhist')).toEqual({ label: 'American English', direction: 'ltr', htmlLang: 'en-US-u-ca-buddhist', calendar: 'buddhist', path: 'en-US-u-ca-buddhist', }); }); }); describe('loadI18n', () => { const consoleSpy = jest.spyOn(console, 'warn').mockImplementation(() => {}); beforeEach(() => { consoleSpy.mockClear(); }); it('loads I18n for default config', async () => { await expect(loadI18nTest(DEFAULT_I18N_CONFIG)).resolves.toEqual({ path: 'i18n', defaultLocale: 'en', locales: ['en'], currentLocale: 'en', localeConfigs: testLocaleConfigsFor(['en']), }); }); it('loads I18n for multi-lang config', async () => { await expect( loadI18nTest({ path: 'i18n', defaultLocale: 'fr', locales: ['en', 'fr', 'de'], localeConfigs: {}, }), ).resolves.toEqual({ defaultLocale: 'fr', path: 'i18n', locales: ['en', 'fr', 'de'], currentLocale: 'fr', localeConfigs: testLocaleConfigsFor(['en', 'fr', 'de']), }); }); it('loads I18n for multi-locale config with specified locale', async () => { await expect( loadI18nTest( { path: 'i18n', defaultLocale: 'fr', locales: ['en', 'fr', 'de'], localeConfigs: {}, }, 'de', ), ).resolves.toEqual({ defaultLocale: 'fr', path: 'i18n', locales: ['en', 'fr', 'de'], currentLocale: 'de', localeConfigs: testLocaleConfigsFor(['en', 'fr', 'de']), }); }); it('loads I18n for multi-locale config with some custom locale configs', async () => { await expect( loadI18nTest( { path: 'i18n', defaultLocale: 'fr', locales: ['en', 'fr', 'de'], localeConfigs: { fr: {label: 'Français'}, en: {}, }, }, 'de', ), ).resolves.toEqual({ defaultLocale: 'fr', path: 'i18n', locales: ['en', 'fr', 'de'], currentLocale: 'de', localeConfigs: { fr: { label: 'Français', direction: 'ltr', htmlLang: 'fr', calendar: 'gregory', path: 'fr', }, en: getDefaultLocaleConfig('en'), de: getDefaultLocaleConfig('de'), }, }); }); it('warns when trying to load undeclared locale', async () => { await loadI18nTest( { path: 'i18n', defaultLocale: 'fr', locales: ['en', 'fr', 'de'], localeConfigs: {}, }, 'it', ); expect(consoleSpy.mock.calls[0]![0]).toMatch( /The locale .*it.* was not found in your site configuration/, ); }); });
2,208
0
petrpan-code/facebook/docusaurus/packages/docusaurus/src/server
petrpan-code/facebook/docusaurus/packages/docusaurus/src/server/__tests__/index.test.ts
/** * Copyright (c) Facebook, Inc. and its affiliates. * * This source code is licensed under the MIT license found in the * LICENSE file in the root directory of this source tree. */ import path from 'path'; import {mergeWithCustomize} from 'webpack-merge'; import {loadSetup} from './testUtils'; import type {Props} from '@docusaurus/types'; import type {DeepPartial} from 'utility-types'; describe('load', () => { it('loads props for site with custom i18n path', async () => { const props = await loadSetup('custom-i18n-site'); expect(props).toMatchSnapshot(); const props2 = await loadSetup('custom-i18n-site', {locale: 'zh-Hans'}); expect(props2).toEqual( mergeWithCustomize<DeepPartial<Props>>({ customizeArray(a, b, key) { return ['routesPaths', 'plugins'].includes(key) ? b : undefined; }, })(props, { baseUrl: '/zh-Hans/', i18n: { currentLocale: 'zh-Hans', }, localizationDir: path.join( __dirname, '__fixtures__/custom-i18n-site/i18n/zh-Hans-custom', ), outDir: path.join( __dirname, '__fixtures__/custom-i18n-site/build/zh-Hans', ), routesPaths: ['/zh-Hans/404.html'], siteConfig: { baseUrl: '/zh-Hans/', }, plugins: props2.plugins, }), ); }); });
2,209
0
petrpan-code/facebook/docusaurus/packages/docusaurus/src/server
petrpan-code/facebook/docusaurus/packages/docusaurus/src/server/__tests__/routes.test.ts
/** * Copyright (c) Facebook, Inc. and its affiliates. * * This source code is licensed under the MIT license found in the * LICENSE file in the root directory of this source tree. */ import {jest} from '@jest/globals'; import {loadRoutes, handleDuplicateRoutes, genChunkName} from '../routes'; import type {RouteConfig} from '@docusaurus/types'; describe('genChunkName', () => { it('works', () => { const firstAssert: {[key: string]: string} = { '/docs/adding-blog': 'docs-adding-blog-062', '/docs/versioning': 'docs-versioning-8a8', '/': 'index', '/blog/2018/04/30/How-I-Converted-Profilo-To-Docusaurus': 'blog-2018-04-30-how-i-converted-profilo-to-docusaurus-4f2', '/youtube': 'youtube-429', '/users/en/': 'users-en-f7a', '/blog': 'blog-c06', }; Object.keys(firstAssert).forEach((str) => { expect(genChunkName(str)).toBe(firstAssert[str]); }); }); it("doesn't allow different chunk name for same path", () => { expect(genChunkName('path/is/similar', 'oldPrefix')).toEqual( genChunkName('path/is/similar', 'newPrefix'), ); }); it('emits different chunk names for different paths even with same preferred name', () => { const secondAssert: {[key: string]: string} = { '/blog/1': 'blog-85-f-089', '/blog/2': 'blog-353-489', }; Object.keys(secondAssert).forEach((str) => { expect(genChunkName(str, undefined, 'blog')).toBe(secondAssert[str]); }); }); it('only generates short unique IDs', () => { const thirdAssert: {[key: string]: string} = { a: '0cc175b9', b: '92eb5ffe', c: '4a8a08f0', d: '8277e091', }; Object.keys(thirdAssert).forEach((str) => { expect(genChunkName(str, undefined, undefined, true)).toBe( thirdAssert[str], ); }); expect(genChunkName('d', undefined, undefined, true)).toBe('8277e091'); }); // https://github.com/facebook/docusaurus/issues/8536 it('avoids hash collisions', () => { expect( genChunkName( '@site/blog/2022-11-18-bye-medium/index.mdx?truncated=true', 'content', 'blog', false, ), ).not.toBe( genChunkName( '@site/blog/2019-10-05-react-nfc/index.mdx?truncated=true', 'content', 'blog', false, ), ); expect( genChunkName( '@site/blog/2022-11-18-bye-medium/index.mdx?truncated=true', 'content', 'blog', true, ), ).not.toBe( genChunkName( '@site/blog/2019-10-05-react-nfc/index.mdx?truncated=true', 'content', 'blog', true, ), ); }); }); describe('handleDuplicateRoutes', () => { const routes: RouteConfig[] = [ { path: '/', component: '', routes: [ {path: '/search', component: ''}, {path: '/sameDoc', component: ''}, ], }, { path: '/', component: '', routes: [ {path: '/search', component: ''}, {path: '/sameDoc', component: ''}, {path: '/uniqueDoc', component: ''}, ], }, { path: '/', component: '', }, { path: '/', component: '', }, { path: '/', component: '', }, ]; it('works', () => { expect(() => { handleDuplicateRoutes(routes, 'throw'); }).toThrowErrorMatchingSnapshot(); const consoleMock = jest.spyOn(console, 'log').mockImplementation(() => {}); handleDuplicateRoutes(routes, 'ignore'); expect(consoleMock).toHaveBeenCalledTimes(0); }); }); describe('loadRoutes', () => { it('loads nested route config', () => { const nestedRouteConfig: RouteConfig = { component: '@theme/DocRoot', path: '/docs:route', modules: { docsMetadata: 'docs-b5f.json', }, routes: [ { path: '/docs/hello', component: '@theme/DocItem', exact: true, modules: { content: 'docs/hello.md', metadata: 'docs-hello-da2.json', }, context: { plugin: 'pluginRouteContextModule-100.json', }, sidebar: 'main', }, { path: 'docs/foo/baz', component: '@theme/DocItem', modules: { content: 'docs/foo/baz.md', metadata: 'docs-foo-baz-dd9.json', }, context: { plugin: 'pluginRouteContextModule-100.json', }, sidebar: 'secondary', 'key:a': 'containing colon', "key'b": 'containing quote', 'key"c': 'containing double quote', 'key,d': 'containing comma', 字段: 'containing unicode', }, ], }; expect(loadRoutes([nestedRouteConfig], '/', 'ignore')).toMatchSnapshot(); }); it('loads flat route config', () => { const flatRouteConfig: RouteConfig = { path: '/blog', component: '@theme/BlogListPage', exact: true, modules: { items: [ { content: { __import: true, path: 'blog/2018-12-14-Happy-First-Birthday-Slash.md', query: { truncated: true, }, }, metadata: 'blog-2018-12-14-happy-first-birthday-slash-d2c.json', }, { content: 'blog/2018-12-14-Happy-First-Birthday-Slash.md', }, { content: { __import: true, path: 'blog/2018-12-14-Happy-First-Birthday-Slash.md', }, }, ], }, }; expect(loadRoutes([flatRouteConfig], '/', 'ignore')).toMatchSnapshot(); }); it('rejects invalid route config', () => { const routeConfigWithoutPath = { component: 'hello/world.js', } as RouteConfig; expect(() => loadRoutes([routeConfigWithoutPath], '/', 'ignore')) .toThrowErrorMatchingInlineSnapshot(` "Invalid route config: path must be a string and component is required. {"component":"hello/world.js"}" `); const routeConfigWithoutComponent = { path: '/hello/world', } as RouteConfig; expect(() => loadRoutes([routeConfigWithoutComponent], '/', 'ignore')) .toThrowErrorMatchingInlineSnapshot(` "Invalid route config: path must be a string and component is required. {"path":"/hello/world"}" `); }); it('loads route config with empty (but valid) path string', () => { const routeConfig = { path: '', component: 'hello/world.js', } as RouteConfig; expect(loadRoutes([routeConfig], '/', 'ignore')).toMatchSnapshot(); }); });
2,210
0
petrpan-code/facebook/docusaurus/packages/docusaurus/src/server
petrpan-code/facebook/docusaurus/packages/docusaurus/src/server/__tests__/siteMetadata.test.ts
/** * Copyright (c) Facebook, Inc. and its affiliates. * * This source code is licensed under the MIT license found in the * LICENSE file in the root directory of this source tree. */ import path from 'path'; import {DOCUSAURUS_VERSION} from '@docusaurus/utils'; import {getPluginVersion, loadSiteMetadata} from '../siteMetadata'; import type {LoadedPlugin} from '@docusaurus/types'; describe('getPluginVersion', () => { it('detects external packages plugins versions', async () => { await expect( getPluginVersion( path.join(__dirname, '__fixtures__/siteMetadata/dummy-plugin.js'), // Make the plugin appear external. path.join(__dirname, '..', '..', '..', '..', '..', '..', 'website'), ), ).resolves.toEqual({type: 'package', version: 'random-version'}); }); it('detects project plugins versions', async () => { await expect( getPluginVersion( path.join(__dirname, '__fixtures__/siteMetadata/dummy-plugin.js'), // Make the plugin appear project local. path.join(__dirname, '__fixtures__/siteMetadata'), ), ).resolves.toEqual({type: 'project'}); }); it('detects local packages versions', async () => { await expect(getPluginVersion('/', '/')).resolves.toEqual({type: 'local'}); }); }); describe('loadSiteMetadata', () => { it('throws if plugin versions mismatch', async () => { await expect( loadSiteMetadata({ plugins: [ { name: 'docusaurus-plugin-content-docs', version: { type: 'package', version: '1.0.0', name: '@docusaurus/plugin-content-docs', }, }, ] as LoadedPlugin[], siteDir: path.join(__dirname, '__fixtures__/siteMetadata'), }), ).rejects .toThrow(`Invalid name=docusaurus-plugin-content-docs version number=1.0.0. All official @docusaurus/* packages should have the exact same version as @docusaurus/core (number=${DOCUSAURUS_VERSION}). Maybe you want to check, or regenerate your yarn.lock or package-lock.json file?`); }); });
2,212
0
petrpan-code/facebook/docusaurus/packages/docusaurus/src/server
petrpan-code/facebook/docusaurus/packages/docusaurus/src/server/__tests__/utils.test.ts
/** * Copyright (c) Facebook, Inc. and its affiliates. * * This source code is licensed under the MIT license found in the * LICENSE file in the root directory of this source tree. */ import {getAllFinalRoutes} from '../utils'; import type {RouteConfig} from '@docusaurus/types'; describe('getAllFinalRoutes', () => { it('gets final routes correctly', () => { const routes: RouteConfig[] = [ { path: '/docs', component: '', routes: [ {path: '/docs/someDoc', component: ''}, {path: '/docs/someOtherDoc', component: ''}, ], }, { path: '/community', component: '', }, ]; expect(getAllFinalRoutes(routes)).toEqual([ routes[0]!.routes![0], routes[0]!.routes![1], routes[1], ]); }); });
2,247
0
petrpan-code/facebook/docusaurus/packages/docusaurus/src/server/__tests__
petrpan-code/facebook/docusaurus/packages/docusaurus/src/server/__tests__/__snapshots__/brokenLinks.test.ts.snap
// Jest Snapshot v1, https://goo.gl/fbAQLP exports[`handleBrokenLinks reports all broken links 1`] = ` "Docusaurus found broken links! Please check the pages of your site in the list below, and make sure you don't reference any path that does not exist. Note: it's possible to ignore broken links with the 'onBrokenLinks' Docusaurus configuration, and let the build pass. Exhaustive list of all broken links found: - On source page path = /docs/good doc with space: -> linking to ./some%20other%20non-existent%20doc1 (resolved as: /docs/some%20other%20non-existent%20doc1) -> linking to ./break%2F..%2F..%2Fout2 (resolved as: /docs/break%2F..%2F..%2Fout2) - On source page path = /docs/goodDoc: -> linking to ../anotherGoodDoc#reported-because-of-bad-relative-path1 (resolved as: /anotherGoodDoc) -> linking to ./docThatDoesNotExist2 (resolved as: /docs/docThatDoesNotExist2) -> linking to ./badRelativeLink3 (resolved as: /docs/badRelativeLink3) -> linking to ../badRelativeLink4 (resolved as: /badRelativeLink4) - On source page path = /community: -> linking to /someNonExistentDoc1 -> linking to /badLink2 -> linking to ./badLink3 (resolved as: /badLink3) - On source page path = /page1: -> linking to /link1 -> linking to /emptyFolder - On source page path = /page2: -> linking to /docs/link2 -> linking to /emptyFolder/ -> linking to /hey/link3 " `; exports[`handleBrokenLinks reports frequent broken links 1`] = ` "Docusaurus found broken links! Please check the pages of your site in the list below, and make sure you don't reference any path that does not exist. Note: it's possible to ignore broken links with the 'onBrokenLinks' Docusaurus configuration, and let the build pass. It looks like some of the broken links we found appear in many pages of your site. Maybe those broken links appear on all pages through your site layout? We recommend that you check your theme configuration for such links (particularly, theme navbar and footer). Frequent broken links are linking to: - /frequent - ./maybe-not Exhaustive list of all broken links found: - On source page path = /docs/good doc with space: -> linking to ./some%20other%20non-existent%20doc1 (resolved as: /docs/some%20other%20non-existent%20doc1) -> linking to ./break%2F..%2F..%2Fout2 (resolved as: /docs/break%2F..%2F..%2Fout2) -> linking to /frequent -> linking to ./maybe-not (resolved as: /docs/maybe-not) - On source page path = /docs/goodDoc: -> linking to ../anotherGoodDoc#reported-because-of-bad-relative-path1 (resolved as: /anotherGoodDoc) -> linking to ./docThatDoesNotExist2 (resolved as: /docs/docThatDoesNotExist2) -> linking to ./badRelativeLink3 (resolved as: /docs/badRelativeLink3) -> linking to ../badRelativeLink4 (resolved as: /badRelativeLink4) -> linking to /frequent -> linking to ./maybe-not (resolved as: /docs/maybe-not) - On source page path = /community: -> linking to /someNonExistentDoc1 -> linking to /badLink2 -> linking to ./badLink3 (resolved as: /badLink3) -> linking to /frequent -> linking to ./maybe-not (resolved as: /maybe-not) - On source page path = /page1: -> linking to /link1 -> linking to /emptyFolder -> linking to /frequent -> linking to ./maybe-not (resolved as: /maybe-not) - On source page path = /page2: -> linking to /docs/link2 -> linking to /emptyFolder/ -> linking to /hey/link3 -> linking to /frequent -> linking to ./maybe-not (resolved as: /maybe-not) " `;