From df431be94e09017b048cff95e1a523d360345f47 Mon Sep 17 00:00:00 2001 From: Joshua Chen Date: Wed, 25 May 2022 11:09:25 +0800 Subject: [PATCH] test: fix some type errors in test files --- jest/deps.d.ts | 17 ++++ .../remark/headings/__tests__/index.test.ts | 2 +- .../transformLinks/__tests__/index.test.ts | 10 +- .../src/__tests__/options.test.ts | 2 +- .../src/__tests__/writeRedirectFiles.test.ts | 6 +- .../src/options.ts | 2 +- .../src/__tests__/blogUtils.test.ts | 4 + .../src/__tests__/feed.test.ts | 3 + .../src/__tests__/frontMatter.test.ts | 4 +- .../src/__tests__/index.test.ts | 25 +++-- .../src/__tests__/options.test.ts | 8 +- .../src/__tests__/translations.test.ts | 3 + .../src/options.ts | 2 +- .../remark/__tests__/footnoteIDFixer.test.ts | 2 +- .../src/__tests__/cli.test.ts | Bin 11378 -> 11753 bytes .../src/__tests__/frontMatter.test.ts | 4 +- .../src/__tests__/globalData.test.ts | 10 +- .../src/__tests__/index.test.ts | 92 ++++++++++++------ .../src/__tests__/options.test.ts | 27 +++-- .../src/__tests__/props.test.ts | 16 +-- .../src/plugin-content-docs.d.ts | 19 +++- .../src/sidebars/__tests__/utils.test.ts | 15 +-- .../src/versions/__tests__/index.test.ts | 8 +- .../src/__tests__/createSitemap.test.ts | 5 +- .../src/__tests__/options.test.ts | 4 +- .../src/__tests__/translations.test.ts | 4 +- .../src/__tests__/validateThemeConfig.test.ts | 2 +- .../src/theme-classic.d.ts | 6 +- .../src/theme/Tabs/index.tsx | 2 +- .../src/utils/__tests__/docsUtils.test.tsx | 34 ++++--- .../utils/__tests__/usePluralForm.test.tsx | 8 +- .../src/__tests__/index.test.ts | 1 + .../src/__tests__/jsUtils.test.ts | 10 +- .../src/__tests__/webpackUtils.test.ts | 2 +- .../src/client/__tests__/flat.test.ts | 2 +- .../__tests__/normalizeLocation.test.ts | 19 ++-- .../exports/__tests__/Interpolate.test.tsx | 6 +- .../exports/__tests__/useBaseUrl.test.tsx | 8 +- .../server/plugins/__tests__/index.test.ts | 4 +- .../src/server/plugins/__tests__/init.test.ts | 16 +-- .../plugins/__tests__/pluginIds.test.ts | 7 +- .../server/plugins/__tests__/presets.test.ts | 6 +- .../__tests__/translations.test.ts | 14 ++- .../__tests__/translationsExtractor.test.ts | 4 +- .../src/webpack/__tests__/base.test.ts | 4 +- .../src/webpack/__tests__/server.test.ts | 12 ++- .../src/webpack/__tests__/utils.test.ts | 19 ++-- .../__tests__/no-untranslated-text.test.ts | 9 +- .../string-literal-i18n-messages.test.ts | 8 +- 49 files changed, 314 insertions(+), 183 deletions(-) create mode 100644 jest/deps.d.ts diff --git a/jest/deps.d.ts b/jest/deps.d.ts new file mode 100644 index 0000000000000..a0694f5b81282 --- /dev/null +++ b/jest/deps.d.ts @@ -0,0 +1,17 @@ +/** + * 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. + */ + +// modules only used in tests + +declare module 'to-vfile'; + +declare module 'remark-mdx'; + +declare module '@testing-utils/git' { + const createTempRepo: typeof import('./utils/git').createTempRepo; + export {createTempRepo}; +} diff --git a/packages/docusaurus-mdx-loader/src/remark/headings/__tests__/index.test.ts b/packages/docusaurus-mdx-loader/src/remark/headings/__tests__/index.test.ts index 2d5ba57c2b780..47a31c836fc80 100644 --- a/packages/docusaurus-mdx-loader/src/remark/headings/__tests__/index.test.ts +++ b/packages/docusaurus-mdx-loader/src/remark/headings/__tests__/index.test.ts @@ -21,7 +21,7 @@ function process(doc: string, plugins: Plugin[] = []) { return removePosition(processor.runSync(processor.parse(doc)), true); } -function heading(label: string, id: string) { +function heading(label: string | null, id: string) { return u( 'heading', {depth: 2, data: {id, hProperties: {id}}}, diff --git a/packages/docusaurus-mdx-loader/src/remark/transformLinks/__tests__/index.test.ts b/packages/docusaurus-mdx-loader/src/remark/transformLinks/__tests__/index.test.ts index e4511f8274842..181ddd4f73153 100644 --- a/packages/docusaurus-mdx-loader/src/remark/transformLinks/__tests__/index.test.ts +++ b/packages/docusaurus-mdx-loader/src/remark/transformLinks/__tests__/index.test.ts @@ -13,15 +13,15 @@ import plugin from '..'; import transformImage, {type PluginOptions} from '../../transformImage'; const processFixture = async (name: string, options?: PluginOptions) => { - const filePath = path.join(__dirname, `__fixtures__/${name}.md`); + const siteDir = path.join(__dirname, `__fixtures__`); const staticDirs = [ - path.join(__dirname, '__fixtures__/static'), - path.join(__dirname, '__fixtures__/static2'), + path.join(siteDir, 'static'), + path.join(siteDir, 'static2'), ]; - const file = await vfile.read(filePath); + const file = await vfile.read(path.join(siteDir, `${name}.md`)); const result = await remark() .use(mdx) - .use(transformImage, {...options, filePath, staticDirs}) + .use(transformImage, {...options, siteDir, staticDirs}) .use(plugin, { ...options, staticDirs, diff --git a/packages/docusaurus-plugin-client-redirects/src/__tests__/options.test.ts b/packages/docusaurus-plugin-client-redirects/src/__tests__/options.test.ts index 1d526c351b4d7..6ef2c84d49859 100644 --- a/packages/docusaurus-plugin-client-redirects/src/__tests__/options.test.ts +++ b/packages/docusaurus-plugin-client-redirects/src/__tests__/options.test.ts @@ -9,7 +9,7 @@ import {normalizePluginOptions} from '@docusaurus/utils-validation'; import {validateOptions, DEFAULT_OPTIONS} from '../options'; import type {Options} from '../options'; -function testValidate(options: Options) { +function testValidate(options?: Options) { return validateOptions({validate: normalizePluginOptions, options}); } diff --git a/packages/docusaurus-plugin-client-redirects/src/__tests__/writeRedirectFiles.test.ts b/packages/docusaurus-plugin-client-redirects/src/__tests__/writeRedirectFiles.test.ts index 2ed5d2f1a1b12..32b992c08650f 100644 --- a/packages/docusaurus-plugin-client-redirects/src/__tests__/writeRedirectFiles.test.ts +++ b/packages/docusaurus-plugin-client-redirects/src/__tests__/writeRedirectFiles.test.ts @@ -176,11 +176,11 @@ describe('writeRedirectFiles', () => { await writeRedirectFiles(filesMetadata); await expect( - fs.readFile(filesMetadata[0].fileAbsolutePath, 'utf8'), + fs.readFile(filesMetadata[0]!.fileAbsolutePath, 'utf8'), ).resolves.toBe('content 1'); await expect( - fs.readFile(filesMetadata[1].fileAbsolutePath, 'utf8'), + fs.readFile(filesMetadata[1]!.fileAbsolutePath, 'utf8'), ).resolves.toBe('content 2'); }); @@ -195,7 +195,7 @@ describe('writeRedirectFiles', () => { ]; await fs.outputFile( - filesMetadata[0].fileAbsolutePath, + filesMetadata[0]!.fileAbsolutePath, 'file already exists!', ); diff --git a/packages/docusaurus-plugin-client-redirects/src/options.ts b/packages/docusaurus-plugin-client-redirects/src/options.ts index 72f3da3010bd6..389e90b958aaf 100644 --- a/packages/docusaurus-plugin-client-redirects/src/options.ts +++ b/packages/docusaurus-plugin-client-redirects/src/options.ts @@ -66,6 +66,6 @@ const UserOptionsSchema = Joi.object({ export function validateOptions({ validate, options: userOptions, -}: OptionValidationContext): PluginOptions { +}: OptionValidationContext): PluginOptions { return validate(UserOptionsSchema, userOptions); } diff --git a/packages/docusaurus-plugin-content-blog/src/__tests__/blogUtils.test.ts b/packages/docusaurus-plugin-content-blog/src/__tests__/blogUtils.test.ts index 1d9cafef920f0..2adc44ca9831f 100644 --- a/packages/docusaurus-plugin-content-blog/src/__tests__/blogUtils.test.ts +++ b/packages/docusaurus-plugin-content-blog/src/__tests__/blogUtils.test.ts @@ -211,7 +211,11 @@ describe('linkify', () => { title: 'date-matter', }, truncated: false, + frontMatter: {}, + authors: [], + formattedDate: '', }, + content: '', }, ]; diff --git a/packages/docusaurus-plugin-content-blog/src/__tests__/feed.test.ts b/packages/docusaurus-plugin-content-blog/src/__tests__/feed.test.ts index 2e5d96872dfef..d7747d16300c6 100644 --- a/packages/docusaurus-plugin-content-blog/src/__tests__/feed.test.ts +++ b/packages/docusaurus-plugin-content-blog/src/__tests__/feed.test.ts @@ -21,6 +21,9 @@ const DefaultI18N: I18n = { defaultLocale: 'en', localeConfigs: { en: { + label: 'English', + direction: 'ltr', + htmlLang: 'en', calendar: 'gregory', }, }, diff --git a/packages/docusaurus-plugin-content-blog/src/__tests__/frontMatter.test.ts b/packages/docusaurus-plugin-content-blog/src/__tests__/frontMatter.test.ts index 36cc680df0e04..7d769afe3f696 100644 --- a/packages/docusaurus-plugin-content-blog/src/__tests__/frontMatter.test.ts +++ b/packages/docusaurus-plugin-content-blog/src/__tests__/frontMatter.test.ts @@ -56,7 +56,9 @@ function testField(params: { ); } catch (err) { // eslint-disable-next-line jest/no-conditional-expect - expect(err.message).toMatch(new RegExp(escapeStringRegexp(message))); + expect((err as Error).message).toMatch( + new RegExp(escapeStringRegexp(message)), + ); } }); }); diff --git a/packages/docusaurus-plugin-content-blog/src/__tests__/index.test.ts b/packages/docusaurus-plugin-content-blog/src/__tests__/index.test.ts index 384b7014c7ea3..0c49808e9c33e 100644 --- a/packages/docusaurus-plugin-content-blog/src/__tests__/index.test.ts +++ b/packages/docusaurus-plugin-content-blog/src/__tests__/index.test.ts @@ -41,7 +41,14 @@ function getI18n(locale: string): I18n { currentLocale: locale, locales: [locale], defaultLocale: locale, - localeConfigs: {[locale]: {calendar: 'gregory'}}, + localeConfigs: { + [locale]: { + calendar: 'gregory', + label: locale, + htmlLang: locale, + direction: 'ltr', + }, + }, }; } @@ -297,28 +304,28 @@ describe('blog plugin', () => { const siteDir = path.join(__dirname, '__fixtures__', 'website'); const blogPostsFrench = await getBlogPosts(siteDir, {}, getI18n('fr')); expect(blogPostsFrench).toHaveLength(8); - expect(blogPostsFrench[0].metadata.formattedDate).toMatchInlineSnapshot( + expect(blogPostsFrench[0]!.metadata.formattedDate).toMatchInlineSnapshot( `"6 mars 2021"`, ); - expect(blogPostsFrench[1].metadata.formattedDate).toMatchInlineSnapshot( + expect(blogPostsFrench[1]!.metadata.formattedDate).toMatchInlineSnapshot( `"5 mars 2021"`, ); - expect(blogPostsFrench[2].metadata.formattedDate).toMatchInlineSnapshot( + expect(blogPostsFrench[2]!.metadata.formattedDate).toMatchInlineSnapshot( `"16 août 2020"`, ); - expect(blogPostsFrench[3].metadata.formattedDate).toMatchInlineSnapshot( + expect(blogPostsFrench[3]!.metadata.formattedDate).toMatchInlineSnapshot( `"15 août 2020"`, ); - expect(blogPostsFrench[4].metadata.formattedDate).toMatchInlineSnapshot( + expect(blogPostsFrench[4]!.metadata.formattedDate).toMatchInlineSnapshot( `"27 février 2020"`, ); - expect(blogPostsFrench[5].metadata.formattedDate).toMatchInlineSnapshot( + expect(blogPostsFrench[5]!.metadata.formattedDate).toMatchInlineSnapshot( `"2 janvier 2019"`, ); - expect(blogPostsFrench[6].metadata.formattedDate).toMatchInlineSnapshot( + expect(blogPostsFrench[6]!.metadata.formattedDate).toMatchInlineSnapshot( `"1 janvier 2019"`, ); - expect(blogPostsFrench[7].metadata.formattedDate).toMatchInlineSnapshot( + expect(blogPostsFrench[7]!.metadata.formattedDate).toMatchInlineSnapshot( `"14 décembre 2018"`, ); }); diff --git a/packages/docusaurus-plugin-content-blog/src/__tests__/options.test.ts b/packages/docusaurus-plugin-content-blog/src/__tests__/options.test.ts index dd2e562bdabc6..61f0da6c99c0b 100644 --- a/packages/docusaurus-plugin-content-blog/src/__tests__/options.test.ts +++ b/packages/docusaurus-plugin-content-blog/src/__tests__/options.test.ts @@ -9,7 +9,7 @@ import {normalizePluginOptions} from '@docusaurus/utils-validation'; import {validateOptions, DEFAULT_OPTIONS} from '../options'; import type {Options} from '@docusaurus/plugin-content-blog'; -function testValidate(options: Options) { +function testValidate(options?: Options) { return validateOptions({validate: normalizePluginOptions, options}); } @@ -44,13 +44,14 @@ describe('validateOptions', () => { }); it('accepts valid user options', () => { - const userOptions = { + const userOptions: Options = { ...defaultOptions, routeBasePath: 'myBlog', beforeDefaultRemarkPlugins: [], beforeDefaultRehypePlugins: [markdownPluginsFunctionStub], remarkPlugins: [[markdownPluginsFunctionStub, {option1: '42'}]], rehypePlugins: [ + // @ts-expect-error: it seems to work in practice markdownPluginsObjectStub, [markdownPluginsFunctionStub, {option1: '42'}], ], @@ -73,6 +74,7 @@ describe('validateOptions', () => { expect(() => testValidate({ feedOptions: { + // @ts-expect-error: test type: 'none', }, }), @@ -138,6 +140,7 @@ describe('validateOptions', () => { it('rejects "abcdef" sidebar count', () => { const userOptions = {blogSidebarCount: 'abcdef'}; + // @ts-expect-error: test expect(() => testValidate(userOptions)).toThrowErrorMatchingInlineSnapshot( `""blogSidebarCount" must be one of [ALL, number]"`, ); @@ -153,6 +156,7 @@ describe('validateOptions', () => { it('rejects 42 sidebar title', () => { const userOptions = {blogSidebarTitle: 42}; + // @ts-expect-error: test expect(() => testValidate(userOptions)).toThrowErrorMatchingInlineSnapshot( `""blogSidebarTitle" must be a string"`, ); diff --git a/packages/docusaurus-plugin-content-blog/src/__tests__/translations.test.ts b/packages/docusaurus-plugin-content-blog/src/__tests__/translations.test.ts index a29ae6e3acb76..5056da9482155 100644 --- a/packages/docusaurus-plugin-content-blog/src/__tests__/translations.test.ts +++ b/packages/docusaurus-plugin-content-blog/src/__tests__/translations.test.ts @@ -33,7 +33,10 @@ const sampleBlogPosts: BlogPost[] = [ tags: [], title: 'Hello', truncated: true, + authors: [], + frontMatter: {}, }, + content: '', }, ]; diff --git a/packages/docusaurus-plugin-content-blog/src/options.ts b/packages/docusaurus-plugin-content-blog/src/options.ts index ff06c867dc9d9..0375aba578e3c 100644 --- a/packages/docusaurus-plugin-content-blog/src/options.ts +++ b/packages/docusaurus-plugin-content-blog/src/options.ts @@ -135,7 +135,7 @@ const PluginOptionSchema = Joi.object({ export function validateOptions({ validate, options, -}: OptionValidationContext): PluginOptions { +}: OptionValidationContext): PluginOptions { const validatedOptions = validate(PluginOptionSchema, options); return validatedOptions; } diff --git a/packages/docusaurus-plugin-content-blog/src/remark/__tests__/footnoteIDFixer.test.ts b/packages/docusaurus-plugin-content-blog/src/remark/__tests__/footnoteIDFixer.test.ts index 2890766350c94..1c757047444b2 100644 --- a/packages/docusaurus-plugin-content-blog/src/remark/__tests__/footnoteIDFixer.test.ts +++ b/packages/docusaurus-plugin-content-blog/src/remark/__tests__/footnoteIDFixer.test.ts @@ -13,7 +13,7 @@ import footnoteIDFixer from '../footnoteIDFixer'; const processFixture = async (name: string) => { const filepath = path.join(__dirname, `__fixtures__/${name}.md`); - const result = await mdx(await fs.readFile(filepath), { + const result = await mdx(await fs.readFile(filepath, 'utf8'), { filepath, remarkPlugins: [footnoteIDFixer], }); diff --git a/packages/docusaurus-plugin-content-docs/src/__tests__/cli.test.ts b/packages/docusaurus-plugin-content-docs/src/__tests__/cli.test.ts index 55c50ab0cddf930ca37a38e3b431cfad218d6b70..194ce3c4e46e20344c3dc2a7f279d59ada8235f0 100644 GIT binary patch delta 650 zcmewq@iKaY4wFG4b%_z1H9+SDPtM?J z#3>id`vr?l!INk4?Zzs;f`1!U@r?rSu!!4EULee|`H5gXHdotjULYLE$f!8^qlh|? zyd`rGNY0j(;!?CyD9y{x%P-HHoTwT)Sy*oN6v-{1tppJdBu}MnQJCL0^;}VVvMzu4LM~e^YbZ8 zzQl3_&VIx?7e&@=GbcMMBT(9Yatz0@&4!%bAPz{M+2(s(ml#nLn@_gpZ9s@@=I7Ib ztDZcYe>Y6$ { it('generates the right docs, sidebars, and metadata', () => { @@ -25,7 +26,7 @@ describe('toGlobalDataVersion', () => { sidebar: 'tutorial', frontMatter: {}, }, - ]; + ] as DocMetadata[]; const sidebars: Sidebars = { tutorial: [ { @@ -46,6 +47,8 @@ describe('toGlobalDataVersion', () => { id: 'doc', }, ], + collapsed: false, + collapsible: true, }, ], links: [ @@ -75,6 +78,8 @@ describe('toGlobalDataVersion', () => { id: 'doc', }, ], + collapsed: false, + collapsible: true, }, ], }; @@ -85,7 +90,6 @@ describe('toGlobalDataVersion', () => { label: 'Label', isLast: true, path: '/current', - mainDocId: 'main', docs, drafts: [ { @@ -93,7 +97,7 @@ describe('toGlobalDataVersion', () => { permalink: '/current/draft', sidebar: undefined, }, - ], + ] as DocMetadata[], sidebars, categoryGeneratedIndices: getCategoryGeneratedIndexMetadataList({ docs, diff --git a/packages/docusaurus-plugin-content-docs/src/__tests__/index.test.ts b/packages/docusaurus-plugin-content-docs/src/__tests__/index.test.ts index fd25cc85eef97..2f83e3f0b576e 100644 --- a/packages/docusaurus-plugin-content-docs/src/__tests__/index.test.ts +++ b/packages/docusaurus-plugin-content-docs/src/__tests__/index.test.ts @@ -26,13 +26,28 @@ import * as cliDocs from '../cli'; import {validateOptions} from '../options'; import type {RouteConfig} from '@docusaurus/types'; -import type {LoadedVersion} from '@docusaurus/plugin-content-docs'; -import type {SidebarItem, SidebarItemsGeneratorOption} from '../sidebars/types'; - -function findDocById(version: LoadedVersion, unversionedId: string) { +import type { + LoadedVersion, + PropSidebarItemLink, +} from '@docusaurus/plugin-content-docs'; +import type { + SidebarItemsGeneratorOption, + NormalizedSidebar, +} from '../sidebars/types'; + +function findDocById( + version: LoadedVersion | undefined, + unversionedId: string, +) { + if (!version) { + throw new Error('Version not found'); + } return version.docs.find((item) => item.unversionedId === unversionedId); } -function getDocById(version: LoadedVersion, unversionedId: string) { +function getDocById(version: LoadedVersion | undefined, unversionedId: string) { + if (!version) { + throw new Error('Version not found'); + } const doc = findDocById(version, unversionedId); if (!doc) { throw new Error( @@ -83,7 +98,10 @@ Entries created: getGlobalData: () => globalDataContainer, getRouteConfigs: () => routeConfigs, - checkVersionMetadataPropCreated: (version: LoadedVersion) => { + checkVersionMetadataPropCreated: (version: LoadedVersion | undefined) => { + if (!version) { + throw new Error('Version not found'); + } const versionMetadataProp = getCreatedDataByPrefix( `version-${_.kebabCase(version.versionName)}-metadata-prop`, ); @@ -164,7 +182,7 @@ describe('sidebar', () => { const result = await plugin.loadContent!(); expect(result.loadedVersions).toHaveLength(1); - expect(result.loadedVersions[0].sidebars).toMatchSnapshot(); + expect(result.loadedVersions[0]!.sidebars).toMatchSnapshot(); }); it('site with disabled sidebar', async () => { @@ -182,7 +200,7 @@ describe('sidebar', () => { const result = await plugin.loadContent!(); expect(result.loadedVersions).toHaveLength(1); - expect(result.loadedVersions[0].sidebars).toEqual(DisabledSidebars); + expect(result.loadedVersions[0]!.sidebars).toEqual(DisabledSidebars); }); }); @@ -309,7 +327,7 @@ describe('simple website', () => { expect(getDocById(currentVersion, 'foo/bar')).toMatchSnapshot(); - expect(currentVersion.sidebars).toMatchSnapshot(); + expect(currentVersion!.sidebars).toMatchSnapshot(); const {actions, utils} = createFakeActions(pluginContentDir); @@ -427,10 +445,12 @@ describe('versioned website', () => { expect(getDocById(version101, 'hello')).toMatchSnapshot(); expect(getDocById(version100, 'foo/baz')).toMatchSnapshot(); - expect(currentVersion.sidebars).toMatchSnapshot('current version sidebars'); - expect(version101.sidebars).toMatchSnapshot('101 version sidebars'); - expect(version100.sidebars).toMatchSnapshot('100 version sidebars'); - expect(versionWithSlugs.sidebars).toMatchSnapshot( + expect(currentVersion!.sidebars).toMatchSnapshot( + 'current version sidebars', + ); + expect(version101!.sidebars).toMatchSnapshot('101 version sidebars'); + expect(version100!.sidebars).toMatchSnapshot('100 version sidebars'); + expect(versionWithSlugs!.sidebars).toMatchSnapshot( 'withSlugs version sidebars', ); @@ -534,8 +554,10 @@ describe('versioned website (community)', () => { expect(getDocById(currentVersion, 'team')).toMatchSnapshot(); expect(getDocById(version100, 'team')).toMatchSnapshot(); - expect(currentVersion.sidebars).toMatchSnapshot('current version sidebars'); - expect(version100.sidebars).toMatchSnapshot('100 version sidebars'); + expect(currentVersion!.sidebars).toMatchSnapshot( + 'current version sidebars', + ); + expect(version100!.sidebars).toMatchSnapshot('100 version sidebars'); const {actions, utils} = createFakeActions(pluginContentDir); await plugin.contentLoaded!({ @@ -544,8 +566,8 @@ describe('versioned website (community)', () => { allContent: {}, }); - utils.checkVersionMetadataPropCreated(currentVersion); - utils.checkVersionMetadataPropCreated(version100); + utils.checkVersionMetadataPropCreated(currentVersion!); + utils.checkVersionMetadataPropCreated(version100!); utils.expectSnapshot(); }); @@ -574,18 +596,22 @@ describe('site with doc label', () => { it('label in sidebar.json is used', async () => { const {content} = await loadSite(); - const loadedVersion = content.loadedVersions[0]; + const loadedVersion = content.loadedVersions[0]!; const sidebarProps = toSidebarsProp(loadedVersion); - expect(sidebarProps.docs[0].label).toBe('Hello One'); + expect((sidebarProps.docs![0] as PropSidebarItemLink).label).toBe( + 'Hello One', + ); }); it('sidebar_label in doc has higher precedence over label in sidebar.json', async () => { const {content} = await loadSite(); - const loadedVersion = content.loadedVersions[0]; + const loadedVersion = content.loadedVersions[0]!; const sidebarProps = toSidebarsProp(loadedVersion); - expect(sidebarProps.docs[1].label).toBe('Hello 2 From Doc'); + expect((sidebarProps.docs![1] as PropSidebarItemLink).label).toBe( + 'Hello 2 From Doc', + ); }); }); @@ -614,14 +640,14 @@ describe('site with full autogenerated sidebar', () => { it('sidebar is fully autogenerated', async () => { const {content} = await loadSite(); - const version = content.loadedVersions[0]; + const version = content.loadedVersions[0]!; expect(version.sidebars).toMatchSnapshot(); }); it('docs in fully generated sidebar have correct metadata', async () => { const {content} = await loadSite(); - const version = content.loadedVersions[0]; + const version = content.loadedVersions[0]!; expect(getDocById(version, 'getting-started')).toMatchSnapshot(); expect(getDocById(version, 'installation')).toMatchSnapshot(); @@ -675,14 +701,14 @@ describe('site with partial autogenerated sidebars', () => { it('sidebar is partially autogenerated', async () => { const {content} = await loadSite(); - const version = content.loadedVersions[0]; + const version = content.loadedVersions[0]!; expect(version.sidebars).toMatchSnapshot(); }); it('docs in partially generated sidebar have correct metadata', async () => { const {content} = await loadSite(); - const version = content.loadedVersions[0]; + const version = content.loadedVersions[0]!; // Only looking at the docs of the autogen sidebar, others metadata should // not be affected @@ -731,7 +757,7 @@ describe('site with partial autogenerated sidebars 2 (fix #4638)', () => { it('sidebar is partially autogenerated', async () => { const {content} = await loadSite(); - const version = content.loadedVersions[0]; + const version = content.loadedVersions[0]!; expect(version.sidebars).toMatchSnapshot(); }); @@ -763,8 +789,10 @@ describe('site with custom sidebar items generator', () => { const customSidebarItemsGeneratorMock = jest.fn(async () => []); const {siteDir} = await loadSite(customSidebarItemsGeneratorMock); - const generatorArg: Parameters[0] = - customSidebarItemsGeneratorMock.mock.calls[0][0]; + const generatorArg = ( + customSidebarItemsGeneratorMock.mock + .calls[0] as unknown as Parameters + )[0]; // Make test pass even if docs are in different order and paths are // absolutes @@ -797,12 +825,12 @@ describe('site with custom sidebar items generator', () => { const {content} = await loadSite(customSidebarItemsGenerator); const version = content.loadedVersions[0]; - expect(version.sidebars).toMatchSnapshot(); + expect(version!.sidebars).toMatchSnapshot(); }); it('sidebarItemsGenerator can wrap/enhance/sort/reverse the default sidebar generator', async () => { - function reverseSidebarItems(items: SidebarItem[]): SidebarItem[] { - const result: SidebarItem[] = items.map((item) => { + function reverseSidebarItems(items: NormalizedSidebar): NormalizedSidebar { + const result: NormalizedSidebar = items.map((item) => { if (item.type === 'category') { return {...item, items: reverseSidebarItems(item.items)}; } @@ -821,7 +849,7 @@ describe('site with custom sidebar items generator', () => { }; const {content} = await loadSite(reversedSidebarItemsGenerator); - const version = content.loadedVersions[0]; + const version = content.loadedVersions[0]!; expect(version.sidebars).toMatchSnapshot(); }); diff --git a/packages/docusaurus-plugin-content-docs/src/__tests__/options.test.ts b/packages/docusaurus-plugin-content-docs/src/__tests__/options.test.ts index a3ddd11f843dc..ea4ebf043114e 100644 --- a/packages/docusaurus-plugin-content-docs/src/__tests__/options.test.ts +++ b/packages/docusaurus-plugin-content-docs/src/__tests__/options.test.ts @@ -36,7 +36,7 @@ describe('normalizeDocsPluginOptions', () => { }); it('accepts correctly defined user options', () => { - const userOptions = { + const userOptions: Options = { path: 'my-docs', // Path to data on filesystem, relative to site dir. routeBasePath: 'my-docs', // URL Route. tagsBasePath: 'tags', // URL Tags Route. @@ -51,6 +51,7 @@ describe('normalizeDocsPluginOptions', () => { docTagsListComponent: '@theme/DocTagsListPage', docCategoryGeneratedIndexComponent: '@theme/DocCategoryGeneratedIndexPage', + // @ts-expect-error: it seems to work in practice? remarkPlugins: [markdownPluginsObjectStub], rehypePlugins: [markdownPluginsFunctionStub], beforeDefaultRehypePlugins: [], @@ -79,16 +80,17 @@ describe('normalizeDocsPluginOptions', () => { expect(testValidate(userOptions)).toEqual({ ...defaultOptions, ...userOptions, - remarkPlugins: [...userOptions.remarkPlugins, expect.any(Array)], + remarkPlugins: [...userOptions.remarkPlugins!, expect.any(Array)], }); }); it('accepts correctly defined remark and rehype plugin options', () => { - const userOptions = { + const userOptions: Options = { beforeDefaultRemarkPlugins: [], beforeDefaultRehypePlugins: [markdownPluginsFunctionStub], remarkPlugins: [[markdownPluginsFunctionStub, {option1: '42'}]], rehypePlugins: [ + // @ts-expect-error: it seems to work in practice markdownPluginsObjectStub, [markdownPluginsFunctionStub, {option1: '42'}], ], @@ -96,12 +98,12 @@ describe('normalizeDocsPluginOptions', () => { expect(testValidate(userOptions)).toEqual({ ...defaultOptions, ...userOptions, - remarkPlugins: [...userOptions.remarkPlugins, expect.any(Array)], + remarkPlugins: [...userOptions.remarkPlugins!, expect.any(Array)], }); }); it('accepts admonitions false', () => { - const admonitionsFalse = { + const admonitionsFalse: Options = { admonitions: false, }; expect(testValidate(admonitionsFalse)).toEqual({ @@ -111,7 +113,7 @@ describe('normalizeDocsPluginOptions', () => { }); it('rejects admonitions true', () => { - const admonitionsTrue = { + const admonitionsTrue: Options = { admonitions: true, }; expect(() => @@ -124,7 +126,10 @@ describe('normalizeDocsPluginOptions', () => { it('accepts numberPrefixParser function', () => { function customNumberPrefixParser() {} expect( - testValidate({numberPrefixParser: customNumberPrefixParser}), + testValidate({ + numberPrefixParser: + customNumberPrefixParser as unknown as Options['numberPrefixParser'], + }), ).toEqual({ ...defaultOptions, numberPrefixParser: customNumberPrefixParser, @@ -148,6 +153,7 @@ describe('normalizeDocsPluginOptions', () => { it('rejects invalid remark plugin options', () => { expect(() => testValidate({ + // @ts-expect-error: test remarkPlugins: [[{option1: '42'}, markdownPluginsFunctionStub]], }), ).toThrowErrorMatchingInlineSnapshot(` @@ -161,6 +167,7 @@ describe('normalizeDocsPluginOptions', () => { expect(() => testValidate({ rehypePlugins: [ + // @ts-expect-error: test [ markdownPluginsFunctionStub, {option1: '42'}, @@ -176,6 +183,7 @@ describe('normalizeDocsPluginOptions', () => { }); it('rejects bad path inputs', () => { + // @ts-expect-error: test expect(() => testValidate({path: 2})).toThrowErrorMatchingInlineSnapshot( `""path" must be a string"`, ); @@ -183,12 +191,14 @@ describe('normalizeDocsPluginOptions', () => { it('rejects bad include inputs', () => { expect(() => + // @ts-expect-error: test testValidate({include: '**/*.{md,mdx}'}), ).toThrowErrorMatchingInlineSnapshot(`""include" must be an array"`); }); it('rejects bad showLastUpdateTime inputs', () => { expect(() => + // @ts-expect-error: test testValidate({showLastUpdateTime: 'true'}), ).toThrowErrorMatchingInlineSnapshot( `""showLastUpdateTime" must be a boolean"`, @@ -197,12 +207,14 @@ describe('normalizeDocsPluginOptions', () => { it('rejects bad remarkPlugins input', () => { expect(() => + // @ts-expect-error: test testValidate({remarkPlugins: 'remark-math'}), ).toThrowErrorMatchingInlineSnapshot(`""remarkPlugins" must be an array"`); }); it('rejects bad lastVersion', () => { expect(() => + // @ts-expect-error: test testValidate({lastVersion: false}), ).toThrowErrorMatchingInlineSnapshot(`""lastVersion" must be a string"`); }); @@ -212,6 +224,7 @@ describe('normalizeDocsPluginOptions', () => { testValidate({ versions: { current: { + // @ts-expect-error: test hey: 3, }, diff --git a/packages/docusaurus-plugin-content-docs/src/__tests__/props.test.ts b/packages/docusaurus-plugin-content-docs/src/__tests__/props.test.ts index 9db11b7cdddb1..7103e3908d59c 100644 --- a/packages/docusaurus-plugin-content-docs/src/__tests__/props.test.ts +++ b/packages/docusaurus-plugin-content-docs/src/__tests__/props.test.ts @@ -21,30 +21,30 @@ describe('toTagDocListProp', () => { docIds: ['id1', 'id3'], }; - const doc1: Doc = { + const doc1 = { id: 'id1', title: 'ZZZ 1', description: 'Description 1', permalink: '/doc1', - }; - const doc2: Doc = { + } as Doc; + const doc2 = { id: 'id2', title: 'XXX 2', description: 'Description 2', permalink: '/doc2', - }; - const doc3: Doc = { + } as Doc; + const doc3 = { id: 'id3', title: 'AAA 3', description: 'Description 3', permalink: '/doc3', - }; - const doc4: Doc = { + } as Doc; + const doc4 = { id: 'id4', title: 'UUU 4', description: 'Description 4', permalink: '/doc4', - }; + } as Doc; const result = toTagDocListProp({ allTagsPath, diff --git a/packages/docusaurus-plugin-content-docs/src/plugin-content-docs.d.ts b/packages/docusaurus-plugin-content-docs/src/plugin-content-docs.d.ts index 1d7784c63fc72..1d7be06b74dcf 100644 --- a/packages/docusaurus-plugin-content-docs/src/plugin-content-docs.d.ts +++ b/packages/docusaurus-plugin-content-docs/src/plugin-content-docs.d.ts @@ -17,7 +17,7 @@ declare module '@docusaurus/plugin-content-docs' { Tag, } from '@docusaurus/utils'; import type {Plugin, LoadContext} from '@docusaurus/types'; - import type {Required} from 'utility-types'; + import type {Overwrite, Required} from 'utility-types'; export type Assets = { image?: string; @@ -206,7 +206,22 @@ declare module '@docusaurus/plugin-content-docs' { */ tagsBasePath: string; }; - export type Options = Partial; + export type Options = Partial< + Overwrite< + PluginOptions, + { + /** + * Custom parsing logic to extract number prefixes from file names. Use + * `false` to disable this behavior and leave the docs untouched, and + * `true` to use the default parser. + * + * @param filename One segment of the path, without any slashes. + * @see https://docusaurus.io/docs/sidebar#using-number-prefixes + */ + numberPrefixParser: PluginOptions['numberPrefixParser'] | boolean; + } + > + >; export type SidebarsConfig = import('./sidebars/types').SidebarsConfig; export type VersionMetadata = ContentPaths & { diff --git a/packages/docusaurus-plugin-content-docs/src/sidebars/__tests__/utils.test.ts b/packages/docusaurus-plugin-content-docs/src/sidebars/__tests__/utils.test.ts index 4085c9931dc7c..60c30b96a8893 100644 --- a/packages/docusaurus-plugin-content-docs/src/sidebars/__tests__/utils.test.ts +++ b/packages/docusaurus-plugin-content-docs/src/sidebars/__tests__/utils.test.ts @@ -100,10 +100,13 @@ describe('createSidebarsUtils', () => { const sidebar4: Sidebar = [ { type: 'category', + collapsed: false, + collapsible: true, + label: 'Related', items: [ - {type: 'link', href: 'https://facebook.com'}, - {type: 'link', href: 'https://reactjs.org'}, - {type: 'link', href: 'https://docusaurus.io'}, + {type: 'link', href: 'https://facebook.com', label: 'Facebook'}, + {type: 'link', href: 'https://reactjs.org', label: 'React'}, + {type: 'link', href: 'https://docusaurus.io', label: 'Docusaurus'}, ], }, { @@ -696,10 +699,10 @@ describe('toNavigationLink', () => { it('with doc items', () => { expect(toNavigationLink({type: 'doc', id: 'doc1'}, docsById)).toEqual( - toDocNavigationLink(docsById.doc1), + toDocNavigationLink(docsById.doc1!), ); expect(toNavigationLink({type: 'doc', id: 'doc2'}, docsById)).toEqual( - toDocNavigationLink(docsById.doc2), + toDocNavigationLink(docsById.doc2!), ); expect(() => toNavigationLink({type: 'doc', id: 'doc3'}, docsById), @@ -724,7 +727,7 @@ describe('toNavigationLink', () => { }, docsById, ), - ).toEqual(toDocNavigationLink(docsById.doc1)); + ).toEqual(toDocNavigationLink(docsById.doc1!)); expect(() => toNavigationLink( { diff --git a/packages/docusaurus-plugin-content-docs/src/versions/__tests__/index.test.ts b/packages/docusaurus-plugin-content-docs/src/versions/__tests__/index.test.ts index 773643ba84416..15bb3d06d7207 100644 --- a/packages/docusaurus-plugin-content-docs/src/versions/__tests__/index.test.ts +++ b/packages/docusaurus-plugin-content-docs/src/versions/__tests__/index.test.ts @@ -10,7 +10,7 @@ import path from 'path'; import {DEFAULT_PLUGIN_ID} from '@docusaurus/utils'; import {readVersionsMetadata} from '../index'; import {DEFAULT_OPTIONS} from '../../options'; -import type {I18n} from '@docusaurus/types'; +import type {I18n, LoadContext} from '@docusaurus/types'; import type { PluginOptions, VersionMetadata, @@ -37,7 +37,7 @@ describe('readVersionsMetadata', () => { siteDir: simpleSiteDir, baseUrl: '/', i18n: DefaultI18N, - }; + } as LoadContext; const vCurrent: VersionMetadata = { contentPath: path.join(simpleSiteDir, 'docs'), @@ -198,7 +198,7 @@ describe('readVersionsMetadata', () => { siteDir: versionedSiteDir, baseUrl: '/', i18n: DefaultI18N, - }; + } as LoadContext; const vCurrent: VersionMetadata = { contentPath: path.join(versionedSiteDir, 'docs'), @@ -636,7 +636,7 @@ describe('readVersionsMetadata', () => { siteDir: versionedSiteDir, baseUrl: '/', i18n: DefaultI18N, - }; + } as LoadContext; const vCurrent: VersionMetadata = { contentPath: path.join(versionedSiteDir, 'community'), diff --git a/packages/docusaurus-plugin-sitemap/src/__tests__/createSitemap.test.ts b/packages/docusaurus-plugin-sitemap/src/__tests__/createSitemap.test.ts index 26fd096caf413..bc34ee51d87fa 100644 --- a/packages/docusaurus-plugin-sitemap/src/__tests__/createSitemap.test.ts +++ b/packages/docusaurus-plugin-sitemap/src/__tests__/createSitemap.test.ts @@ -8,6 +8,7 @@ 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', () => { @@ -31,7 +32,8 @@ describe('createSitemap', () => { it('empty site', () => expect(async () => { - await createSitemap({} as DocusaurusConfig, [], {}, {}); + // @ts-expect-error: test + await createSitemap({}, [], {}, {} as PluginOptions); }).rejects.toThrow( 'URL in docusaurus.config.js cannot be empty/undefined.', )); @@ -148,6 +150,7 @@ describe('createSitemap', () => { { '/noindex': { meta: { + // @ts-expect-error: bad lib def toComponent: () => [ React.createElement('meta', {name: 'robots', content: 'noindex'}), ], diff --git a/packages/docusaurus-plugin-sitemap/src/__tests__/options.test.ts b/packages/docusaurus-plugin-sitemap/src/__tests__/options.test.ts index 8d57746125b91..e48bc9302e492 100644 --- a/packages/docusaurus-plugin-sitemap/src/__tests__/options.test.ts +++ b/packages/docusaurus-plugin-sitemap/src/__tests__/options.test.ts @@ -23,7 +23,7 @@ describe('validateOptions', () => { }); it('accepts correctly defined user options', () => { - const userOptions = { + const userOptions: Options = { changefreq: 'yearly', priority: 0.9, ignorePatterns: ['/search/**'], @@ -52,9 +52,11 @@ describe('validateOptions', () => { 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"`, diff --git a/packages/docusaurus-theme-classic/src/__tests__/translations.test.ts b/packages/docusaurus-theme-classic/src/__tests__/translations.test.ts index 48a2c70f3ff7b..ba4d3464ea354 100644 --- a/packages/docusaurus-theme-classic/src/__tests__/translations.test.ts +++ b/packages/docusaurus-theme-classic/src/__tests__/translations.test.ts @@ -9,7 +9,7 @@ import {updateTranslationFileMessages} from '@docusaurus/utils'; import {getTranslationFiles, translateThemeConfig} from '../translations'; import type {ThemeConfig} from '@docusaurus/theme-common'; -const ThemeConfigSample: ThemeConfig = { +const ThemeConfigSample = { colorMode: {}, announcementBar: {}, prism: {}, @@ -47,7 +47,7 @@ const ThemeConfigSample: ThemeConfig = { }, ], }, -}; +} as unknown as ThemeConfig; const ThemeConfigSampleSimpleFooter: ThemeConfig = { ...ThemeConfigSample, diff --git a/packages/docusaurus-theme-classic/src/__tests__/validateThemeConfig.test.ts b/packages/docusaurus-theme-classic/src/__tests__/validateThemeConfig.test.ts index e7c9d7dcb1b0c..dd4eaae6df498 100644 --- a/packages/docusaurus-theme-classic/src/__tests__/validateThemeConfig.test.ts +++ b/packages/docusaurus-theme-classic/src/__tests__/validateThemeConfig.test.ts @@ -674,7 +674,7 @@ describe('themeConfig', () => { }); it('max config', () => { - const colorMode = { + const colorMode: ThemeConfig['colorMode'] = { defaultMode: 'dark', disableSwitch: false, respectPrefersColorScheme: true, diff --git a/packages/docusaurus-theme-classic/src/theme-classic.d.ts b/packages/docusaurus-theme-classic/src/theme-classic.d.ts index bc9b9c9bbaf37..76861545731fd 100644 --- a/packages/docusaurus-theme-classic/src/theme-classic.d.ts +++ b/packages/docusaurus-theme-classic/src/theme-classic.d.ts @@ -1032,10 +1032,10 @@ declare module '@theme/Tabs' { readonly lazy?: boolean; readonly block?: boolean; readonly children: readonly ReactElement[]; - readonly defaultValue?: string | null; + readonly defaultValue?: string | number | null; readonly values?: readonly { - value: string; - label?: string; + value: string | number; + label?: string | number; attributes?: {[key: string]: unknown}; }[]; readonly groupId?: string; diff --git a/packages/docusaurus-theme-classic/src/theme/Tabs/index.tsx b/packages/docusaurus-theme-classic/src/theme/Tabs/index.tsx index 8d055ce06e6f5..098879881f9e3 100644 --- a/packages/docusaurus-theme-classic/src/theme/Tabs/index.tsx +++ b/packages/docusaurus-theme-classic/src/theme/Tabs/index.tsx @@ -115,7 +115,7 @@ function TabsComponent(props: Props): JSX.Element { setSelectedValue(newTabValue); if (groupId != null) { - setTabGroupChoices(groupId, newTabValue); + setTabGroupChoices(groupId, String(newTabValue)); } } }; diff --git a/packages/docusaurus-theme-common/src/utils/__tests__/docsUtils.test.tsx b/packages/docusaurus-theme-common/src/utils/__tests__/docsUtils.test.tsx index b8ac8fb9eeddb..8f4c480112990 100644 --- a/packages/docusaurus-theme-common/src/utils/__tests__/docsUtils.test.tsx +++ b/packages/docusaurus-theme-common/src/utils/__tests__/docsUtils.test.tsx @@ -26,6 +26,7 @@ import type { 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( @@ -294,19 +295,22 @@ describe('isActiveSidebarItem', () => { describe('useSidebarBreadcrumbs', () => { const createUseSidebarBreadcrumbsMock = - (sidebar: PropSidebar, breadcrumbsOption?: boolean) => (location: string) => + (sidebar: PropSidebar | undefined, breadcrumbsOption?: boolean) => + (location: string) => renderHook(() => useSidebarBreadcrumbs(), { wrapper: ({children}) => ( + } as unknown as DocusaurusContext + }> {children} @@ -421,7 +425,9 @@ describe('useSidebarBreadcrumbs', () => { }); it('returns null when there is no sidebar', () => { - expect(createUseSidebarBreadcrumbsMock(null, false)('/foo')).toBeNull(); + expect( + createUseSidebarBreadcrumbsMock(undefined, false)('/foo'), + ).toBeNull(); }); }); @@ -436,9 +442,12 @@ describe('useCurrentSidebarCategory', () => { ), }).result.current; it('works', () => { - const category = { + const category: PropSidebarItemCategory = { type: 'category', + label: 'Category', href: '/cat', + collapsible: true, + collapsed: false, items: [ {type: 'link', href: '/cat/foo', label: 'Foo'}, {type: 'link', href: '/cat/bar', label: 'Bar'}, @@ -453,8 +462,11 @@ describe('useCurrentSidebarCategory', () => { }); it('throws for non-category index page', () => { - const category = { + 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'}, diff --git a/packages/docusaurus-theme-common/src/utils/__tests__/usePluralForm.test.tsx b/packages/docusaurus-theme-common/src/utils/__tests__/usePluralForm.test.tsx index f7618dbb258c2..f789734119f76 100644 --- a/packages/docusaurus-theme-common/src/utils/__tests__/usePluralForm.test.tsx +++ b/packages/docusaurus-theme-common/src/utils/__tests__/usePluralForm.test.tsx @@ -24,7 +24,7 @@ describe('usePluralForm', () => { i18n: { currentLocale: 'en', }, - }); + } as DocusaurusContext); expect(mockUsePluralForm().selectMessage(1, 'one|many')).toBe('one'); expect(mockUsePluralForm().selectMessage(10, 'one|many')).toBe('many'); }); @@ -34,7 +34,7 @@ describe('usePluralForm', () => { i18n: { currentLocale: 'zh-Hans', }, - }); + } as DocusaurusContext); const consoleMock = jest .spyOn(console, 'error') .mockImplementation(() => {}); @@ -50,7 +50,7 @@ describe('usePluralForm', () => { i18n: { currentLocale: 'en', }, - }); + } as DocusaurusContext); expect(mockUsePluralForm().selectMessage(10, 'many')).toBe('many'); }); @@ -59,7 +59,7 @@ describe('usePluralForm', () => { i18n: { currentLocale: 'zh-Hans', }, - }); + } as DocusaurusContext); const consoleMock = jest .spyOn(console, 'error') .mockImplementation(() => {}); diff --git a/packages/docusaurus-theme-translations/src/__tests__/index.test.ts b/packages/docusaurus-theme-translations/src/__tests__/index.test.ts index af47cd2f17549..571c35474ce68 100644 --- a/packages/docusaurus-theme-translations/src/__tests__/index.test.ts +++ b/packages/docusaurus-theme-translations/src/__tests__/index.test.ts @@ -78,6 +78,7 @@ describe('readDefaultCodeTranslationMessages', () => { it('for empty locale', async () => { await expect( readDefaultCodeTranslationMessages({ + name: 'default', locale: '', dirPath, }), diff --git a/packages/docusaurus-utils/src/__tests__/jsUtils.test.ts b/packages/docusaurus-utils/src/__tests__/jsUtils.test.ts index ca7218ab02ad2..5831ad69626bb 100644 --- a/packages/docusaurus-utils/src/__tests__/jsUtils.test.ts +++ b/packages/docusaurus-utils/src/__tests__/jsUtils.test.ts @@ -58,7 +58,7 @@ describe('mapAsyncSequential', () => { const timeBefore = Date.now(); await expect( mapAsyncSequential(items, async (item) => { - const itemTimeout = itemToTimeout[item]; + const itemTimeout = itemToTimeout[item]!; itemMapStartsAt[item] = Date.now(); await sleep(itemTimeout); itemMapEndsAt[item] = Date.now(); @@ -72,12 +72,10 @@ describe('mapAsyncSequential', () => { 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[1]).toBeGreaterThanOrEqual(0); + expect(itemMapStartsAt[2]).toBeGreaterThanOrEqual(itemMapEndsAt[1]! - 100); expect(itemMapStartsAt['3']).toBeGreaterThanOrEqual( - itemMapEndsAt['2'] - 100, + itemMapEndsAt[2]! - 100, ); }); }); diff --git a/packages/docusaurus-utils/src/__tests__/webpackUtils.test.ts b/packages/docusaurus-utils/src/__tests__/webpackUtils.test.ts index f4ce3578bf1b1..3d2c70f68924f 100644 --- a/packages/docusaurus-utils/src/__tests__/webpackUtils.test.ts +++ b/packages/docusaurus-utils/src/__tests__/webpackUtils.test.ts @@ -10,7 +10,7 @@ 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(oneOf![0]!.use).toContainEqual( expect.objectContaining({ loader: require.resolve('@svgr/webpack'), options: expect.objectContaining({ diff --git a/packages/docusaurus/src/client/__tests__/flat.test.ts b/packages/docusaurus/src/client/__tests__/flat.test.ts index 54c252393dd1f..358a0c547d165 100644 --- a/packages/docusaurus/src/client/__tests__/flat.test.ts +++ b/packages/docusaurus/src/client/__tests__/flat.test.ts @@ -46,7 +46,7 @@ describe('flat', () => { expect( flat({ foo: { - bar: value, + bar: value as string, }, }), ).toEqual({ diff --git a/packages/docusaurus/src/client/__tests__/normalizeLocation.test.ts b/packages/docusaurus/src/client/__tests__/normalizeLocation.test.ts index fad94198575cb..fcc23ba63cd3b 100644 --- a/packages/docusaurus/src/client/__tests__/normalizeLocation.test.ts +++ b/packages/docusaurus/src/client/__tests__/normalizeLocation.test.ts @@ -7,13 +7,14 @@ 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: '/', }); @@ -23,7 +24,7 @@ describe('normalizeLocation', () => { pathname: '/docs/introduction/index.html', search: '?search=foo', hash: '#features', - }), + } as Location), ).toEqual({ pathname: '/docs/introduction', search: '?search=foo', @@ -35,7 +36,7 @@ describe('normalizeLocation', () => { pathname: '/index.html', search: '', hash: '#features', - }), + } as Location), ).toEqual({ pathname: '/', search: '', @@ -47,7 +48,7 @@ describe('normalizeLocation', () => { expect( normalizeLocation({ pathname: '/docs/installation.html', - }), + } as Location), ).toEqual({ pathname: '/docs/installation', }); @@ -56,7 +57,7 @@ describe('normalizeLocation', () => { pathname: '/docs/introduction/foo.html', search: '', hash: '#bar', - }), + } as Location), ).toEqual({ pathname: '/docs/introduction/foo', search: '', @@ -65,7 +66,7 @@ describe('normalizeLocation', () => { }); it('does not strip extension if the route location has one', () => { - expect(normalizeLocation({pathname: '/page.html'})).toEqual({ + expect(normalizeLocation({pathname: '/page.html'} as Location)).toEqual({ pathname: '/page.html', }); }); @@ -78,7 +79,7 @@ describe('normalizeLocation', () => { pathname: '/docs/introduction', search: '', hash: '#features', - }), + } as Location), ).toEqual({ pathname: '/docs/introduction', search: '', @@ -91,7 +92,7 @@ describe('normalizeLocation', () => { pathname: '/docs/introduction', search: '', hash: '#features', - }), + } as Location), ).toEqual({ pathname: '/docs/introduction', search: '', @@ -102,7 +103,7 @@ describe('normalizeLocation', () => { expect( normalizeLocation({ pathname: '/', - }), + } as Location), ).toEqual({ pathname: '/', }); diff --git a/packages/docusaurus/src/client/exports/__tests__/Interpolate.test.tsx b/packages/docusaurus/src/client/exports/__tests__/Interpolate.test.tsx index 57f944d58b8fd..d21b296f12531 100644 --- a/packages/docusaurus/src/client/exports/__tests__/Interpolate.test.tsx +++ b/packages/docusaurus/src/client/exports/__tests__/Interpolate.test.tsx @@ -31,7 +31,7 @@ describe('interpolate', () => { object: {hello: 'world'}, array: ['Hello'], }; - // Do we need to improve the JS type -> String conversion logic here? + // @ts-expect-error: test expect(interpolate(text, values)).toMatchInlineSnapshot( `"42 Hello [object Object] Hello"`, ); @@ -52,6 +52,7 @@ describe('interpolate', () => { // Should we emit warnings in such case? const text = 'Hello {name} how are you {unprovidedValue}?'; const values = {name: 'Sébastien', extraValue: 'today'}; + // @ts-expect-error: test expect(interpolate(text, values)).toMatchInlineSnapshot( `"Hello Sébastien how are you {unprovidedValue}?"`, ); @@ -61,6 +62,7 @@ describe('interpolate', () => { // Should we emit warnings in such case? const text = 'Hello {name} how are you {day}?'; expect(interpolate(text)).toEqual(text); + // @ts-expect-error: test expect(interpolate(text, {})).toEqual(text); }); @@ -84,6 +86,7 @@ describe('interpolate', () => { extraUselessValue1:
test
, extraUselessValue2: 'hi', }; + // @ts-expect-error: test expect(interpolate(text, values)).toMatchSnapshot(); }); }); @@ -133,6 +136,7 @@ describe('', () => { `"The Docusaurus component only accept simple string values. Received: React element"`, ); expect(() => + // @ts-expect-error: test renderer.create({null}), ).toThrowErrorMatchingInlineSnapshot( `"The Docusaurus component only accept simple string values. Received: object"`, diff --git a/packages/docusaurus/src/client/exports/__tests__/useBaseUrl.test.tsx b/packages/docusaurus/src/client/exports/__tests__/useBaseUrl.test.tsx index 5478f7c358f9c..1c6724da3069b 100644 --- a/packages/docusaurus/src/client/exports/__tests__/useBaseUrl.test.tsx +++ b/packages/docusaurus/src/client/exports/__tests__/useBaseUrl.test.tsx @@ -28,7 +28,7 @@ describe('useBaseUrl', () => { baseUrl: '/', url: 'https://docusaurus.io', }, - }); + } as DocusaurusContext); expect(mockUseBaseUrl('hello')).toBe('/hello'); expect(mockUseBaseUrl('/hello')).toBe('/hello'); @@ -56,7 +56,7 @@ describe('useBaseUrl', () => { baseUrl: '/docusaurus/', url: 'https://docusaurus.io', }, - }); + } as DocusaurusContext); expect(mockUseBaseUrl('')).toBe(''); expect(mockUseBaseUrl('hello')).toBe('/docusaurus/hello'); @@ -97,7 +97,7 @@ describe('useBaseUrlUtils().withBaseUrl()', () => { baseUrl: '/', url: 'https://docusaurus.io', }, - }); + } as DocusaurusContext); expect(withBaseUrl('hello')).toBe('/hello'); expect(withBaseUrl('/hello')).toBe('/hello'); @@ -125,7 +125,7 @@ describe('useBaseUrlUtils().withBaseUrl()', () => { baseUrl: '/docusaurus/', url: 'https://docusaurus.io', }, - }); + } as DocusaurusContext); expect(withBaseUrl('hello')).toBe('/docusaurus/hello'); expect(withBaseUrl('/hello')).toBe('/docusaurus/hello'); diff --git a/packages/docusaurus/src/server/plugins/__tests__/index.test.ts b/packages/docusaurus/src/server/plugins/__tests__/index.test.ts index 7e3ae0f428e2d..148e20fa46a63 100644 --- a/packages/docusaurus/src/server/plugins/__tests__/index.test.ts +++ b/packages/docusaurus/src/server/plugins/__tests__/index.test.ts @@ -7,6 +7,7 @@ import path from 'path'; import {loadPlugins} from '..'; +import type {Props} from '@docusaurus/types'; describe('loadPlugins', () => { it('loads plugins', async () => { @@ -16,7 +17,6 @@ describe('loadPlugins', () => { siteDir, generatedFilesDir: path.join(siteDir, '.docusaurus'), outDir: path.join(siteDir, 'build'), - // @ts-expect-error: good enough siteConfig: { baseUrl: '/', trailingSlash: true, @@ -51,7 +51,7 @@ describe('loadPlugins', () => { ], }, siteConfigPath: path.join(siteDir, 'docusaurus.config.js'), - }), + } as unknown as Props), ).resolves.toMatchSnapshot(); }); }); diff --git a/packages/docusaurus/src/server/plugins/__tests__/init.test.ts b/packages/docusaurus/src/server/plugins/__tests__/init.test.ts index 30fe4cb603a96..249b5af2bf547 100644 --- a/packages/docusaurus/src/server/plugins/__tests__/init.test.ts +++ b/packages/docusaurus/src/server/plugins/__tests__/init.test.ts @@ -24,14 +24,14 @@ describe('initPlugins', () => { expect(context.siteConfig.plugins).toHaveLength(4); expect(plugins).toHaveLength(8); - expect(plugins[0].name).toBe('preset-plugin1'); - expect(plugins[1].name).toBe('preset-plugin2'); - expect(plugins[2].name).toBe('preset-theme1'); - expect(plugins[3].name).toBe('preset-theme2'); - expect(plugins[4].name).toBe('first-plugin'); - expect(plugins[5].name).toBe('second-plugin'); - expect(plugins[6].name).toBe('third-plugin'); - expect(plugins[7].name).toBe('fourth-plugin'); + expect(plugins[0]!.name).toBe('preset-plugin1'); + expect(plugins[1]!.name).toBe('preset-plugin2'); + expect(plugins[2]!.name).toBe('preset-theme1'); + expect(plugins[3]!.name).toBe('preset-theme2'); + expect(plugins[4]!.name).toBe('first-plugin'); + expect(plugins[5]!.name).toBe('second-plugin'); + expect(plugins[6]!.name).toBe('third-plugin'); + expect(plugins[7]!.name).toBe('fourth-plugin'); expect(context.siteConfig.themeConfig).toEqual({a: 1}); }); diff --git a/packages/docusaurus/src/server/plugins/__tests__/pluginIds.test.ts b/packages/docusaurus/src/server/plugins/__tests__/pluginIds.test.ts index a6315f59a813d..e01417689a12d 100644 --- a/packages/docusaurus/src/server/plugins/__tests__/pluginIds.test.ts +++ b/packages/docusaurus/src/server/plugins/__tests__/pluginIds.test.ts @@ -8,12 +8,11 @@ import {ensureUniquePluginInstanceIds} from '../pluginIds'; import type {InitializedPlugin} from '@docusaurus/types'; -function createTestPlugin(name: string, id?: string): InitializedPlugin { - // @ts-expect-error: good enough for tests +function createTestPlugin(name: string, id?: string) { return { name, - options: {id}, - }; + options: {id: id ?? 'default'}, + } as InitializedPlugin; } describe('ensureUniquePluginInstanceIds', () => { diff --git a/packages/docusaurus/src/server/plugins/__tests__/presets.test.ts b/packages/docusaurus/src/server/plugins/__tests__/presets.test.ts index 10d50a29506a6..c91709df62df4 100644 --- a/packages/docusaurus/src/server/plugins/__tests__/presets.test.ts +++ b/packages/docusaurus/src/server/plugins/__tests__/presets.test.ts @@ -62,7 +62,7 @@ describe('loadPresets', () => { [path.join(__dirname, '__fixtures__/presets/preset-plugins.js')], ], }, - } as Partial; + } as unknown as LoadContext; const presets = await loadPresets(context); expect(presets).toMatchSnapshot(); }); @@ -78,7 +78,7 @@ describe('loadPresets', () => { ], ], }, - } as Partial; + } as unknown as LoadContext; const presets = await loadPresets(context); expect(presets).toMatchSnapshot(); }); @@ -98,7 +98,7 @@ describe('loadPresets', () => { ], ], }, - } as Partial; + } as unknown as LoadContext; const presets = await loadPresets(context); expect(presets).toMatchSnapshot(); }); diff --git a/packages/docusaurus/src/server/translations/__tests__/translations.test.ts b/packages/docusaurus/src/server/translations/__tests__/translations.test.ts index f34318cd47074..7ced1c70b5c22 100644 --- a/packages/docusaurus/src/server/translations/__tests__/translations.test.ts +++ b/packages/docusaurus/src/server/translations/__tests__/translations.test.ts @@ -20,6 +20,7 @@ import { } from '../translations'; import type { InitializedPlugin, + LoadedPlugin, TranslationFile, TranslationFileContent, } from '@docusaurus/types'; @@ -399,7 +400,7 @@ describe('writePluginTranslations', () => { options: { id: 'my-plugin-id', }, - }, + } as LoadedPlugin, options: {}, }), @@ -426,11 +427,10 @@ describe('localizePluginTranslationFile', () => { siteDir, locale: 'fr', translationFile, - // @ts-expect-error: enough for this test plugin: { name: 'my-plugin-name', options: {}, - }, + } as LoadedPlugin, }); expect(localizedTranslationFile).toEqual(translationFile); @@ -466,11 +466,10 @@ describe('localizePluginTranslationFile', () => { siteDir, locale: 'fr', translationFile, - // @ts-expect-error: enough for this test plugin: { name: 'my-plugin-name', options: {}, - }, + } as LoadedPlugin, }); expect(localizedTranslationFile).toEqual({ @@ -521,25 +520,30 @@ describe('readCodeTranslationFileContent', () => { it('fails for invalid translation file content', async () => { await expect(() => + // @ts-expect-error: test testReadTranslation('HEY'), ).rejects.toThrowErrorMatchingInlineSnapshot( `""value" must be of type object"`, ); await expect(() => + // @ts-expect-error: test testReadTranslation(42), ).rejects.toThrowErrorMatchingInlineSnapshot( `""value" must be of type object"`, ); await expect(() => + // @ts-expect-error: test testReadTranslation({key: {description: 'no message'}}), ).rejects.toThrowErrorMatchingInlineSnapshot(`""key.message" is required"`); await expect(() => + // @ts-expect-error: test testReadTranslation({key: {message: 42}}), ).rejects.toThrowErrorMatchingInlineSnapshot( `""key.message" must be a string"`, ); await expect(() => testReadTranslation({ + // @ts-expect-error: test key: {message: 'Message', description: 42}, }), ).rejects.toThrowErrorMatchingInlineSnapshot( diff --git a/packages/docusaurus/src/server/translations/__tests__/translationsExtractor.test.ts b/packages/docusaurus/src/server/translations/__tests__/translationsExtractor.test.ts index e06bc5f57d1fd..ac74f839ea2ec 100644 --- a/packages/docusaurus/src/server/translations/__tests__/translationsExtractor.test.ts +++ b/packages/docusaurus/src/server/translations/__tests__/translationsExtractor.test.ts @@ -15,7 +15,7 @@ import { extractSiteSourceCodeTranslations, } from '../translationsExtractor'; import {getBabelOptions} from '../../../webpack/utils'; -import type {InitializedPlugin} from '@docusaurus/types'; +import type {InitializedPlugin, LoadedPlugin} from '@docusaurus/types'; const TestBabelOptions = getBabelOptions({ isServer: true, @@ -693,7 +693,7 @@ export default function MyComponent(props: Props) { plugin1, plugin2, {name: 'dummy', options: {}, version: {type: 'synthetic'}} as const, - ]; + ] as LoadedPlugin[]; const translations = await extractSiteSourceCodeTranslations( siteDir, plugins, diff --git a/packages/docusaurus/src/webpack/__tests__/base.test.ts b/packages/docusaurus/src/webpack/__tests__/base.test.ts index 3e39adfda4355..469d6a5540a50 100644 --- a/packages/docusaurus/src/webpack/__tests__/base.test.ts +++ b/packages/docusaurus/src/webpack/__tests__/base.test.ts @@ -63,7 +63,7 @@ describe('babel transpilation exclude logic', () => { }); describe('base webpack config', () => { - const props: Props = { + const props = { outDir: '', siteDir: path.resolve(__dirname, '__fixtures__', 'base_test_site'), siteConfig: {staticDirectories: ['static']}, @@ -98,7 +98,7 @@ describe('base webpack config', () => { }, }, ], - }; + } as Props; afterEach(() => { jest.restoreAllMocks(); diff --git a/packages/docusaurus/src/webpack/__tests__/server.test.ts b/packages/docusaurus/src/webpack/__tests__/server.test.ts index b722f46f7dd08..f3207fdc2fe2b 100644 --- a/packages/docusaurus/src/webpack/__tests__/server.test.ts +++ b/packages/docusaurus/src/webpack/__tests__/server.test.ts @@ -15,7 +15,11 @@ describe('webpack production config', () => { it('simple', async () => { jest.spyOn(console, 'log').mockImplementation(() => {}); const props = await loadSetup('simple'); - const config = await createServerConfig({props}); + const config = await createServerConfig({ + props, + onHeadTagsCollected: () => {}, + onLinksCollected: () => {}, + }); const errors = webpack.validate(config); expect(errors).toBeUndefined(); }); @@ -23,7 +27,11 @@ describe('webpack production config', () => { it('custom', async () => { jest.spyOn(console, 'log').mockImplementation(() => {}); const props = await loadSetup('custom'); - const config = await createServerConfig({props}); + const config = await createServerConfig({ + props, + onHeadTagsCollected: () => {}, + onLinksCollected: () => {}, + }); const errors = webpack.validate(config); expect(errors).toBeUndefined(); }); diff --git a/packages/docusaurus/src/webpack/__tests__/utils.test.ts b/packages/docusaurus/src/webpack/__tests__/utils.test.ts index 411ed9180469e..f5366ded41c1f 100644 --- a/packages/docusaurus/src/webpack/__tests__/utils.test.ts +++ b/packages/docusaurus/src/webpack/__tests__/utils.test.ts @@ -60,6 +60,7 @@ describe('extending generated webpack config', () => { }, }; + // @ts-expect-error: Testing an edge-case that we did not write types for const configureWebpack: Plugin['configureWebpack'] = ( generatedConfig, isServer, @@ -125,14 +126,16 @@ describe('extending generated webpack config', () => { }, }; - const createConfigureWebpack: (mergeStrategy?: { - [key: string]: 'prepend' | 'append'; - }) => Plugin['configureWebpack'] = (mergeStrategy) => () => ({ - module: { - rules: [{use: 'zzz'}], - }, - mergeStrategy, - }); + const createConfigureWebpack = + (mergeStrategy?: { + [key: string]: 'prepend' | 'append'; + }): Plugin['configureWebpack'] => + () => ({ + module: { + rules: [{use: 'zzz'}], + }, + mergeStrategy, + }); const defaultStrategyMergeConfig = applyConfigureWebpack( createConfigureWebpack(), diff --git a/packages/eslint-plugin/src/rules/__tests__/no-untranslated-text.test.ts b/packages/eslint-plugin/src/rules/__tests__/no-untranslated-text.test.ts index 869605a48c681..dc287f602c3a7 100644 --- a/packages/eslint-plugin/src/rules/__tests__/no-untranslated-text.test.ts +++ b/packages/eslint-plugin/src/rules/__tests__/no-untranslated-text.test.ts @@ -8,12 +8,7 @@ import rule from '../no-untranslated-text'; import {getCommonValidTests, RuleTester} from './testUtils'; -const errorsJSX = [ - {messageId: 'translateChildren', type: 'JSXElement'}, -] as const; -const errorsJSXFragment = [ - {messageId: 'translateChildren', type: 'JSXFragment'}, -]; +const errorsJSX = [{messageId: 'translateChildren'}] as const; const ruleTester = new RuleTester({ parser: '@typescript-eslint/parser', @@ -110,7 +105,7 @@ ruleTester.run('no-untranslated-text', rule, { }, { code: '<>text', - errors: errorsJSXFragment, + errors: errorsJSX, }, { code: '· — ×', diff --git a/packages/eslint-plugin/src/rules/__tests__/string-literal-i18n-messages.test.ts b/packages/eslint-plugin/src/rules/__tests__/string-literal-i18n-messages.test.ts index d836979acd228..066017931d7a7 100644 --- a/packages/eslint-plugin/src/rules/__tests__/string-literal-i18n-messages.test.ts +++ b/packages/eslint-plugin/src/rules/__tests__/string-literal-i18n-messages.test.ts @@ -8,12 +8,8 @@ import rule from '../string-literal-i18n-messages'; import {getCommonValidTests, RuleTester} from './testUtils'; -const errorsJSX = [ - {messageId: 'translateChildren', type: 'JSXElement'}, -] as const; -const errorsFunc = [ - {messageId: 'translateArg', type: 'CallExpression'}, -] as const; +const errorsJSX = [{messageId: 'translateChildren'}] as const; +const errorsFunc = [{messageId: 'translateArg'}] as const; const ruleTester = new RuleTester({ parser: '@typescript-eslint/parser',