test: fix some type errors in test files (#7486)

This commit is contained in:
Joshua Chen 2022-05-25 11:46:10 +08:00 committed by GitHub
parent 624735bd92
commit e2e40b8f5f
No known key found for this signature in database
GPG key ID: 4AEE18F83AFDEB23
50 changed files with 319 additions and 182 deletions

View file

@ -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)),
);
}
});
});

View file

@ -9,6 +9,7 @@ import {toGlobalDataVersion} from '../globalData';
import {createSidebarsUtils} from '../sidebars/utils';
import {getCategoryGeneratedIndexMetadataList} from '../categoryGeneratedIndex';
import type {Sidebars} from '../sidebars/types';
import type {DocMetadata} from '@docusaurus/plugin-content-docs';
describe('toGlobalDataVersion', () => {
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,

View file

@ -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';
import type {
LoadedVersion,
PropSidebarItemLink,
} from '@docusaurus/plugin-content-docs';
import type {
SidebarItemsGeneratorOption,
NormalizedSidebar,
} from '../sidebars/types';
function findDocById(version: LoadedVersion, unversionedId: string) {
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<SidebarItemsGeneratorOption>[0] =
customSidebarItemsGeneratorMock.mock.calls[0][0];
const generatorArg = (
customSidebarItemsGeneratorMock.mock
.calls[0] as unknown as Parameters<SidebarItemsGeneratorOption>
)[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();
});

View file

@ -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,
},

View file

@ -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,

View file

@ -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<PluginOptions>;
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 & {

View file

@ -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(
{

View file

@ -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'),