test: fix ALL type errors in tests (#7487)

This commit is contained in:
Joshua Chen 2022-05-25 14:01:10 +08:00 committed by GitHub
parent e2e40b8f5f
commit d50fe3b670
No known key found for this signature in database
GPG key ID: 4AEE18F83AFDEB23
37 changed files with 407 additions and 184 deletions

View file

@ -11,9 +11,15 @@ import {normalizePluginOptions} from '@docusaurus/utils-validation';
import {posixPath, getFileCommitDate} from '@docusaurus/utils';
import pluginContentBlog from '../index';
import {validateOptions} from '../options';
import type {DocusaurusConfig, LoadContext, I18n} from '@docusaurus/types';
import type {
DocusaurusConfig,
LoadContext,
I18n,
Validate,
} from '@docusaurus/types';
import type {
BlogPost,
Options,
PluginOptions,
EditUrlFunction,
} from '@docusaurus/plugin-content-blog';
@ -77,7 +83,10 @@ const getPlugin = async (
i18n,
} as LoadContext,
validateOptions({
validate: normalizePluginOptions,
validate: normalizePluginOptions as Validate<
Options | undefined,
PluginOptions
>,
options: {
path: PluginPath,
editUrl: BaseEditUrl,

View file

@ -7,10 +7,17 @@
import {normalizePluginOptions} from '@docusaurus/utils-validation';
import {validateOptions, DEFAULT_OPTIONS} from '../options';
import type {Options} from '@docusaurus/plugin-content-blog';
import type {Options, PluginOptions} from '@docusaurus/plugin-content-blog';
import type {Validate} from '@docusaurus/types';
function testValidate(options?: Options) {
return validateOptions({validate: normalizePluginOptions, options});
return validateOptions({
validate: normalizePluginOptions as Validate<
Options | undefined,
PluginOptions
>,
options,
});
}
// The type of remark/rehype plugins can be either function, object or array

View file

@ -84,11 +84,15 @@ exports[`translateLoadedContent returns translated loaded content 1`] = `
{
"loadedVersions": [
{
"badge": true,
"banner": null,
"className": "",
"contentPath": "any",
"contentPathLocalized": "any",
"docs": [
{
"description": "doc1 description",
"draft": false,
"editUrl": "any",
"frontMatter": {
"sidebar_label": "doc1 title",
@ -101,12 +105,15 @@ exports[`translateLoadedContent returns translated loaded content 1`] = `
"previous": undefined,
"slug": "any",
"source": "any",
"sourceDirName": "",
"tags": [],
"title": "doc1 title",
"unversionedId": "any",
"version": "any",
},
{
"description": "doc2 description",
"draft": false,
"editUrl": "any",
"frontMatter": {
"sidebar_label": "doc2 title",
@ -119,12 +126,15 @@ exports[`translateLoadedContent returns translated loaded content 1`] = `
"previous": undefined,
"slug": "any",
"source": "any",
"sourceDirName": "",
"tags": [],
"title": "doc2 title",
"unversionedId": "any",
"version": "any",
},
{
"description": "doc3 description",
"draft": false,
"editUrl": "any",
"frontMatter": {
"sidebar_label": "doc3 title",
@ -137,12 +147,15 @@ exports[`translateLoadedContent returns translated loaded content 1`] = `
"previous": undefined,
"slug": "any",
"source": "any",
"sourceDirName": "",
"tags": [],
"title": "doc3 title",
"unversionedId": "any",
"version": "any",
},
{
"description": "doc4 description",
"draft": false,
"editUrl": "any",
"frontMatter": {
"sidebar_label": "doc4 title",
@ -155,12 +168,15 @@ exports[`translateLoadedContent returns translated loaded content 1`] = `
"previous": undefined,
"slug": "any",
"source": "any",
"sourceDirName": "",
"tags": [],
"title": "doc4 title",
"unversionedId": "any",
"version": "any",
},
{
"description": "doc5 description",
"draft": false,
"editUrl": "any",
"frontMatter": {
"sidebar_label": "doc5 title",
@ -173,14 +189,16 @@ exports[`translateLoadedContent returns translated loaded content 1`] = `
"previous": undefined,
"slug": "any",
"source": "any",
"sourceDirName": "",
"tags": [],
"title": "doc5 title",
"unversionedId": "any",
"version": "any",
},
],
"drafts": [],
"isLast": true,
"label": "current label (translated)",
"mainDocId": "",
"path": "/docs/",
"routePriority": undefined,
"sidebarFilePath": "any",
@ -188,6 +206,7 @@ exports[`translateLoadedContent returns translated loaded content 1`] = `
"docs": [
{
"collapsed": false,
"collapsible": true,
"items": [
{
"id": "doc1",
@ -233,14 +252,19 @@ exports[`translateLoadedContent returns translated loaded content 1`] = `
},
],
},
"tagsPath": "/tags/",
"versionName": "current",
},
{
"badge": true,
"banner": null,
"className": "",
"contentPath": "any",
"contentPathLocalized": "any",
"docs": [
{
"description": "doc1 description",
"draft": false,
"editUrl": "any",
"frontMatter": {
"sidebar_label": "doc1 title",
@ -253,12 +277,15 @@ exports[`translateLoadedContent returns translated loaded content 1`] = `
"previous": undefined,
"slug": "any",
"source": "any",
"sourceDirName": "",
"tags": [],
"title": "doc1 title",
"unversionedId": "any",
"version": "any",
},
{
"description": "doc2 description",
"draft": false,
"editUrl": "any",
"frontMatter": {
"sidebar_label": "doc2 title",
@ -271,12 +298,15 @@ exports[`translateLoadedContent returns translated loaded content 1`] = `
"previous": undefined,
"slug": "any",
"source": "any",
"sourceDirName": "",
"tags": [],
"title": "doc2 title",
"unversionedId": "any",
"version": "any",
},
{
"description": "doc3 description",
"draft": false,
"editUrl": "any",
"frontMatter": {
"sidebar_label": "doc3 title",
@ -289,12 +319,15 @@ exports[`translateLoadedContent returns translated loaded content 1`] = `
"previous": undefined,
"slug": "any",
"source": "any",
"sourceDirName": "",
"tags": [],
"title": "doc3 title",
"unversionedId": "any",
"version": "any",
},
{
"description": "doc4 description",
"draft": false,
"editUrl": "any",
"frontMatter": {
"sidebar_label": "doc4 title",
@ -307,12 +340,15 @@ exports[`translateLoadedContent returns translated loaded content 1`] = `
"previous": undefined,
"slug": "any",
"source": "any",
"sourceDirName": "",
"tags": [],
"title": "doc4 title",
"unversionedId": "any",
"version": "any",
},
{
"description": "doc5 description",
"draft": false,
"editUrl": "any",
"frontMatter": {
"sidebar_label": "doc5 title",
@ -325,14 +361,16 @@ exports[`translateLoadedContent returns translated loaded content 1`] = `
"previous": undefined,
"slug": "any",
"source": "any",
"sourceDirName": "",
"tags": [],
"title": "doc5 title",
"unversionedId": "any",
"version": "any",
},
],
"drafts": [],
"isLast": true,
"label": "2.0.0 label (translated)",
"mainDocId": "",
"path": "/docs/",
"routePriority": undefined,
"sidebarFilePath": "any",
@ -340,6 +378,7 @@ exports[`translateLoadedContent returns translated loaded content 1`] = `
"docs": [
{
"collapsed": false,
"collapsible": true,
"items": [
{
"id": "doc1",
@ -385,14 +424,19 @@ exports[`translateLoadedContent returns translated loaded content 1`] = `
},
],
},
"tagsPath": "/tags/",
"versionName": "2.0.0",
},
{
"badge": true,
"banner": null,
"className": "",
"contentPath": "any",
"contentPathLocalized": "any",
"docs": [
{
"description": "doc1 description",
"draft": false,
"editUrl": "any",
"frontMatter": {
"sidebar_label": "doc1 title",
@ -405,12 +449,15 @@ exports[`translateLoadedContent returns translated loaded content 1`] = `
"previous": undefined,
"slug": "any",
"source": "any",
"sourceDirName": "",
"tags": [],
"title": "doc1 title",
"unversionedId": "any",
"version": "any",
},
{
"description": "doc2 description",
"draft": false,
"editUrl": "any",
"frontMatter": {
"sidebar_label": "doc2 title",
@ -423,12 +470,15 @@ exports[`translateLoadedContent returns translated loaded content 1`] = `
"previous": undefined,
"slug": "any",
"source": "any",
"sourceDirName": "",
"tags": [],
"title": "doc2 title",
"unversionedId": "any",
"version": "any",
},
{
"description": "doc3 description",
"draft": false,
"editUrl": "any",
"frontMatter": {
"sidebar_label": "doc3 title",
@ -441,12 +491,15 @@ exports[`translateLoadedContent returns translated loaded content 1`] = `
"previous": undefined,
"slug": "any",
"source": "any",
"sourceDirName": "",
"tags": [],
"title": "doc3 title",
"unversionedId": "any",
"version": "any",
},
{
"description": "doc4 description",
"draft": false,
"editUrl": "any",
"frontMatter": {
"sidebar_label": "doc4 title",
@ -459,12 +512,15 @@ exports[`translateLoadedContent returns translated loaded content 1`] = `
"previous": undefined,
"slug": "any",
"source": "any",
"sourceDirName": "",
"tags": [],
"title": "doc4 title",
"unversionedId": "any",
"version": "any",
},
{
"description": "doc5 description",
"draft": false,
"editUrl": "any",
"frontMatter": {
"sidebar_label": "doc5 title",
@ -477,14 +533,16 @@ exports[`translateLoadedContent returns translated loaded content 1`] = `
"previous": undefined,
"slug": "any",
"source": "any",
"sourceDirName": "",
"tags": [],
"title": "doc5 title",
"unversionedId": "any",
"version": "any",
},
],
"drafts": [],
"isLast": true,
"label": "1.0.0 label (translated)",
"mainDocId": "",
"path": "/docs/",
"routePriority": undefined,
"sidebarFilePath": "any",
@ -492,6 +550,7 @@ exports[`translateLoadedContent returns translated loaded content 1`] = `
"docs": [
{
"collapsed": false,
"collapsible": true,
"items": [
{
"id": "doc1",
@ -537,6 +596,7 @@ exports[`translateLoadedContent returns translated loaded content 1`] = `
},
],
},
"tagsPath": "/tags/",
"versionName": "1.0.0",
},
],

View file

@ -25,9 +25,11 @@ import {DisabledSidebars} from '../sidebars';
import * as cliDocs from '../cli';
import {validateOptions} from '../options';
import type {RouteConfig} from '@docusaurus/types';
import type {RouteConfig, Validate, Plugin} from '@docusaurus/types';
import type {
LoadedVersion,
Options,
PluginOptions,
PropSidebarItemLink,
} from '@docusaurus/plugin-content-docs';
import type {
@ -133,7 +135,7 @@ describe('sidebar', () => {
const plugin = await pluginContentDocs(
context,
validateOptions({
validate: normalizePluginOptions,
validate: normalizePluginOptions as Validate<Options, PluginOptions>,
options: {
sidebarPath,
},
@ -150,7 +152,7 @@ describe('sidebar', () => {
const plugin = await pluginContentDocs(
context,
validateOptions({
validate: normalizePluginOptions,
validate: normalizePluginOptions as Validate<Options, PluginOptions>,
options: {
sidebarPath: 'wrong-path-sidebar.json',
},
@ -173,7 +175,7 @@ describe('sidebar', () => {
const plugin = await pluginContentDocs(
context,
validateOptions({
validate: normalizePluginOptions,
validate: normalizePluginOptions as Validate<Options, PluginOptions>,
options: {
sidebarPath: undefined,
},
@ -191,7 +193,7 @@ describe('sidebar', () => {
const plugin = await pluginContentDocs(
context,
validateOptions({
validate: normalizePluginOptions,
validate: normalizePluginOptions as Validate<Options, PluginOptions>,
options: {
sidebarPath: false,
},
@ -212,7 +214,10 @@ describe('empty/no docs website', () => {
await fs.ensureDir(path.join(siteDir, 'docs'));
const plugin = await pluginContentDocs(
context,
validateOptions({validate: normalizePluginOptions, options: {}}),
validateOptions({
validate: normalizePluginOptions as Validate<Options, PluginOptions>,
options: {},
}),
);
await expect(
plugin.loadContent!(),
@ -227,7 +232,7 @@ describe('empty/no docs website', () => {
pluginContentDocs(
context,
validateOptions({
validate: normalizePluginOptions,
validate: normalizePluginOptions as Validate<Options, PluginOptions>,
options: {
path: 'path/does/not/exist',
},
@ -245,7 +250,7 @@ describe('simple website', () => {
const context = await loadContext({siteDir});
const sidebarPath = path.join(siteDir, 'sidebars.json');
const options = validateOptions({
validate: normalizePluginOptions,
validate: normalizePluginOptions as Validate<Options, PluginOptions>,
options: {
path: 'docs',
sidebarPath,
@ -299,7 +304,7 @@ describe('simple website', () => {
const content = await plugin.loadContent?.();
const config = applyConfigureWebpack(
plugin.configureWebpack,
plugin.configureWebpack as NonNullable<Plugin['configureWebpack']>,
{
entry: './src/index.js',
output: {
@ -352,7 +357,7 @@ describe('versioned website', () => {
const sidebarPath = path.join(siteDir, 'sidebars.json');
const routeBasePath = 'docs';
const options = validateOptions({
validate: normalizePluginOptions,
validate: normalizePluginOptions as Validate<Options, PluginOptions>,
options: {
routeBasePath,
sidebarPath,
@ -478,7 +483,7 @@ describe('versioned website (community)', () => {
const routeBasePath = 'community';
const pluginId = 'community';
const options = validateOptions({
validate: normalizePluginOptions,
validate: normalizePluginOptions as Validate<Options, PluginOptions>,
options: {
id: 'community',
path: 'community',
@ -581,7 +586,7 @@ describe('site with doc label', () => {
const plugin = await pluginContentDocs(
context,
validateOptions({
validate: normalizePluginOptions,
validate: normalizePluginOptions as Validate<Options, PluginOptions>,
options: {
path: 'docs',
sidebarPath,
@ -626,7 +631,7 @@ describe('site with full autogenerated sidebar', () => {
const plugin = await pluginContentDocs(
context,
validateOptions({
validate: normalizePluginOptions,
validate: normalizePluginOptions as Validate<Options, PluginOptions>,
options: {
path: 'docs',
},
@ -681,7 +686,7 @@ describe('site with partial autogenerated sidebars', () => {
const plugin = await pluginContentDocs(
context,
validateOptions({
validate: normalizePluginOptions,
validate: normalizePluginOptions as Validate<Options, PluginOptions>,
options: {
path: 'docs',
sidebarPath: path.join(
@ -737,7 +742,7 @@ describe('site with partial autogenerated sidebars 2 (fix #4638)', () => {
const plugin = await pluginContentDocs(
context,
validateOptions({
validate: normalizePluginOptions,
validate: normalizePluginOptions as Validate<Options, PluginOptions>,
options: {
path: 'docs',
sidebarPath: path.join(
@ -774,7 +779,7 @@ describe('site with custom sidebar items generator', () => {
const plugin = await pluginContentDocs(
context,
validateOptions({
validate: normalizePluginOptions,
validate: normalizePluginOptions as Validate<Options, PluginOptions>,
options: {
path: 'docs',
sidebarItemsGenerator,

View file

@ -13,14 +13,18 @@ import {
DefaultNumberPrefixParser,
DisabledNumberPrefixParser,
} from '../numberPrefix';
import type {Options} from '@docusaurus/plugin-content-docs';
import type {Options, PluginOptions} from '@docusaurus/plugin-content-docs';
import type {Validate} from '@docusaurus/types';
// The type of remark/rehype plugins can be function/object
const markdownPluginsFunctionStub = () => {};
const markdownPluginsObjectStub = {};
function testValidate(options: Options) {
return validateOptions({validate: normalizePluginOptions, options});
return validateOptions({
validate: normalizePluginOptions as Validate<Options, PluginOptions>,
options,
});
}
const defaultOptions = {

View file

@ -19,6 +19,9 @@ import type {
function createSampleDoc(doc: Pick<DocMetadata, 'id'>): DocMetadata {
return {
sourceDirName: '',
draft: false,
tags: [],
editUrl: 'any',
lastUpdatedAt: 0,
lastUpdatedBy: 'any',
@ -44,12 +47,16 @@ function createSampleVersion(
return {
label: `${version.versionName} label`,
path: '/docs/',
mainDocId: '',
routePriority: undefined,
sidebarFilePath: 'any',
isLast: true,
contentPath: 'any',
contentPathLocalized: 'any',
tagsPath: '/tags/',
banner: null,
badge: true,
className: '',
drafts: [],
docs: [
createSampleDoc({id: 'doc1'}),
createSampleDoc({id: 'doc2'}),
@ -63,6 +70,7 @@ function createSampleVersion(
type: 'category',
label: 'Getting started',
collapsed: false,
collapsible: true,
link: {
type: 'generated-index',
slug: '/category/getting-started-index-slug',

View file

@ -17,6 +17,7 @@ import type {
GlobalPluginData,
GlobalVersion,
ActivePlugin,
GlobalDoc,
} from '@docusaurus/plugin-content-docs/client';
describe('docsClientUtils', () => {
@ -25,10 +26,12 @@ describe('docsClientUtils', () => {
pluginIosId: {
path: '/ios',
versions: [],
breadcrumbs: true,
},
pluginAndroidId: {
path: '/android',
versions: [],
breadcrumbs: true,
},
};
@ -48,7 +51,7 @@ describe('docsClientUtils', () => {
const activePluginIos: ActivePlugin = {
pluginId: 'pluginIosId',
pluginData: data.pluginIosId,
pluginData: data.pluginIosId!,
};
expect(getActivePlugin(data, '/ios')).toEqual(activePluginIos);
expect(getActivePlugin(data, '/ios/')).toEqual(activePluginIos);
@ -56,38 +59,42 @@ describe('docsClientUtils', () => {
const activePluginAndroid: ActivePlugin = {
pluginId: 'pluginAndroidId',
pluginData: data.pluginAndroidId,
pluginData: data.pluginAndroidId!,
};
expect(getActivePlugin(data, '/android')).toEqual(activePluginAndroid);
expect(getActivePlugin(data, '/android/')).toEqual(activePluginAndroid);
expect(getActivePlugin(data, '/android/ijk')).toEqual(activePluginAndroid);
// https://github.com/facebook/docusaurus/issues/6434
const onePluginAtRoot = {
const onePluginAtRoot: {[key: string]: GlobalPluginData} = {
pluginIosId: {
path: '/',
versions: [],
breadcrumbs: true,
},
pluginAndroidId: {
path: '/android',
versions: [],
breadcrumbs: true,
},
};
expect(getActivePlugin(onePluginAtRoot, '/android/foo').pluginId).toBe(
expect(getActivePlugin(onePluginAtRoot, '/android/foo')!.pluginId).toBe(
'pluginAndroidId',
);
const onePluginAtRootReversed = {
const onePluginAtRootReversed: {[key: string]: GlobalPluginData} = {
pluginAndroidId: {
path: '/android',
versions: [],
breadcrumbs: true,
},
pluginIosId: {
path: '/',
versions: [],
breadcrumbs: true,
},
};
expect(
getActivePlugin(onePluginAtRootReversed, '/android/foo').pluginId,
getActivePlugin(onePluginAtRootReversed, '/android/foo')!.pluginId,
).toBe('pluginAndroidId');
});
@ -100,6 +107,7 @@ describe('docsClientUtils', () => {
isLast: false,
docs: [],
mainDocId: '???',
draftIds: [],
},
{
name: 'version2',
@ -108,6 +116,7 @@ describe('docsClientUtils', () => {
isLast: true,
docs: [],
mainDocId: '???',
draftIds: [],
},
{
name: 'version3',
@ -116,6 +125,7 @@ describe('docsClientUtils', () => {
isLast: false,
docs: [],
mainDocId: '???',
draftIds: [],
},
];
@ -123,6 +133,7 @@ describe('docsClientUtils', () => {
getLatestVersion({
path: '???',
versions,
breadcrumbs: true,
}),
).toEqual(versions[1]);
});
@ -138,6 +149,7 @@ describe('docsClientUtils', () => {
path: '/docs/next',
docs: [],
mainDocId: '???',
draftIds: [],
},
{
name: 'version2',
@ -146,6 +158,7 @@ describe('docsClientUtils', () => {
path: '/docs',
docs: [],
mainDocId: '???',
draftIds: [],
},
{
name: 'version1',
@ -154,8 +167,10 @@ describe('docsClientUtils', () => {
path: '/docs/version1',
docs: [],
mainDocId: '???',
draftIds: [],
},
],
breadcrumbs: true,
};
expect(getActiveVersion(data, '/someUnknownPath')).toBeUndefined();
@ -191,7 +206,8 @@ describe('docsClientUtils', () => {
id: 'doc2',
path: '/docs/next/doc2',
},
],
] as GlobalDoc[],
draftIds: [],
};
const version2: GlobalVersion = {
@ -209,7 +225,8 @@ describe('docsClientUtils', () => {
id: 'doc2',
path: '/docs/doc2',
},
],
] as GlobalDoc[],
draftIds: [],
};
const version1: GlobalVersion = {
@ -223,7 +240,8 @@ describe('docsClientUtils', () => {
id: 'doc1',
path: '/docs/version1/',
},
],
] as GlobalDoc[],
draftIds: [],
};
// Shuffle, because order shouldn't matter
@ -236,6 +254,7 @@ describe('docsClientUtils', () => {
const data: GlobalPluginData = {
path: 'docs',
versions,
breadcrumbs: true,
};
expect(getActiveDocContext(data, '/doesNotExist')).toEqual({
@ -320,7 +339,8 @@ describe('docsClientUtils', () => {
id: 'doc2',
path: '/docs/next/doc2',
},
],
] as GlobalDoc[],
draftIds: [],
};
const version2: GlobalVersion = {
@ -338,7 +358,8 @@ describe('docsClientUtils', () => {
id: 'doc2',
path: '/docs/doc2',
},
],
] as GlobalDoc[],
draftIds: [],
};
const version1: GlobalVersion = {
@ -352,7 +373,8 @@ describe('docsClientUtils', () => {
id: 'doc1',
path: '/docs/version1/',
},
],
] as GlobalDoc[],
draftIds: [],
};
// Shuffle, because order shouldn't matter
@ -365,6 +387,7 @@ describe('docsClientUtils', () => {
const data: GlobalPluginData = {
path: 'docs',
versions,
breadcrumbs: true,
};
expect(getDocVersionSuggestions(data, '/doesNotExist')).toEqual({

View file

@ -28,8 +28,12 @@ function createFakeVersion({
}): VersionMetadata {
return {
versionName,
versionLabel: 'Any',
versionPath: 'any',
label: 'Any',
path: 'any',
badge: true,
banner: null,
tagsPath: '/tags/',
className: '',
contentPath,
contentPathLocalized,
sidebarFilePath: 'any',

View file

@ -27,10 +27,6 @@ describe('DefaultSidebarItemsGenerator', () => {
contentPath: 'docs',
},
docs: [],
options: {
sidebarCollapsed: true,
sidebarCollapsible: true,
},
categoriesMetadata: {},
...params,
});
@ -69,6 +65,8 @@ describe('DefaultSidebarItemsGenerator', () => {
frontMatter: {
sidebar_label: 'doc1 sidebar label',
},
title: '',
unversionedId: 'doc1',
},
{
id: 'doc2',
@ -76,6 +74,8 @@ describe('DefaultSidebarItemsGenerator', () => {
sourceDirName: '.',
sidebarPosition: 3,
frontMatter: {},
title: '',
unversionedId: 'doc2',
},
{
id: 'doc3',
@ -83,6 +83,8 @@ describe('DefaultSidebarItemsGenerator', () => {
sourceDirName: '.',
sidebarPosition: 1,
frontMatter: {},
title: '',
unversionedId: 'doc3',
},
{
id: 'doc4',
@ -90,6 +92,8 @@ describe('DefaultSidebarItemsGenerator', () => {
sourceDirName: '.',
sidebarPosition: 1.5,
frontMatter: {},
title: '',
unversionedId: 'doc4',
},
{
id: 'doc5',
@ -97,12 +101,12 @@ describe('DefaultSidebarItemsGenerator', () => {
sourceDirName: '.',
sidebarPosition: undefined,
frontMatter: {},
title: '',
unversionedId: 'doc5',
},
],
options: {
sidebarCollapsed: true,
sidebarCollapsible: true,
},
isCategoryIndex: () => false,
categoriesMetadata: {},
});
expect(sidebarSlice).toMatchSnapshot();
@ -144,6 +148,8 @@ describe('DefaultSidebarItemsGenerator', () => {
sourceDirName: '.',
sidebarPosition: 0,
frontMatter: {},
title: '',
unversionedId: 'intro',
},
{
id: 'tutorials-index',
@ -151,6 +157,8 @@ describe('DefaultSidebarItemsGenerator', () => {
sourceDirName: '01-Tutorials',
sidebarPosition: 2,
frontMatter: {},
title: 'Tutorials',
unversionedId: 'tutorials-index',
},
{
id: 'tutorial2',
@ -158,6 +166,8 @@ describe('DefaultSidebarItemsGenerator', () => {
sourceDirName: '01-Tutorials',
sidebarPosition: 2,
frontMatter: {},
title: '',
unversionedId: 'tutorial2',
},
{
id: 'tutorial1',
@ -165,12 +175,16 @@ describe('DefaultSidebarItemsGenerator', () => {
sourceDirName: '01-Tutorials',
sidebarPosition: 1,
frontMatter: {},
title: '',
unversionedId: 'tutorial1',
},
{
id: 'guides-index',
source: '@site/docs/02-Guides/02-Guides.md', // TODO should we allow to just use "Guides.md" to have an index?
sourceDirName: '02-Guides',
frontMatter: {},
title: 'Guides',
unversionedId: 'guides-index',
},
{
id: 'guide2',
@ -178,6 +192,8 @@ describe('DefaultSidebarItemsGenerator', () => {
sourceDirName: '02-Guides',
sidebarPosition: 2,
frontMatter: {},
title: '',
unversionedId: 'guide2',
},
{
id: 'guide1',
@ -187,6 +203,8 @@ describe('DefaultSidebarItemsGenerator', () => {
frontMatter: {
sidebar_class_name: 'foo',
},
title: '',
unversionedId: 'guide1',
},
{
id: 'nested-guide',
@ -194,6 +212,8 @@ describe('DefaultSidebarItemsGenerator', () => {
sourceDirName: '02-Guides/01-SubGuides',
sidebarPosition: undefined,
frontMatter: {},
title: '',
unversionedId: 'nested-guide',
},
{
id: 'end',
@ -201,12 +221,10 @@ describe('DefaultSidebarItemsGenerator', () => {
sourceDirName: '.',
sidebarPosition: 3,
frontMatter: {},
title: '',
unversionedId: 'end',
},
],
options: {
sidebarCollapsed: true,
sidebarCollapsible: true,
},
});
expect(sidebarSlice).toMatchSnapshot();
@ -249,6 +267,7 @@ describe('DefaultSidebarItemsGenerator', () => {
title: 'Subsubsubfolder category label',
sidebarPosition: undefined,
frontMatter: {},
unversionedId: 'doc1',
},
{
id: 'doc2',
@ -256,6 +275,8 @@ describe('DefaultSidebarItemsGenerator', () => {
sourceDirName: 'subfolder',
sidebarPosition: undefined,
frontMatter: {},
title: '',
unversionedId: 'doc2',
},
{
id: 'doc3',
@ -263,6 +284,8 @@ describe('DefaultSidebarItemsGenerator', () => {
sourceDirName: '.',
sidebarPosition: undefined,
frontMatter: {},
title: '',
unversionedId: 'doc2',
},
{
id: 'doc4',
@ -270,6 +293,8 @@ describe('DefaultSidebarItemsGenerator', () => {
sourceDirName: 'subfolder/subsubfolder',
sidebarPosition: undefined,
frontMatter: {},
title: '',
unversionedId: 'doc4',
},
{
id: 'doc5',
@ -277,6 +302,8 @@ describe('DefaultSidebarItemsGenerator', () => {
sourceDirName: 'subfolder/subsubfolder/subsubsubfolder',
sidebarPosition: undefined,
frontMatter: {},
title: '',
unversionedId: 'doc5',
},
{
id: 'doc6',
@ -284,6 +311,8 @@ describe('DefaultSidebarItemsGenerator', () => {
sourceDirName: 'subfolder/subsubfolder/subsubsubfolder2',
sidebarPosition: undefined,
frontMatter: {},
title: '',
unversionedId: 'doc6',
},
{
id: 'doc7',
@ -291,6 +320,8 @@ describe('DefaultSidebarItemsGenerator', () => {
sourceDirName: 'subfolder/subsubfolder/subsubsubfolder3',
sidebarPosition: 2,
frontMatter: {},
title: '',
unversionedId: 'doc7',
},
{
id: 'doc8',
@ -298,12 +329,10 @@ describe('DefaultSidebarItemsGenerator', () => {
sourceDirName: 'subfolder/subsubfolder/subsubsubfolder3',
sidebarPosition: 1,
frontMatter: {},
title: '',
unversionedId: 'doc8',
},
],
options: {
sidebarCollapsed: true,
sidebarCollapsible: true,
},
});
expect(sidebarSlice).toMatchSnapshot();
@ -339,42 +368,51 @@ describe('DefaultSidebarItemsGenerator', () => {
source: '@site/docs/Category/index.md',
sourceDirName: 'Category',
frontMatter: {},
title: '',
unversionedId: 'parent/doc1',
},
{
id: 'parent/doc2',
source: '@site/docs/Category/doc2.md',
sourceDirName: 'Category',
frontMatter: {},
title: '',
unversionedId: 'parent/doc2',
},
{
id: 'parent/doc3',
source: '@site/docs/Category/doc3.md',
sourceDirName: 'Category',
frontMatter: {},
title: '',
unversionedId: 'parent/doc3',
},
{
id: 'parent/doc4',
source: '@site/docs/Category2/doc1.md',
sourceDirName: 'Category2',
frontMatter: {},
title: '',
unversionedId: 'parent/doc4',
},
{
id: 'parent/doc5',
source: '@site/docs/Category2/index.md',
sourceDirName: 'Category2',
frontMatter: {},
title: '',
unversionedId: 'parent/doc5',
},
{
id: 'parent/doc6',
source: '@site/docs/Category2/doc3.md',
sourceDirName: 'Category2',
frontMatter: {},
title: '',
unversionedId: 'parent/doc6',
},
],
options: {
sidebarCollapsed: true,
sidebarCollapsible: true,
},
isCategoryIndex: () => false,
});
expect(sidebarSlice).toMatchSnapshot();
@ -387,7 +425,7 @@ describe('DefaultSidebarItemsGenerator', () => {
return (
fileName.replace(
`${DefaultNumberPrefixParser(
directories[0],
directories[0]!,
).filename.toLowerCase()}-`,
'',
) === 'index'
@ -409,6 +447,8 @@ describe('DefaultSidebarItemsGenerator', () => {
sourceDirName: '.',
sidebarPosition: 0,
frontMatter: {},
title: '',
unversionedId: 'intro',
},
{
id: 'tutorials-index',
@ -416,6 +456,8 @@ describe('DefaultSidebarItemsGenerator', () => {
sourceDirName: '01-Tutorials',
sidebarPosition: 2,
frontMatter: {},
title: 'Tutorials',
unversionedId: 'tutorials-index',
},
{
id: 'tutorial2',
@ -423,6 +465,8 @@ describe('DefaultSidebarItemsGenerator', () => {
sourceDirName: '01-Tutorials',
sidebarPosition: 2,
frontMatter: {},
title: '',
unversionedId: 'tutorial2',
},
{
id: 'tutorial1',
@ -430,12 +474,16 @@ describe('DefaultSidebarItemsGenerator', () => {
sourceDirName: '01-Tutorials',
sidebarPosition: 1,
frontMatter: {},
title: '',
unversionedId: 'tutorial1',
},
{
id: 'not-guides-index',
source: '@site/docs/02-Guides/README.md',
sourceDirName: '02-Guides',
frontMatter: {},
title: 'Guides',
unversionedId: 'not-guides-index',
},
{
id: 'guide2',
@ -443,6 +491,8 @@ describe('DefaultSidebarItemsGenerator', () => {
sourceDirName: '02-Guides',
sidebarPosition: 2,
frontMatter: {},
title: 'guide2',
unversionedId: 'guide2',
},
{
id: 'guide1',
@ -452,12 +502,10 @@ describe('DefaultSidebarItemsGenerator', () => {
frontMatter: {
sidebar_class_name: 'foo',
},
title: '',
unversionedId: 'guide1',
},
],
options: {
sidebarCollapsed: true,
sidebarCollapsible: true,
},
});
expect(sidebarSlice).toMatchSnapshot();
@ -491,12 +539,9 @@ describe('DefaultSidebarItemsGenerator', () => {
source: '@site/docs/category/intro.md',
sourceDirName: 'category',
frontMatter: {},
title: '',
},
],
options: {
sidebarCollapsed: true,
sidebarCollapsible: true,
},
});
expect(() => generateSidebar()).toThrowErrorMatchingInlineSnapshot(`

View file

@ -11,7 +11,10 @@ import {createSlugger} from '@docusaurus/utils';
import {loadSidebars, DisabledSidebars} from '../index';
import {DefaultSidebarItemsGenerator} from '../generator';
import type {SidebarProcessorParams} from '../types';
import type {DocMetadata} from '@docusaurus/plugin-content-docs';
import type {
DocMetadata,
VersionMetadata,
} from '@docusaurus/plugin-content-docs';
describe('loadSidebars', () => {
const fixtureDir = path.join(__dirname, '__fixtures__', 'sidebars');
@ -25,14 +28,14 @@ describe('loadSidebars', () => {
id: 'bar',
frontMatter: {},
},
],
] as DocMetadata[],
drafts: [],
version: {
path: 'version',
contentPath: path.join(fixtureDir, 'docs'),
contentPathLocalized: path.join(fixtureDir, 'docs'),
},
categoryLabelSlugger: null,
} as VersionMetadata,
categoryLabelSlugger: {slug: (v) => v},
sidebarOptions: {sidebarCollapsed: true, sidebarCollapsible: true},
};
it('sidebars with known sidebar item type', async () => {
@ -137,7 +140,7 @@ describe('loadSidebars', () => {
sourceDirName: 'tutorials/tutorial-basics',
frontMatter: {},
},
],
] as DocMetadata[],
});
expect(result).toMatchSnapshot();
});
@ -146,7 +149,7 @@ describe('loadSidebars', () => {
const sidebarPath = path.join(fixtureDir, 'sidebars-drafts.json');
const result = await loadSidebars(sidebarPath, {
...params,
drafts: [{id: 'draft1'}, {id: 'draft2'}, {id: 'draft3'}],
drafts: [{id: 'draft1'}, {id: 'draft2'}, {id: 'draft3'}] as DocMetadata[],
categoryLabelSlugger: createSlugger(),
});
expect(result).toMatchSnapshot();
@ -169,7 +172,7 @@ describe('loadSidebars', () => {
version: {
contentPath: path.join(fixtureDir, 'invalid-docs'),
contentPathLocalized: path.join(fixtureDir, 'invalid-docs'),
},
} as VersionMetadata,
}),
).rejects.toThrowErrorMatchingInlineSnapshot(`""foo" is not allowed"`);
expect(consoleWarnMock).toBeCalledWith(

View file

@ -41,7 +41,9 @@ describe('normalization', () => {
expect(() =>
normalizeSidebars({
sidebar: {
// @ts-expect-error: test
Category: {type: 'autogenerated', dirName: 'foo'},
// @ts-expect-error: test
Category2: {type: 'autogenerated', dirName: 'bar'},
},
}),
@ -55,6 +57,7 @@ describe('normalization', () => {
'foo',
{
Category: {
// @ts-expect-error: test
type: 'category',
items: ['bar', 'baz'],
},
@ -70,6 +73,7 @@ describe('normalization', () => {
sidebar: [
'foo',
{
// @ts-expect-error: test
Category: 'bar',
},
],
@ -80,6 +84,7 @@ describe('normalization', () => {
expect(() =>
normalizeSidebars({
// @ts-expect-error: test
sidebar: 'item',
}),
).toThrowErrorMatchingInlineSnapshot(

View file

@ -5,7 +5,10 @@
* LICENSE file in the root directory of this source tree.
*/
import {postProcessSidebars} from '../postProcessor';
import {
postProcessSidebars,
type SidebarPostProcessorParams,
} from '../postProcessor';
describe('postProcess', () => {
it('transforms category without subitems', () => {
@ -36,7 +39,7 @@ describe('postProcess', () => {
sidebarOptions: {sidebarCollapsed: true, sidebarCollapsible: true},
version: {path: 'version'},
drafts: [],
},
} as unknown as SidebarPostProcessorParams,
);
expect(processedSidebar).toMatchSnapshot();
@ -56,7 +59,7 @@ describe('postProcess', () => {
sidebarOptions: {sidebarCollapsed: true, sidebarCollapsible: true},
version: {path: 'version'},
drafts: [],
},
} as unknown as SidebarPostProcessorParams,
);
}).toThrowErrorMatchingInlineSnapshot(
`"Sidebar category Bad category has neither any subitem nor a link. This makes this item not able to link to anything."`,
@ -82,7 +85,7 @@ describe('postProcess', () => {
sidebarOptions: {sidebarCollapsed: true, sidebarCollapsible: true},
version: {path: 'version'},
drafts: [],
},
} as unknown as SidebarPostProcessorParams,
),
).toMatchSnapshot();
@ -103,7 +106,7 @@ describe('postProcess', () => {
sidebarOptions: {sidebarCollapsed: false, sidebarCollapsible: false},
version: {path: 'version'},
drafts: [],
},
} as unknown as SidebarPostProcessorParams,
),
).toMatchSnapshot();
@ -123,7 +126,7 @@ describe('postProcess', () => {
sidebarOptions: {sidebarCollapsed: true, sidebarCollapsible: false},
version: {path: 'version'},
drafts: [],
},
} as unknown as SidebarPostProcessorParams,
),
).toMatchSnapshot();
});
@ -153,7 +156,7 @@ describe('postProcess', () => {
sidebarOptions: {sidebarCollapsed: true, sidebarCollapsible: true},
version: {path: 'version'},
drafts: [{id: 'foo', unversionedId: 'foo'}],
},
} as unknown as SidebarPostProcessorParams,
),
).toMatchSnapshot();
});

View file

@ -12,7 +12,7 @@ import {DefaultSidebarItemsGenerator} from '../generator';
import {DefaultNumberPrefixParser} from '../../numberPrefix';
import {isCategoryIndex} from '../../docs';
import type {
SidebarItem,
Sidebar,
SidebarItemsGenerator,
NormalizedSidebar,
NormalizedSidebars,
@ -24,12 +24,12 @@ import type {VersionMetadata} from '@docusaurus/plugin-content-docs';
describe('processSidebars', () => {
function createStaticSidebarItemGenerator(
sidebarSlice: SidebarItem[],
sidebarSlice: NormalizedSidebar,
): SidebarItemsGenerator {
return jest.fn(() => sidebarSlice);
}
const StaticGeneratedSidebarSlice: NormalizedSidebar = [
const StaticGeneratedSidebarSlice: Sidebar = [
{type: 'doc', id: 'doc-generated-id-1'},
{type: 'doc', id: 'doc-generated-id-2'},
];
@ -215,7 +215,7 @@ describe('processSidebars', () => {
},
];
const unprocessedSidebars = {
const unprocessedSidebars: NormalizedSidebars = {
someSidebar: [{type: 'autogenerated', dirName: 'dir2'}],
};

View file

@ -18,7 +18,7 @@ import type {
SidebarItemCategoryLink,
} from './types';
type SidebarPostProcessorParams = SidebarProcessorParams & {
export type SidebarPostProcessorParams = SidebarProcessorParams & {
draftIds: Set<string>;
};

View file

@ -6,10 +6,20 @@
*/
import {normalizePluginOptions} from '@docusaurus/utils-validation';
import {validateOptions, DEFAULT_OPTIONS, type Options} from '../options';
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, options});
return validateOptions({
validate: normalizePluginOptions as Validate<Options, PluginOptions>,
options,
});
}
const defaultOptions = {
@ -24,7 +34,7 @@ describe('validateOptions', () => {
it('accepts correctly defined user options', () => {
const userOptions: Options = {
changefreq: 'yearly',
changefreq: 'yearly' as EnumChangefreq,
priority: 0.9,
ignorePatterns: ['/search/**'],
};
@ -44,7 +54,7 @@ describe('validateOptions', () => {
it('rejects bad changefreq inputs', () => {
expect(() =>
testValidate({changefreq: 'annually'}),
testValidate({changefreq: 'annually' as EnumChangefreq}),
).toThrowErrorMatchingInlineSnapshot(
`""changefreq" must be one of [daily, monthly, always, hourly, weekly, yearly, never]"`,
);

View file

@ -501,7 +501,7 @@ describe('themeConfig', () => {
links: [
{
title: null, // Default value is important to distinguish simple footer from multi-column footer
items: partialConfig.footer.links[0].items,
items: partialConfig.footer.links[0]!.items,
},
],
},
@ -657,7 +657,7 @@ describe('themeConfig', () => {
});
describe('color mode config', () => {
const withDefaultValues = (colorMode: ThemeConfig['colorMode']) =>
const withDefaultValues = (colorMode?: ThemeConfig['colorMode']) =>
_.merge({}, DEFAULT_CONFIG.colorMode, colorMode);
it('switch config', () => {

View file

@ -1032,10 +1032,10 @@ declare module '@theme/Tabs' {
readonly lazy?: boolean;
readonly block?: boolean;
readonly children: readonly ReactElement<TabItemProps>[];
readonly defaultValue?: string | number | null;
readonly defaultValue?: string | null;
readonly values?: readonly {
value: string | number;
label?: string | number;
value: string;
label?: string;
attributes?: {[key: string]: unknown};
}[];
readonly groupId?: string;

View file

@ -117,9 +117,12 @@ describe('Tabs', () => {
<ScrollControllerProvider>
<TabGroupChoiceProvider>
<Tabs
// @ts-expect-error: for an edge-case that we didn't write types for
values={tabs.map((t, idx) => ({label: t, value: idx}))}
// @ts-expect-error: for an edge-case that we didn't write types for
defaultValue={0}>
{tabs.map((t, idx) => (
// @ts-expect-error: for an edge-case that we didn't write types for
<TabItem key={idx} value={idx}>
{t}
</TabItem>

View file

@ -25,7 +25,7 @@ describe('useTitleFormatter', () => {
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');

View file

@ -26,7 +26,7 @@ describe('useAlternatePageUtils', () => {
const mockUseAlternatePageUtils = createUseAlternatePageUtilsMock({
siteConfig: {baseUrl: '/', url: 'https://example.com'},
i18n: {defaultLocale: 'en', currentLocale: 'en'},
});
} as DocusaurusContext);
expect(
mockUseAlternatePageUtils('/').createUrl({
locale: 'zh-Hans',
@ -51,7 +51,7 @@ describe('useAlternatePageUtils', () => {
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',
@ -76,7 +76,7 @@ describe('useAlternatePageUtils', () => {
const mockUseAlternatePageUtils = createUseAlternatePageUtilsMock({
siteConfig: {baseUrl: '/base/', url: 'https://example.com'},
i18n: {defaultLocale: 'en', currentLocale: 'en'},
});
} as DocusaurusContext);
expect(
mockUseAlternatePageUtils('/base/').createUrl({
locale: 'zh-Hans',
@ -101,7 +101,7 @@ describe('useAlternatePageUtils', () => {
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',

View file

@ -25,14 +25,14 @@ describe('useLocalPathname', () => {
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');
});
});

View file

@ -40,7 +40,7 @@ describe('usePluralForm', () => {
.mockImplementation(() => {});
expect(mockUsePluralForm().selectMessage(1, 'one|many')).toBe('one');
expect(mockUsePluralForm().selectMessage(10, 'one|many')).toBe('one');
expect(consoleMock.mock.calls[0][0]).toMatchInlineSnapshot(
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"`,
);
});
@ -65,10 +65,11 @@ describe('usePluralForm', () => {
.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(`
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

View file

@ -12,14 +12,16 @@ import useGlobalData, {
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
// eslint-disable-next-line react/jsx-no-constructed-context-values
<Context.Provider value={{globalData: {foo: 'bar'}}}>
value={{globalData: {foo: 'bar'}} as unknown as DocusaurusContext}>
{children}
</Context.Provider>
),
@ -34,8 +36,12 @@ describe('useAllPluginInstancesData', () => {
renderHook(() => useAllPluginInstancesData('foo'), {
wrapper: ({children}) => (
<Context.Provider
value={
// eslint-disable-next-line react/jsx-no-constructed-context-values
value={{globalData: {foo: {default: 'default', bar: 'bar'}}}}>
{
globalData: {foo: {default: 'default', bar: 'bar'}},
} as unknown as DocusaurusContext
}>
{children}
</Context.Provider>
),
@ -49,8 +55,12 @@ describe('useAllPluginInstancesData', () => {
renderHook(() => useAllPluginInstancesData('bar', {failfast: true}), {
wrapper: ({children}) => (
<Context.Provider
value={
// eslint-disable-next-line react/jsx-no-constructed-context-values
value={{globalData: {foo: {default: 'default', bar: 'bar'}}}}>
{
globalData: {foo: {default: 'default', bar: 'bar'}},
} as unknown as DocusaurusContext
}>
{children}
</Context.Provider>
),
@ -67,8 +77,12 @@ describe('usePluginData', () => {
renderHook(() => usePluginData('foo', 'bar'), {
wrapper: ({children}) => (
<Context.Provider
value={
// eslint-disable-next-line react/jsx-no-constructed-context-values
value={{globalData: {foo: {default: 'default', bar: 'bar'}}}}>
{
globalData: {foo: {default: 'default', bar: 'bar'}},
} as unknown as DocusaurusContext
}>
{children}
</Context.Provider>
),
@ -81,8 +95,12 @@ describe('usePluginData', () => {
renderHook(() => usePluginData('foo'), {
wrapper: ({children}) => (
<Context.Provider
value={
// eslint-disable-next-line react/jsx-no-constructed-context-values
value={{globalData: {foo: {default: 'default', bar: 'bar'}}}}>
{
globalData: {foo: {default: 'default', bar: 'bar'}},
} as unknown as DocusaurusContext
}>
{children}
</Context.Provider>
),
@ -96,8 +114,12 @@ describe('usePluginData', () => {
renderHook(() => usePluginData('foo', 'baz', {failfast: true}), {
wrapper: ({children}) => (
<Context.Provider
value={
// eslint-disable-next-line react/jsx-no-constructed-context-values
value={{globalData: {foo: {default: 'default', bar: 'bar'}}}}>
{
globalData: {foo: {default: 'default', bar: 'bar'}},
} as unknown as DocusaurusContext
}>
{children}
</Context.Provider>
),

View file

@ -126,7 +126,7 @@ describe('wrap', () => {
siteDir,
siteThemePath,
createdFiles: stableCreatedFiles(siteThemePath, result.createdFiles),
firstFileContent: () => fs.readFile(result.createdFiles[0], 'utf8'),
firstFileContent: () => fs.readFile(result.createdFiles[0]!, 'utf8'),
tree: tree(siteThemePath),
};
}

View file

@ -55,13 +55,13 @@ class MockExitError extends Error {
}
function createExitMock() {
let mock: jest.SpyInstance;
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);
});
throw new MockExitError(code!);
}) as jest.SpyInstance<(code?: number) => never>;
});
// eslint-disable-next-line jest/require-top-level-describe
afterEach(async () => {

View file

@ -8,20 +8,20 @@
import {loadClientModules} from '../clientModules';
import type {LoadedPlugin} from '@docusaurus/types';
const pluginEmpty: LoadedPlugin = {
const pluginEmpty = {
name: 'plugin-empty',
path: __dirname,
};
} as LoadedPlugin;
const pluginFooBar: LoadedPlugin = {
const pluginFooBar = {
name: 'plugin-foo-bar',
path: __dirname,
getClientModules() {
return ['foo', 'bar'];
},
};
} as LoadedPlugin;
const pluginHelloWorld: LoadedPlugin = {
const pluginHelloWorld = {
plugin: 'plugin-hello-world',
path: __dirname,
getClientModules() {
@ -31,7 +31,7 @@ const pluginHelloWorld: LoadedPlugin = {
'world',
];
},
};
} as unknown as LoadedPlugin;
describe('loadClientModules', () => {
it('loads an empty plugin', () => {

View file

@ -10,15 +10,16 @@ import {
DEFAULT_CONFIG,
validateConfig,
} from '../configValidation';
import type {DocusaurusConfig} from '@docusaurus/types';
import type {Config} from '@docusaurus/types';
const baseConfig: DocusaurusConfig = {
const baseConfig = {
baseUrl: '/',
title: 'my site',
url: 'https://mysite.com',
};
} as Config;
const normalizeConfig = (config) => validateConfig({...baseConfig, ...config});
const normalizeConfig = (config: Partial<Config>) =>
validateConfig({...baseConfig, ...config});
describe('normalizeConfig', () => {
it('normalizes empty config', () => {
@ -79,6 +80,7 @@ describe('normalizeConfig', () => {
it('throws error for unknown field', () => {
expect(() => {
normalizeConfig({
// @ts-expect-error: test
invalid: true,
});
}).toThrowErrorMatchingSnapshot();
@ -113,6 +115,7 @@ describe('normalizeConfig', () => {
])(`%s for the input of: %p`, (_message, plugins) => {
expect(() => {
normalizeConfig({
// @ts-expect-error: test
plugins,
});
}).toThrowErrorMatchingSnapshot();
@ -139,6 +142,7 @@ describe('normalizeConfig', () => {
])(`%s for the input of: %p`, (_message, themes) => {
expect(() => {
normalizeConfig({
// @ts-expect-error: test
themes,
});
}).toThrowErrorMatchingSnapshot();
@ -174,12 +178,12 @@ describe('normalizeConfig', () => {
'should accept [function, object] for plugin',
[[() => {}, {it: 'should work'}]],
],
['should accept false/null for plugin', [false, null, 'classic']],
['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.toThrowError();
});
@ -218,13 +222,14 @@ describe('normalizeConfig', () => {
expect(() => {
normalizeConfig({
themes,
});
} as Config);
}).not.toThrowError();
});
it('throws error if themes is not array', () => {
expect(() => {
normalizeConfig({
// @ts-expect-error: test
themes: {},
});
}).toThrowErrorMatchingInlineSnapshot(`
@ -236,6 +241,7 @@ describe('normalizeConfig', () => {
it('throws error if presets is not array', () => {
expect(() => {
normalizeConfig({
// @ts-expect-error: test
presets: {},
});
}).toThrowErrorMatchingInlineSnapshot(`
@ -247,6 +253,7 @@ describe('normalizeConfig', () => {
it('throws error if presets looks invalid', () => {
expect(() => {
normalizeConfig({
// @ts-expect-error: test
presets: [() => {}],
});
}).toThrowErrorMatchingInlineSnapshot(`
@ -314,10 +321,10 @@ describe('config warnings', () => {
const warning = getWarning({
...baseConfig,
url: 'https://mysite.com/someSubpath',
});
})!;
expect(warning).toBeDefined();
expect(warning.details).toHaveLength(1);
expect(warning.details[0].message).toMatchInlineSnapshot(
expect(warning.details[0]!.message).toMatchInlineSnapshot(
`"Docusaurus config validation warning. Field "url": the url is not supposed to contain a sub-path like '/someSubpath', please use the baseUrl field for sub-paths"`,
);
});

View file

@ -8,11 +8,11 @@
import {loadHtmlTags} from '../htmlTags';
import type {LoadedPlugin} from '@docusaurus/types';
const pluginEmpty: LoadedPlugin = {
const pluginEmpty = {
name: 'plugin-empty',
};
} as LoadedPlugin;
const pluginPreBodyTags: LoadedPlugin = {
const pluginPreBodyTags = {
name: 'plugin-preBodyTags',
injectHtmlTags() {
return {
@ -26,9 +26,9 @@ const pluginPreBodyTags: LoadedPlugin = {
},
};
},
};
} as unknown as LoadedPlugin;
const pluginHeadTags: LoadedPlugin = {
const pluginHeadTags = {
name: 'plugin-headTags-only',
injectHtmlTags() {
return {
@ -59,9 +59,9 @@ const pluginHeadTags: LoadedPlugin = {
],
};
},
};
} as unknown as LoadedPlugin;
const pluginPostBodyTags: LoadedPlugin = {
const pluginPostBodyTags = {
name: 'plugin-postBody-tags',
injectHtmlTags() {
return {
@ -74,14 +74,14 @@ const pluginPostBodyTags: LoadedPlugin = {
],
};
},
};
} as unknown as LoadedPlugin;
const pluginMaybeInjectHeadTags: LoadedPlugin = {
const pluginMaybeInjectHeadTags = {
name: 'plugin-postBody-tags',
injectHtmlTags() {
return undefined;
},
};
} as unknown as LoadedPlugin;
describe('loadHtmlTags', () => {
it('works for an empty plugin', () => {
@ -170,6 +170,7 @@ describe('loadHtmlTags', () => {
it('throws for invalid tag', () => {
expect(() =>
loadHtmlTags([
// @ts-expect-error: test
{
injectHtmlTags() {
return {
@ -192,6 +193,7 @@ describe('loadHtmlTags', () => {
expect(() =>
loadHtmlTags([
{
// @ts-expect-error: test
injectHtmlTags() {
return {
headTags: {
@ -210,6 +212,7 @@ describe('loadHtmlTags', () => {
expect(() =>
loadHtmlTags([
{
// @ts-expect-error: test
injectHtmlTags() {
return {
headTags: 2,

View file

@ -180,7 +180,7 @@ describe('loadI18n', () => {
},
'it',
);
expect(consoleSpy.mock.calls[0][0]).toMatch(
expect(consoleSpy.mock.calls[0]![0]).toMatch(
/The locale .*it.* was not found in your site configuration/,
);
});

View file

@ -8,6 +8,7 @@
import {jest} from '@jest/globals';
import path from 'path';
import {getPluginVersion, loadSiteMetadata} from '../siteMetadata';
import type {LoadedPlugin} from '@docusaurus/types';
describe('getPluginVersion', () => {
it('detects external packages plugins versions', async () => {
@ -51,11 +52,11 @@ describe('loadSiteMetadata', () => {
name: '@docusaurus/plugin-content-docs',
},
},
],
] as LoadedPlugin[],
siteDir: path.join(__dirname, '__fixtures__/siteMetadata'),
}),
).resolves.toMatchSnapshot();
expect(consoleMock.mock.calls[0][0]).toMatchInlineSnapshot(`
expect(consoleMock.mock.calls[0]![0]).toMatchInlineSnapshot(`
"[ERROR] Invalid docusaurus-plugin-content-docs version 1.0.0.
All official @docusaurus/* packages should have the exact same version as @docusaurus/core (<CURRENT_VERSION>).
Maybe you want to check, or regenerate your yarn.lock or package-lock.json file?"

View file

@ -25,8 +25,8 @@ describe('getAllFinalRoutes', () => {
},
];
expect(getAllFinalRoutes(routes)).toEqual([
routes[0].routes[0],
routes[0].routes[1],
routes[0]!.routes![0],
routes[0]!.routes![1],
routes[1],
]);
});

View file

@ -7,7 +7,7 @@
import path from 'path';
import {loadPlugins} from '..';
import type {Props} from '@docusaurus/types';
import type {Plugin, Props} from '@docusaurus/types';
describe('loadPlugins', () => {
it('loads plugins', async () => {
@ -23,7 +23,8 @@ describe('loadPlugins', () => {
themeConfig: {},
presets: [],
plugins: [
() => ({
() =>
({
name: 'test1',
prop: 'a',
async loadContent() {
@ -39,7 +40,7 @@ describe('loadPlugins', () => {
});
actions.setGlobalData({content, prop: this.prop});
},
}),
} as Plugin & ThisType<{prop: 'a'}>),
],
themes: [
() => ({

View file

@ -6,7 +6,6 @@
*/
import path from 'path';
import {loadPresets} from '../presets';
import type {LoadContext} from '@docusaurus/types';
@ -17,7 +16,7 @@ describe('loadPresets', () => {
siteConfig: {
presets: [],
},
} as LoadContext;
} as unknown as LoadContext;
const presets = await loadPresets(context);
expect(presets).toMatchInlineSnapshot(`
{

View file

@ -292,13 +292,12 @@ describe('writePluginTranslations', () => {
key3: {message: 'key3 message'},
},
},
// @ts-expect-error: enough for this test
plugin: {
name: 'my-plugin-name',
options: {
id: undefined,
},
id: 'default',
},
} as LoadedPlugin,
});
await expect(fs.readJSON(filePath)).resolves.toEqual({
@ -698,7 +697,7 @@ describe('applyDefaultCodeTranslations', () => {
},
});
expect(consoleWarnMock).toHaveBeenCalledTimes(1);
expect(consoleWarnMock.mock.calls[0][0]).toMatch(/unknownId/);
expect(consoleWarnMock.mock.calls[0]![0]).toMatch(/unknownId/);
});
it('works for realistic scenario', () => {
@ -740,7 +739,7 @@ describe('applyDefaultCodeTranslations', () => {
},
});
expect(consoleWarnMock).toHaveBeenCalledTimes(1);
expect(consoleWarnMock.mock.calls[0][0]).toMatch(/idUnknown1/);
expect(consoleWarnMock.mock.calls[0][0]).toMatch(/idUnknown2/);
expect(consoleWarnMock.mock.calls[0]![0]).toMatch(/idUnknown1/);
expect(consoleWarnMock.mock.calls[0]![0]).toMatch(/idUnknown2/);
});
});

View file

@ -721,7 +721,7 @@ export default function MyComponent(props: Props) {
message: 'plugin2 message 2',
},
});
expect(consoleWarnMock.mock.calls[0][0]).toMatch(
expect(consoleWarnMock.mock.calls[0]![0]).toMatch(
/.*\[WARNING\].* Translation extraction warnings for file .*src.theme.file4\.jsx.*\n.*- translate\(\) first arg should be a statically evaluable object\./,
);
});

View file

@ -61,7 +61,7 @@ describe('extending generated webpack config', () => {
};
// @ts-expect-error: Testing an edge-case that we did not write types for
const configureWebpack: Plugin['configureWebpack'] = (
const configureWebpack: NonNullable<Plugin['configureWebpack']> = (
generatedConfig,
isServer,
) => {
@ -129,7 +129,7 @@ describe('extending generated webpack config', () => {
const createConfigureWebpack =
(mergeStrategy?: {
[key: string]: 'prepend' | 'append';
}): Plugin['configureWebpack'] =>
}): NonNullable<Plugin['configureWebpack']> =>
() => ({
module: {
rules: [{use: 'zzz'}],
@ -272,7 +272,7 @@ describe('extending PostCSS', () => {
expect(postCssLoader1.loader).toBe('postcss-loader-1');
const pluginNames1 = postCssLoader1.options.postcssOptions.plugins.map(
(p: unknown) => p[0],
(p: unknown[]) => p[0],
);
expect(pluginNames1).toHaveLength(4);
expect(pluginNames1).toEqual([
@ -287,7 +287,7 @@ describe('extending PostCSS', () => {
expect(postCssLoader2.loader).toBe('postcss-loader-2');
const pluginNames2 = postCssLoader2.options.postcssOptions.plugins.map(
(p: unknown) => p[0],
(p: unknown[]) => p[0],
);
expect(pluginNames2).toHaveLength(4);
expect(pluginNames2).toEqual([

View file

@ -13,6 +13,7 @@ import {
sortAliases,
createAliasesForTheme,
} from '../index';
import type {LoadedPlugin} from '@docusaurus/types';
describe('sortAliases', () => {
// https://github.com/facebook/docusaurus/issues/6878
@ -197,7 +198,7 @@ describe('loadThemeAliases', () => {
plugins: [
{getThemePath: () => theme1Path},
{getThemePath: () => theme2Path},
],
] as LoadedPlugin[],
});
// Testing entries, because order matters!