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

17
jest/deps.d.ts vendored Normal file
View file

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

View file

@ -21,7 +21,7 @@ function process(doc: string, plugins: Plugin[] = []) {
return removePosition(processor.runSync(processor.parse(doc)), true); return removePosition(processor.runSync(processor.parse(doc)), true);
} }
function heading(label: string, id: string) { function heading(label: string | null, id: string) {
return u( return u(
'heading', 'heading',
{depth: 2, data: {id, hProperties: {id}}}, {depth: 2, data: {id, hProperties: {id}}},

View file

@ -13,15 +13,15 @@ import plugin from '..';
import transformImage, {type PluginOptions} from '../../transformImage'; import transformImage, {type PluginOptions} from '../../transformImage';
const processFixture = async (name: string, options?: PluginOptions) => { const processFixture = async (name: string, options?: PluginOptions) => {
const filePath = path.join(__dirname, `__fixtures__/${name}.md`); const siteDir = path.join(__dirname, `__fixtures__`);
const staticDirs = [ const staticDirs = [
path.join(__dirname, '__fixtures__/static'), path.join(siteDir, 'static'),
path.join(__dirname, '__fixtures__/static2'), path.join(siteDir, 'static2'),
]; ];
const file = await vfile.read(filePath); const file = await vfile.read(path.join(siteDir, `${name}.md`));
const result = await remark() const result = await remark()
.use(mdx) .use(mdx)
.use(transformImage, {...options, filePath, staticDirs}) .use(transformImage, {...options, siteDir, staticDirs})
.use(plugin, { .use(plugin, {
...options, ...options,
staticDirs, staticDirs,

View file

@ -9,7 +9,7 @@ import {normalizePluginOptions} from '@docusaurus/utils-validation';
import {validateOptions, DEFAULT_OPTIONS} from '../options'; import {validateOptions, DEFAULT_OPTIONS} from '../options';
import type {Options} from '../options'; import type {Options} from '../options';
function testValidate(options: Options) { function testValidate(options?: Options) {
return validateOptions({validate: normalizePluginOptions, options}); return validateOptions({validate: normalizePluginOptions, options});
} }

View file

@ -176,11 +176,11 @@ describe('writeRedirectFiles', () => {
await writeRedirectFiles(filesMetadata); await writeRedirectFiles(filesMetadata);
await expect( await expect(
fs.readFile(filesMetadata[0].fileAbsolutePath, 'utf8'), fs.readFile(filesMetadata[0]!.fileAbsolutePath, 'utf8'),
).resolves.toBe('content 1'); ).resolves.toBe('content 1');
await expect( await expect(
fs.readFile(filesMetadata[1].fileAbsolutePath, 'utf8'), fs.readFile(filesMetadata[1]!.fileAbsolutePath, 'utf8'),
).resolves.toBe('content 2'); ).resolves.toBe('content 2');
}); });
@ -195,7 +195,7 @@ describe('writeRedirectFiles', () => {
]; ];
await fs.outputFile( await fs.outputFile(
filesMetadata[0].fileAbsolutePath, filesMetadata[0]!.fileAbsolutePath,
'file already exists!', 'file already exists!',
); );

View file

@ -66,6 +66,6 @@ const UserOptionsSchema = Joi.object<PluginOptions>({
export function validateOptions({ export function validateOptions({
validate, validate,
options: userOptions, options: userOptions,
}: OptionValidationContext<Options, PluginOptions>): PluginOptions { }: OptionValidationContext<Options | undefined, PluginOptions>): PluginOptions {
return validate(UserOptionsSchema, userOptions); return validate(UserOptionsSchema, userOptions);
} }

View file

@ -44,11 +44,14 @@ exports[`translateContent falls back when translation is incomplete 1`] = `
], ],
"blogPosts": [ "blogPosts": [
{ {
"content": "",
"id": "hello", "id": "hello",
"metadata": { "metadata": {
"authors": [],
"date": 2021-07-19T00:00:00.000Z, "date": 2021-07-19T00:00:00.000Z,
"description": "/blog/2021/06/19/hello", "description": "/blog/2021/06/19/hello",
"formattedDate": "June 19, 2021", "formattedDate": "June 19, 2021",
"frontMatter": {},
"permalink": "/blog/2021/06/19/hello", "permalink": "/blog/2021/06/19/hello",
"source": "/blog/2021/06/19/hello", "source": "/blog/2021/06/19/hello",
"tags": [], "tags": [],
@ -85,11 +88,14 @@ exports[`translateContent returns translated loaded 1`] = `
], ],
"blogPosts": [ "blogPosts": [
{ {
"content": "",
"id": "hello", "id": "hello",
"metadata": { "metadata": {
"authors": [],
"date": 2021-07-19T00:00:00.000Z, "date": 2021-07-19T00:00:00.000Z,
"description": "/blog/2021/06/19/hello", "description": "/blog/2021/06/19/hello",
"formattedDate": "June 19, 2021", "formattedDate": "June 19, 2021",
"frontMatter": {},
"permalink": "/blog/2021/06/19/hello", "permalink": "/blog/2021/06/19/hello",
"source": "/blog/2021/06/19/hello", "source": "/blog/2021/06/19/hello",
"tags": [], "tags": [],

View file

@ -211,7 +211,11 @@ describe('linkify', () => {
title: 'date-matter', title: 'date-matter',
}, },
truncated: false, truncated: false,
frontMatter: {},
authors: [],
formattedDate: '',
}, },
content: '',
}, },
]; ];

View file

@ -21,6 +21,9 @@ const DefaultI18N: I18n = {
defaultLocale: 'en', defaultLocale: 'en',
localeConfigs: { localeConfigs: {
en: { en: {
label: 'English',
direction: 'ltr',
htmlLang: 'en',
calendar: 'gregory', calendar: 'gregory',
}, },
}, },

View file

@ -56,7 +56,9 @@ function testField(params: {
); );
} catch (err) { } catch (err) {
// eslint-disable-next-line jest/no-conditional-expect // 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

@ -41,7 +41,14 @@ function getI18n(locale: string): I18n {
currentLocale: locale, currentLocale: locale,
locales: [locale], locales: [locale],
defaultLocale: 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 siteDir = path.join(__dirname, '__fixtures__', 'website');
const blogPostsFrench = await getBlogPosts(siteDir, {}, getI18n('fr')); const blogPostsFrench = await getBlogPosts(siteDir, {}, getI18n('fr'));
expect(blogPostsFrench).toHaveLength(8); expect(blogPostsFrench).toHaveLength(8);
expect(blogPostsFrench[0].metadata.formattedDate).toMatchInlineSnapshot( expect(blogPostsFrench[0]!.metadata.formattedDate).toMatchInlineSnapshot(
`"6 mars 2021"`, `"6 mars 2021"`,
); );
expect(blogPostsFrench[1].metadata.formattedDate).toMatchInlineSnapshot( expect(blogPostsFrench[1]!.metadata.formattedDate).toMatchInlineSnapshot(
`"5 mars 2021"`, `"5 mars 2021"`,
); );
expect(blogPostsFrench[2].metadata.formattedDate).toMatchInlineSnapshot( expect(blogPostsFrench[2]!.metadata.formattedDate).toMatchInlineSnapshot(
`"16 août 2020"`, `"16 août 2020"`,
); );
expect(blogPostsFrench[3].metadata.formattedDate).toMatchInlineSnapshot( expect(blogPostsFrench[3]!.metadata.formattedDate).toMatchInlineSnapshot(
`"15 août 2020"`, `"15 août 2020"`,
); );
expect(blogPostsFrench[4].metadata.formattedDate).toMatchInlineSnapshot( expect(blogPostsFrench[4]!.metadata.formattedDate).toMatchInlineSnapshot(
`"27 février 2020"`, `"27 février 2020"`,
); );
expect(blogPostsFrench[5].metadata.formattedDate).toMatchInlineSnapshot( expect(blogPostsFrench[5]!.metadata.formattedDate).toMatchInlineSnapshot(
`"2 janvier 2019"`, `"2 janvier 2019"`,
); );
expect(blogPostsFrench[6].metadata.formattedDate).toMatchInlineSnapshot( expect(blogPostsFrench[6]!.metadata.formattedDate).toMatchInlineSnapshot(
`"1 janvier 2019"`, `"1 janvier 2019"`,
); );
expect(blogPostsFrench[7].metadata.formattedDate).toMatchInlineSnapshot( expect(blogPostsFrench[7]!.metadata.formattedDate).toMatchInlineSnapshot(
`"14 décembre 2018"`, `"14 décembre 2018"`,
); );
}); });

View file

@ -9,7 +9,7 @@ import {normalizePluginOptions} from '@docusaurus/utils-validation';
import {validateOptions, DEFAULT_OPTIONS} from '../options'; import {validateOptions, DEFAULT_OPTIONS} from '../options';
import type {Options} from '@docusaurus/plugin-content-blog'; import type {Options} from '@docusaurus/plugin-content-blog';
function testValidate(options: Options) { function testValidate(options?: Options) {
return validateOptions({validate: normalizePluginOptions, options}); return validateOptions({validate: normalizePluginOptions, options});
} }
@ -44,13 +44,14 @@ describe('validateOptions', () => {
}); });
it('accepts valid user options', () => { it('accepts valid user options', () => {
const userOptions = { const userOptions: Options = {
...defaultOptions, ...defaultOptions,
routeBasePath: 'myBlog', routeBasePath: 'myBlog',
beforeDefaultRemarkPlugins: [], beforeDefaultRemarkPlugins: [],
beforeDefaultRehypePlugins: [markdownPluginsFunctionStub], beforeDefaultRehypePlugins: [markdownPluginsFunctionStub],
remarkPlugins: [[markdownPluginsFunctionStub, {option1: '42'}]], remarkPlugins: [[markdownPluginsFunctionStub, {option1: '42'}]],
rehypePlugins: [ rehypePlugins: [
// @ts-expect-error: it seems to work in practice
markdownPluginsObjectStub, markdownPluginsObjectStub,
[markdownPluginsFunctionStub, {option1: '42'}], [markdownPluginsFunctionStub, {option1: '42'}],
], ],
@ -73,6 +74,7 @@ describe('validateOptions', () => {
expect(() => expect(() =>
testValidate({ testValidate({
feedOptions: { feedOptions: {
// @ts-expect-error: test
type: 'none', type: 'none',
}, },
}), }),
@ -138,6 +140,7 @@ describe('validateOptions', () => {
it('rejects "abcdef" sidebar count', () => { it('rejects "abcdef" sidebar count', () => {
const userOptions = {blogSidebarCount: 'abcdef'}; const userOptions = {blogSidebarCount: 'abcdef'};
// @ts-expect-error: test
expect(() => testValidate(userOptions)).toThrowErrorMatchingInlineSnapshot( expect(() => testValidate(userOptions)).toThrowErrorMatchingInlineSnapshot(
`""blogSidebarCount" must be one of [ALL, number]"`, `""blogSidebarCount" must be one of [ALL, number]"`,
); );
@ -153,6 +156,7 @@ describe('validateOptions', () => {
it('rejects 42 sidebar title', () => { it('rejects 42 sidebar title', () => {
const userOptions = {blogSidebarTitle: 42}; const userOptions = {blogSidebarTitle: 42};
// @ts-expect-error: test
expect(() => testValidate(userOptions)).toThrowErrorMatchingInlineSnapshot( expect(() => testValidate(userOptions)).toThrowErrorMatchingInlineSnapshot(
`""blogSidebarTitle" must be a string"`, `""blogSidebarTitle" must be a string"`,
); );

View file

@ -33,7 +33,10 @@ const sampleBlogPosts: BlogPost[] = [
tags: [], tags: [],
title: 'Hello', title: 'Hello',
truncated: true, truncated: true,
authors: [],
frontMatter: {},
}, },
content: '',
}, },
]; ];

View file

@ -135,7 +135,7 @@ const PluginOptionSchema = Joi.object<PluginOptions>({
export function validateOptions({ export function validateOptions({
validate, validate,
options, options,
}: OptionValidationContext<Options, PluginOptions>): PluginOptions { }: OptionValidationContext<Options | undefined, PluginOptions>): PluginOptions {
const validatedOptions = validate(PluginOptionSchema, options); const validatedOptions = validate(PluginOptionSchema, options);
return validatedOptions; return validatedOptions;
} }

View file

@ -13,7 +13,7 @@ import footnoteIDFixer from '../footnoteIDFixer';
const processFixture = async (name: string) => { const processFixture = async (name: string) => {
const filepath = path.join(__dirname, `__fixtures__/${name}.md`); 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, filepath,
remarkPlugins: [footnoteIDFixer], remarkPlugins: [footnoteIDFixer],
}); });

View file

@ -56,7 +56,9 @@ function testField(params: {
); );
} catch (err) { } catch (err) {
// eslint-disable-next-line jest/no-conditional-expect // 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 {createSidebarsUtils} from '../sidebars/utils';
import {getCategoryGeneratedIndexMetadataList} from '../categoryGeneratedIndex'; import {getCategoryGeneratedIndexMetadataList} from '../categoryGeneratedIndex';
import type {Sidebars} from '../sidebars/types'; import type {Sidebars} from '../sidebars/types';
import type {DocMetadata} from '@docusaurus/plugin-content-docs';
describe('toGlobalDataVersion', () => { describe('toGlobalDataVersion', () => {
it('generates the right docs, sidebars, and metadata', () => { it('generates the right docs, sidebars, and metadata', () => {
@ -25,7 +26,7 @@ describe('toGlobalDataVersion', () => {
sidebar: 'tutorial', sidebar: 'tutorial',
frontMatter: {}, frontMatter: {},
}, },
]; ] as DocMetadata[];
const sidebars: Sidebars = { const sidebars: Sidebars = {
tutorial: [ tutorial: [
{ {
@ -46,6 +47,8 @@ describe('toGlobalDataVersion', () => {
id: 'doc', id: 'doc',
}, },
], ],
collapsed: false,
collapsible: true,
}, },
], ],
links: [ links: [
@ -75,6 +78,8 @@ describe('toGlobalDataVersion', () => {
id: 'doc', id: 'doc',
}, },
], ],
collapsed: false,
collapsible: true,
}, },
], ],
}; };
@ -85,7 +90,6 @@ describe('toGlobalDataVersion', () => {
label: 'Label', label: 'Label',
isLast: true, isLast: true,
path: '/current', path: '/current',
mainDocId: 'main',
docs, docs,
drafts: [ drafts: [
{ {
@ -93,7 +97,7 @@ describe('toGlobalDataVersion', () => {
permalink: '/current/draft', permalink: '/current/draft',
sidebar: undefined, sidebar: undefined,
}, },
], ] as DocMetadata[],
sidebars, sidebars,
categoryGeneratedIndices: getCategoryGeneratedIndexMetadataList({ categoryGeneratedIndices: getCategoryGeneratedIndexMetadataList({
docs, docs,

View file

@ -26,13 +26,28 @@ import * as cliDocs from '../cli';
import {validateOptions} from '../options'; import {validateOptions} from '../options';
import type {RouteConfig} from '@docusaurus/types'; import type {RouteConfig} from '@docusaurus/types';
import type {LoadedVersion} from '@docusaurus/plugin-content-docs'; import type {
import type {SidebarItem, SidebarItemsGeneratorOption} from '../sidebars/types'; 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); 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); const doc = findDocById(version, unversionedId);
if (!doc) { if (!doc) {
throw new Error( throw new Error(
@ -83,7 +98,10 @@ Entries created:
getGlobalData: () => globalDataContainer, getGlobalData: () => globalDataContainer,
getRouteConfigs: () => routeConfigs, getRouteConfigs: () => routeConfigs,
checkVersionMetadataPropCreated: (version: LoadedVersion) => { checkVersionMetadataPropCreated: (version: LoadedVersion | undefined) => {
if (!version) {
throw new Error('Version not found');
}
const versionMetadataProp = getCreatedDataByPrefix( const versionMetadataProp = getCreatedDataByPrefix(
`version-${_.kebabCase(version.versionName)}-metadata-prop`, `version-${_.kebabCase(version.versionName)}-metadata-prop`,
); );
@ -164,7 +182,7 @@ describe('sidebar', () => {
const result = await plugin.loadContent!(); const result = await plugin.loadContent!();
expect(result.loadedVersions).toHaveLength(1); expect(result.loadedVersions).toHaveLength(1);
expect(result.loadedVersions[0].sidebars).toMatchSnapshot(); expect(result.loadedVersions[0]!.sidebars).toMatchSnapshot();
}); });
it('site with disabled sidebar', async () => { it('site with disabled sidebar', async () => {
@ -182,7 +200,7 @@ describe('sidebar', () => {
const result = await plugin.loadContent!(); const result = await plugin.loadContent!();
expect(result.loadedVersions).toHaveLength(1); 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(getDocById(currentVersion, 'foo/bar')).toMatchSnapshot();
expect(currentVersion.sidebars).toMatchSnapshot(); expect(currentVersion!.sidebars).toMatchSnapshot();
const {actions, utils} = createFakeActions(pluginContentDir); const {actions, utils} = createFakeActions(pluginContentDir);
@ -427,10 +445,12 @@ describe('versioned website', () => {
expect(getDocById(version101, 'hello')).toMatchSnapshot(); expect(getDocById(version101, 'hello')).toMatchSnapshot();
expect(getDocById(version100, 'foo/baz')).toMatchSnapshot(); expect(getDocById(version100, 'foo/baz')).toMatchSnapshot();
expect(currentVersion.sidebars).toMatchSnapshot('current version sidebars'); expect(currentVersion!.sidebars).toMatchSnapshot(
expect(version101.sidebars).toMatchSnapshot('101 version sidebars'); 'current version sidebars',
expect(version100.sidebars).toMatchSnapshot('100 version sidebars'); );
expect(versionWithSlugs.sidebars).toMatchSnapshot( expect(version101!.sidebars).toMatchSnapshot('101 version sidebars');
expect(version100!.sidebars).toMatchSnapshot('100 version sidebars');
expect(versionWithSlugs!.sidebars).toMatchSnapshot(
'withSlugs version sidebars', 'withSlugs version sidebars',
); );
@ -534,8 +554,10 @@ describe('versioned website (community)', () => {
expect(getDocById(currentVersion, 'team')).toMatchSnapshot(); expect(getDocById(currentVersion, 'team')).toMatchSnapshot();
expect(getDocById(version100, 'team')).toMatchSnapshot(); expect(getDocById(version100, 'team')).toMatchSnapshot();
expect(currentVersion.sidebars).toMatchSnapshot('current version sidebars'); expect(currentVersion!.sidebars).toMatchSnapshot(
expect(version100.sidebars).toMatchSnapshot('100 version sidebars'); 'current version sidebars',
);
expect(version100!.sidebars).toMatchSnapshot('100 version sidebars');
const {actions, utils} = createFakeActions(pluginContentDir); const {actions, utils} = createFakeActions(pluginContentDir);
await plugin.contentLoaded!({ await plugin.contentLoaded!({
@ -544,8 +566,8 @@ describe('versioned website (community)', () => {
allContent: {}, allContent: {},
}); });
utils.checkVersionMetadataPropCreated(currentVersion); utils.checkVersionMetadataPropCreated(currentVersion!);
utils.checkVersionMetadataPropCreated(version100); utils.checkVersionMetadataPropCreated(version100!);
utils.expectSnapshot(); utils.expectSnapshot();
}); });
@ -574,18 +596,22 @@ describe('site with doc label', () => {
it('label in sidebar.json is used', async () => { it('label in sidebar.json is used', async () => {
const {content} = await loadSite(); const {content} = await loadSite();
const loadedVersion = content.loadedVersions[0]; const loadedVersion = content.loadedVersions[0]!;
const sidebarProps = toSidebarsProp(loadedVersion); 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 () => { it('sidebar_label in doc has higher precedence over label in sidebar.json', async () => {
const {content} = await loadSite(); const {content} = await loadSite();
const loadedVersion = content.loadedVersions[0]; const loadedVersion = content.loadedVersions[0]!;
const sidebarProps = toSidebarsProp(loadedVersion); 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 () => { it('sidebar is fully autogenerated', async () => {
const {content} = await loadSite(); const {content} = await loadSite();
const version = content.loadedVersions[0]; const version = content.loadedVersions[0]!;
expect(version.sidebars).toMatchSnapshot(); expect(version.sidebars).toMatchSnapshot();
}); });
it('docs in fully generated sidebar have correct metadata', async () => { it('docs in fully generated sidebar have correct metadata', async () => {
const {content} = await loadSite(); const {content} = await loadSite();
const version = content.loadedVersions[0]; const version = content.loadedVersions[0]!;
expect(getDocById(version, 'getting-started')).toMatchSnapshot(); expect(getDocById(version, 'getting-started')).toMatchSnapshot();
expect(getDocById(version, 'installation')).toMatchSnapshot(); expect(getDocById(version, 'installation')).toMatchSnapshot();
@ -675,14 +701,14 @@ describe('site with partial autogenerated sidebars', () => {
it('sidebar is partially autogenerated', async () => { it('sidebar is partially autogenerated', async () => {
const {content} = await loadSite(); const {content} = await loadSite();
const version = content.loadedVersions[0]; const version = content.loadedVersions[0]!;
expect(version.sidebars).toMatchSnapshot(); expect(version.sidebars).toMatchSnapshot();
}); });
it('docs in partially generated sidebar have correct metadata', async () => { it('docs in partially generated sidebar have correct metadata', async () => {
const {content} = await loadSite(); 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 // Only looking at the docs of the autogen sidebar, others metadata should
// not be affected // not be affected
@ -731,7 +757,7 @@ describe('site with partial autogenerated sidebars 2 (fix #4638)', () => {
it('sidebar is partially autogenerated', async () => { it('sidebar is partially autogenerated', async () => {
const {content} = await loadSite(); const {content} = await loadSite();
const version = content.loadedVersions[0]; const version = content.loadedVersions[0]!;
expect(version.sidebars).toMatchSnapshot(); expect(version.sidebars).toMatchSnapshot();
}); });
@ -763,8 +789,10 @@ describe('site with custom sidebar items generator', () => {
const customSidebarItemsGeneratorMock = jest.fn(async () => []); const customSidebarItemsGeneratorMock = jest.fn(async () => []);
const {siteDir} = await loadSite(customSidebarItemsGeneratorMock); const {siteDir} = await loadSite(customSidebarItemsGeneratorMock);
const generatorArg: Parameters<SidebarItemsGeneratorOption>[0] = const generatorArg = (
customSidebarItemsGeneratorMock.mock.calls[0][0]; customSidebarItemsGeneratorMock.mock
.calls[0] as unknown as Parameters<SidebarItemsGeneratorOption>
)[0];
// Make test pass even if docs are in different order and paths are // Make test pass even if docs are in different order and paths are
// absolutes // absolutes
@ -797,12 +825,12 @@ describe('site with custom sidebar items generator', () => {
const {content} = await loadSite(customSidebarItemsGenerator); const {content} = await loadSite(customSidebarItemsGenerator);
const version = content.loadedVersions[0]; 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 () => { it('sidebarItemsGenerator can wrap/enhance/sort/reverse the default sidebar generator', async () => {
function reverseSidebarItems(items: SidebarItem[]): SidebarItem[] { function reverseSidebarItems(items: NormalizedSidebar): NormalizedSidebar {
const result: SidebarItem[] = items.map((item) => { const result: NormalizedSidebar = items.map((item) => {
if (item.type === 'category') { if (item.type === 'category') {
return {...item, items: reverseSidebarItems(item.items)}; return {...item, items: reverseSidebarItems(item.items)};
} }
@ -821,7 +849,7 @@ describe('site with custom sidebar items generator', () => {
}; };
const {content} = await loadSite(reversedSidebarItemsGenerator); const {content} = await loadSite(reversedSidebarItemsGenerator);
const version = content.loadedVersions[0]; const version = content.loadedVersions[0]!;
expect(version.sidebars).toMatchSnapshot(); expect(version.sidebars).toMatchSnapshot();
}); });

View file

@ -36,7 +36,7 @@ describe('normalizeDocsPluginOptions', () => {
}); });
it('accepts correctly defined user options', () => { it('accepts correctly defined user options', () => {
const userOptions = { const userOptions: Options = {
path: 'my-docs', // Path to data on filesystem, relative to site dir. path: 'my-docs', // Path to data on filesystem, relative to site dir.
routeBasePath: 'my-docs', // URL Route. routeBasePath: 'my-docs', // URL Route.
tagsBasePath: 'tags', // URL Tags Route. tagsBasePath: 'tags', // URL Tags Route.
@ -51,6 +51,7 @@ describe('normalizeDocsPluginOptions', () => {
docTagsListComponent: '@theme/DocTagsListPage', docTagsListComponent: '@theme/DocTagsListPage',
docCategoryGeneratedIndexComponent: docCategoryGeneratedIndexComponent:
'@theme/DocCategoryGeneratedIndexPage', '@theme/DocCategoryGeneratedIndexPage',
// @ts-expect-error: it seems to work in practice?
remarkPlugins: [markdownPluginsObjectStub], remarkPlugins: [markdownPluginsObjectStub],
rehypePlugins: [markdownPluginsFunctionStub], rehypePlugins: [markdownPluginsFunctionStub],
beforeDefaultRehypePlugins: [], beforeDefaultRehypePlugins: [],
@ -79,16 +80,17 @@ describe('normalizeDocsPluginOptions', () => {
expect(testValidate(userOptions)).toEqual({ expect(testValidate(userOptions)).toEqual({
...defaultOptions, ...defaultOptions,
...userOptions, ...userOptions,
remarkPlugins: [...userOptions.remarkPlugins, expect.any(Array)], remarkPlugins: [...userOptions.remarkPlugins!, expect.any(Array)],
}); });
}); });
it('accepts correctly defined remark and rehype plugin options', () => { it('accepts correctly defined remark and rehype plugin options', () => {
const userOptions = { const userOptions: Options = {
beforeDefaultRemarkPlugins: [], beforeDefaultRemarkPlugins: [],
beforeDefaultRehypePlugins: [markdownPluginsFunctionStub], beforeDefaultRehypePlugins: [markdownPluginsFunctionStub],
remarkPlugins: [[markdownPluginsFunctionStub, {option1: '42'}]], remarkPlugins: [[markdownPluginsFunctionStub, {option1: '42'}]],
rehypePlugins: [ rehypePlugins: [
// @ts-expect-error: it seems to work in practice
markdownPluginsObjectStub, markdownPluginsObjectStub,
[markdownPluginsFunctionStub, {option1: '42'}], [markdownPluginsFunctionStub, {option1: '42'}],
], ],
@ -96,12 +98,12 @@ describe('normalizeDocsPluginOptions', () => {
expect(testValidate(userOptions)).toEqual({ expect(testValidate(userOptions)).toEqual({
...defaultOptions, ...defaultOptions,
...userOptions, ...userOptions,
remarkPlugins: [...userOptions.remarkPlugins, expect.any(Array)], remarkPlugins: [...userOptions.remarkPlugins!, expect.any(Array)],
}); });
}); });
it('accepts admonitions false', () => { it('accepts admonitions false', () => {
const admonitionsFalse = { const admonitionsFalse: Options = {
admonitions: false, admonitions: false,
}; };
expect(testValidate(admonitionsFalse)).toEqual({ expect(testValidate(admonitionsFalse)).toEqual({
@ -111,7 +113,7 @@ describe('normalizeDocsPluginOptions', () => {
}); });
it('rejects admonitions true', () => { it('rejects admonitions true', () => {
const admonitionsTrue = { const admonitionsTrue: Options = {
admonitions: true, admonitions: true,
}; };
expect(() => expect(() =>
@ -124,7 +126,10 @@ describe('normalizeDocsPluginOptions', () => {
it('accepts numberPrefixParser function', () => { it('accepts numberPrefixParser function', () => {
function customNumberPrefixParser() {} function customNumberPrefixParser() {}
expect( expect(
testValidate({numberPrefixParser: customNumberPrefixParser}), testValidate({
numberPrefixParser:
customNumberPrefixParser as unknown as Options['numberPrefixParser'],
}),
).toEqual({ ).toEqual({
...defaultOptions, ...defaultOptions,
numberPrefixParser: customNumberPrefixParser, numberPrefixParser: customNumberPrefixParser,
@ -148,6 +153,7 @@ describe('normalizeDocsPluginOptions', () => {
it('rejects invalid remark plugin options', () => { it('rejects invalid remark plugin options', () => {
expect(() => expect(() =>
testValidate({ testValidate({
// @ts-expect-error: test
remarkPlugins: [[{option1: '42'}, markdownPluginsFunctionStub]], remarkPlugins: [[{option1: '42'}, markdownPluginsFunctionStub]],
}), }),
).toThrowErrorMatchingInlineSnapshot(` ).toThrowErrorMatchingInlineSnapshot(`
@ -161,6 +167,7 @@ describe('normalizeDocsPluginOptions', () => {
expect(() => expect(() =>
testValidate({ testValidate({
rehypePlugins: [ rehypePlugins: [
// @ts-expect-error: test
[ [
markdownPluginsFunctionStub, markdownPluginsFunctionStub,
{option1: '42'}, {option1: '42'},
@ -176,6 +183,7 @@ describe('normalizeDocsPluginOptions', () => {
}); });
it('rejects bad path inputs', () => { it('rejects bad path inputs', () => {
// @ts-expect-error: test
expect(() => testValidate({path: 2})).toThrowErrorMatchingInlineSnapshot( expect(() => testValidate({path: 2})).toThrowErrorMatchingInlineSnapshot(
`""path" must be a string"`, `""path" must be a string"`,
); );
@ -183,12 +191,14 @@ describe('normalizeDocsPluginOptions', () => {
it('rejects bad include inputs', () => { it('rejects bad include inputs', () => {
expect(() => expect(() =>
// @ts-expect-error: test
testValidate({include: '**/*.{md,mdx}'}), testValidate({include: '**/*.{md,mdx}'}),
).toThrowErrorMatchingInlineSnapshot(`""include" must be an array"`); ).toThrowErrorMatchingInlineSnapshot(`""include" must be an array"`);
}); });
it('rejects bad showLastUpdateTime inputs', () => { it('rejects bad showLastUpdateTime inputs', () => {
expect(() => expect(() =>
// @ts-expect-error: test
testValidate({showLastUpdateTime: 'true'}), testValidate({showLastUpdateTime: 'true'}),
).toThrowErrorMatchingInlineSnapshot( ).toThrowErrorMatchingInlineSnapshot(
`""showLastUpdateTime" must be a boolean"`, `""showLastUpdateTime" must be a boolean"`,
@ -197,12 +207,14 @@ describe('normalizeDocsPluginOptions', () => {
it('rejects bad remarkPlugins input', () => { it('rejects bad remarkPlugins input', () => {
expect(() => expect(() =>
// @ts-expect-error: test
testValidate({remarkPlugins: 'remark-math'}), testValidate({remarkPlugins: 'remark-math'}),
).toThrowErrorMatchingInlineSnapshot(`""remarkPlugins" must be an array"`); ).toThrowErrorMatchingInlineSnapshot(`""remarkPlugins" must be an array"`);
}); });
it('rejects bad lastVersion', () => { it('rejects bad lastVersion', () => {
expect(() => expect(() =>
// @ts-expect-error: test
testValidate({lastVersion: false}), testValidate({lastVersion: false}),
).toThrowErrorMatchingInlineSnapshot(`""lastVersion" must be a string"`); ).toThrowErrorMatchingInlineSnapshot(`""lastVersion" must be a string"`);
}); });
@ -212,6 +224,7 @@ describe('normalizeDocsPluginOptions', () => {
testValidate({ testValidate({
versions: { versions: {
current: { current: {
// @ts-expect-error: test
hey: 3, hey: 3,
}, },

View file

@ -21,30 +21,30 @@ describe('toTagDocListProp', () => {
docIds: ['id1', 'id3'], docIds: ['id1', 'id3'],
}; };
const doc1: Doc = { const doc1 = {
id: 'id1', id: 'id1',
title: 'ZZZ 1', title: 'ZZZ 1',
description: 'Description 1', description: 'Description 1',
permalink: '/doc1', permalink: '/doc1',
}; } as Doc;
const doc2: Doc = { const doc2 = {
id: 'id2', id: 'id2',
title: 'XXX 2', title: 'XXX 2',
description: 'Description 2', description: 'Description 2',
permalink: '/doc2', permalink: '/doc2',
}; } as Doc;
const doc3: Doc = { const doc3 = {
id: 'id3', id: 'id3',
title: 'AAA 3', title: 'AAA 3',
description: 'Description 3', description: 'Description 3',
permalink: '/doc3', permalink: '/doc3',
}; } as Doc;
const doc4: Doc = { const doc4 = {
id: 'id4', id: 'id4',
title: 'UUU 4', title: 'UUU 4',
description: 'Description 4', description: 'Description 4',
permalink: '/doc4', permalink: '/doc4',
}; } as Doc;
const result = toTagDocListProp({ const result = toTagDocListProp({
allTagsPath, allTagsPath,

View file

@ -17,7 +17,7 @@ declare module '@docusaurus/plugin-content-docs' {
Tag, Tag,
} from '@docusaurus/utils'; } from '@docusaurus/utils';
import type {Plugin, LoadContext} from '@docusaurus/types'; import type {Plugin, LoadContext} from '@docusaurus/types';
import type {Required} from 'utility-types'; import type {Overwrite, Required} from 'utility-types';
export type Assets = { export type Assets = {
image?: string; image?: string;
@ -206,7 +206,22 @@ declare module '@docusaurus/plugin-content-docs' {
*/ */
tagsBasePath: string; 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 SidebarsConfig = import('./sidebars/types').SidebarsConfig;
export type VersionMetadata = ContentPaths & { export type VersionMetadata = ContentPaths & {

View file

@ -100,10 +100,13 @@ describe('createSidebarsUtils', () => {
const sidebar4: Sidebar = [ const sidebar4: Sidebar = [
{ {
type: 'category', type: 'category',
collapsed: false,
collapsible: true,
label: 'Related',
items: [ items: [
{type: 'link', href: 'https://facebook.com'}, {type: 'link', href: 'https://facebook.com', label: 'Facebook'},
{type: 'link', href: 'https://reactjs.org'}, {type: 'link', href: 'https://reactjs.org', label: 'React'},
{type: 'link', href: 'https://docusaurus.io'}, {type: 'link', href: 'https://docusaurus.io', label: 'Docusaurus'},
], ],
}, },
{ {
@ -696,10 +699,10 @@ describe('toNavigationLink', () => {
it('with doc items', () => { it('with doc items', () => {
expect(toNavigationLink({type: 'doc', id: 'doc1'}, docsById)).toEqual( expect(toNavigationLink({type: 'doc', id: 'doc1'}, docsById)).toEqual(
toDocNavigationLink(docsById.doc1), toDocNavigationLink(docsById.doc1!),
); );
expect(toNavigationLink({type: 'doc', id: 'doc2'}, docsById)).toEqual( expect(toNavigationLink({type: 'doc', id: 'doc2'}, docsById)).toEqual(
toDocNavigationLink(docsById.doc2), toDocNavigationLink(docsById.doc2!),
); );
expect(() => expect(() =>
toNavigationLink({type: 'doc', id: 'doc3'}, docsById), toNavigationLink({type: 'doc', id: 'doc3'}, docsById),
@ -724,7 +727,7 @@ describe('toNavigationLink', () => {
}, },
docsById, docsById,
), ),
).toEqual(toDocNavigationLink(docsById.doc1)); ).toEqual(toDocNavigationLink(docsById.doc1!));
expect(() => expect(() =>
toNavigationLink( toNavigationLink(
{ {

View file

@ -10,7 +10,7 @@ import path from 'path';
import {DEFAULT_PLUGIN_ID} from '@docusaurus/utils'; import {DEFAULT_PLUGIN_ID} from '@docusaurus/utils';
import {readVersionsMetadata} from '../index'; import {readVersionsMetadata} from '../index';
import {DEFAULT_OPTIONS} from '../../options'; import {DEFAULT_OPTIONS} from '../../options';
import type {I18n} from '@docusaurus/types'; import type {I18n, LoadContext} from '@docusaurus/types';
import type { import type {
PluginOptions, PluginOptions,
VersionMetadata, VersionMetadata,
@ -37,7 +37,7 @@ describe('readVersionsMetadata', () => {
siteDir: simpleSiteDir, siteDir: simpleSiteDir,
baseUrl: '/', baseUrl: '/',
i18n: DefaultI18N, i18n: DefaultI18N,
}; } as LoadContext;
const vCurrent: VersionMetadata = { const vCurrent: VersionMetadata = {
contentPath: path.join(simpleSiteDir, 'docs'), contentPath: path.join(simpleSiteDir, 'docs'),
@ -198,7 +198,7 @@ describe('readVersionsMetadata', () => {
siteDir: versionedSiteDir, siteDir: versionedSiteDir,
baseUrl: '/', baseUrl: '/',
i18n: DefaultI18N, i18n: DefaultI18N,
}; } as LoadContext;
const vCurrent: VersionMetadata = { const vCurrent: VersionMetadata = {
contentPath: path.join(versionedSiteDir, 'docs'), contentPath: path.join(versionedSiteDir, 'docs'),
@ -636,7 +636,7 @@ describe('readVersionsMetadata', () => {
siteDir: versionedSiteDir, siteDir: versionedSiteDir,
baseUrl: '/', baseUrl: '/',
i18n: DefaultI18N, i18n: DefaultI18N,
}; } as LoadContext;
const vCurrent: VersionMetadata = { const vCurrent: VersionMetadata = {
contentPath: path.join(versionedSiteDir, 'community'), contentPath: path.join(versionedSiteDir, 'community'),

View file

@ -8,6 +8,7 @@
import React from 'react'; import React from 'react';
import {EnumChangefreq} from 'sitemap'; import {EnumChangefreq} from 'sitemap';
import createSitemap from '../createSitemap'; import createSitemap from '../createSitemap';
import type {PluginOptions} from '../options';
import type {DocusaurusConfig} from '@docusaurus/types'; import type {DocusaurusConfig} from '@docusaurus/types';
describe('createSitemap', () => { describe('createSitemap', () => {
@ -31,7 +32,8 @@ describe('createSitemap', () => {
it('empty site', () => it('empty site', () =>
expect(async () => { expect(async () => {
await createSitemap({} as DocusaurusConfig, [], {}, {}); // @ts-expect-error: test
await createSitemap({}, [], {}, {} as PluginOptions);
}).rejects.toThrow( }).rejects.toThrow(
'URL in docusaurus.config.js cannot be empty/undefined.', 'URL in docusaurus.config.js cannot be empty/undefined.',
)); ));
@ -148,6 +150,7 @@ describe('createSitemap', () => {
{ {
'/noindex': { '/noindex': {
meta: { meta: {
// @ts-expect-error: bad lib def
toComponent: () => [ toComponent: () => [
React.createElement('meta', {name: 'robots', content: 'noindex'}), React.createElement('meta', {name: 'robots', content: 'noindex'}),
], ],

View file

@ -23,7 +23,7 @@ describe('validateOptions', () => {
}); });
it('accepts correctly defined user options', () => { it('accepts correctly defined user options', () => {
const userOptions = { const userOptions: Options = {
changefreq: 'yearly', changefreq: 'yearly',
priority: 0.9, priority: 0.9,
ignorePatterns: ['/search/**'], ignorePatterns: ['/search/**'],
@ -52,9 +52,11 @@ describe('validateOptions', () => {
it('rejects bad ignorePatterns inputs', () => { it('rejects bad ignorePatterns inputs', () => {
expect(() => expect(() =>
// @ts-expect-error: test
testValidate({ignorePatterns: '/search'}), testValidate({ignorePatterns: '/search'}),
).toThrowErrorMatchingInlineSnapshot(`""ignorePatterns" must be an array"`); ).toThrowErrorMatchingInlineSnapshot(`""ignorePatterns" must be an array"`);
expect(() => expect(() =>
// @ts-expect-error: test
testValidate({ignorePatterns: [/^\/search/]}), testValidate({ignorePatterns: [/^\/search/]}),
).toThrowErrorMatchingInlineSnapshot( ).toThrowErrorMatchingInlineSnapshot(
`""ignorePatterns[0]" must be a string"`, `""ignorePatterns[0]" must be a string"`,

View file

@ -9,7 +9,7 @@ import {updateTranslationFileMessages} from '@docusaurus/utils';
import {getTranslationFiles, translateThemeConfig} from '../translations'; import {getTranslationFiles, translateThemeConfig} from '../translations';
import type {ThemeConfig} from '@docusaurus/theme-common'; import type {ThemeConfig} from '@docusaurus/theme-common';
const ThemeConfigSample: ThemeConfig = { const ThemeConfigSample = {
colorMode: {}, colorMode: {},
announcementBar: {}, announcementBar: {},
prism: {}, prism: {},
@ -47,7 +47,7 @@ const ThemeConfigSample: ThemeConfig = {
}, },
], ],
}, },
}; } as unknown as ThemeConfig;
const ThemeConfigSampleSimpleFooter: ThemeConfig = { const ThemeConfigSampleSimpleFooter: ThemeConfig = {
...ThemeConfigSample, ...ThemeConfigSample,

View file

@ -674,7 +674,7 @@ describe('themeConfig', () => {
}); });
it('max config', () => { it('max config', () => {
const colorMode = { const colorMode: ThemeConfig['colorMode'] = {
defaultMode: 'dark', defaultMode: 'dark',
disableSwitch: false, disableSwitch: false,
respectPrefersColorScheme: true, respectPrefersColorScheme: true,

View file

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

View file

@ -115,7 +115,7 @@ function TabsComponent(props: Props): JSX.Element {
setSelectedValue(newTabValue); setSelectedValue(newTabValue);
if (groupId != null) { if (groupId != null) {
setTabGroupChoices(groupId, newTabValue); setTabGroupChoices(groupId, String(newTabValue));
} }
} }
}; };

View file

@ -26,6 +26,7 @@ import type {
PropSidebarItemLink, PropSidebarItemLink,
PropVersionMetadata, PropVersionMetadata,
} from '@docusaurus/plugin-content-docs'; } from '@docusaurus/plugin-content-docs';
import type {DocusaurusContext} from '@docusaurus/types';
// Make tests more readable with some useful category item defaults // Make tests more readable with some useful category item defaults
function testCategory( function testCategory(
@ -294,19 +295,22 @@ describe('isActiveSidebarItem', () => {
describe('useSidebarBreadcrumbs', () => { describe('useSidebarBreadcrumbs', () => {
const createUseSidebarBreadcrumbsMock = const createUseSidebarBreadcrumbsMock =
(sidebar: PropSidebar, breadcrumbsOption?: boolean) => (location: string) => (sidebar: PropSidebar | undefined, breadcrumbsOption?: boolean) =>
(location: string) =>
renderHook(() => useSidebarBreadcrumbs(), { renderHook(() => useSidebarBreadcrumbs(), {
wrapper: ({children}) => ( wrapper: ({children}) => (
<StaticRouter location={location}> <StaticRouter location={location}>
<Context.Provider <Context.Provider
value={
// eslint-disable-next-line react/jsx-no-constructed-context-values // eslint-disable-next-line react/jsx-no-constructed-context-values
value={{ {
globalData: { globalData: {
'docusaurus-plugin-content-docs': { 'docusaurus-plugin-content-docs': {
default: {path: '/', breadcrumbs: breadcrumbsOption}, default: {path: '/', breadcrumbs: breadcrumbsOption},
}, },
}, },
}}> } as unknown as DocusaurusContext
}>
<DocsSidebarProvider name="sidebarName" items={sidebar}> <DocsSidebarProvider name="sidebarName" items={sidebar}>
{children} {children}
</DocsSidebarProvider> </DocsSidebarProvider>
@ -421,7 +425,9 @@ describe('useSidebarBreadcrumbs', () => {
}); });
it('returns null when there is no sidebar', () => { 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; }).result.current;
it('works', () => { it('works', () => {
const category = { const category: PropSidebarItemCategory = {
type: 'category', type: 'category',
label: 'Category',
href: '/cat', href: '/cat',
collapsible: true,
collapsed: false,
items: [ items: [
{type: 'link', href: '/cat/foo', label: 'Foo'}, {type: 'link', href: '/cat/foo', label: 'Foo'},
{type: 'link', href: '/cat/bar', label: 'Bar'}, {type: 'link', href: '/cat/bar', label: 'Bar'},
@ -453,8 +462,11 @@ describe('useCurrentSidebarCategory', () => {
}); });
it('throws for non-category index page', () => { it('throws for non-category index page', () => {
const category = { const category: PropSidebarItemCategory = {
type: 'category', type: 'category',
label: 'Category',
collapsible: true,
collapsed: false,
items: [ items: [
{type: 'link', href: '/cat/foo', label: 'Foo'}, {type: 'link', href: '/cat/foo', label: 'Foo'},
{type: 'link', href: '/cat/bar', label: 'Bar'}, {type: 'link', href: '/cat/bar', label: 'Bar'},

View file

@ -24,7 +24,7 @@ describe('usePluralForm', () => {
i18n: { i18n: {
currentLocale: 'en', currentLocale: 'en',
}, },
}); } as DocusaurusContext);
expect(mockUsePluralForm().selectMessage(1, 'one|many')).toBe('one'); expect(mockUsePluralForm().selectMessage(1, 'one|many')).toBe('one');
expect(mockUsePluralForm().selectMessage(10, 'one|many')).toBe('many'); expect(mockUsePluralForm().selectMessage(10, 'one|many')).toBe('many');
}); });
@ -34,7 +34,7 @@ describe('usePluralForm', () => {
i18n: { i18n: {
currentLocale: 'zh-Hans', currentLocale: 'zh-Hans',
}, },
}); } as DocusaurusContext);
const consoleMock = jest const consoleMock = jest
.spyOn(console, 'error') .spyOn(console, 'error')
.mockImplementation(() => {}); .mockImplementation(() => {});
@ -50,7 +50,7 @@ describe('usePluralForm', () => {
i18n: { i18n: {
currentLocale: 'en', currentLocale: 'en',
}, },
}); } as DocusaurusContext);
expect(mockUsePluralForm().selectMessage(10, 'many')).toBe('many'); expect(mockUsePluralForm().selectMessage(10, 'many')).toBe('many');
}); });
@ -59,7 +59,7 @@ describe('usePluralForm', () => {
i18n: { i18n: {
currentLocale: 'zh-Hans', currentLocale: 'zh-Hans',
}, },
}); } as DocusaurusContext);
const consoleMock = jest const consoleMock = jest
.spyOn(console, 'error') .spyOn(console, 'error')
.mockImplementation(() => {}); .mockImplementation(() => {});

View file

@ -78,6 +78,7 @@ describe('readDefaultCodeTranslationMessages', () => {
it('for empty locale', async () => { it('for empty locale', async () => {
await expect( await expect(
readDefaultCodeTranslationMessages({ readDefaultCodeTranslationMessages({
name: 'default',
locale: '', locale: '',
dirPath, dirPath,
}), }),

View file

@ -58,7 +58,7 @@ describe('mapAsyncSequential', () => {
const timeBefore = Date.now(); const timeBefore = Date.now();
await expect( await expect(
mapAsyncSequential(items, async (item) => { mapAsyncSequential(items, async (item) => {
const itemTimeout = itemToTimeout[item]; const itemTimeout = itemToTimeout[item]!;
itemMapStartsAt[item] = Date.now(); itemMapStartsAt[item] = Date.now();
await sleep(itemTimeout); await sleep(itemTimeout);
itemMapEndsAt[item] = Date.now(); itemMapEndsAt[item] = Date.now();
@ -72,12 +72,10 @@ describe('mapAsyncSequential', () => {
const totalTimeouts = _.sum(Object.values(itemToTimeout)); const totalTimeouts = _.sum(Object.values(itemToTimeout));
expect(timeTotal).toBeGreaterThanOrEqual(totalTimeouts - 100); expect(timeTotal).toBeGreaterThanOrEqual(totalTimeouts - 100);
expect(itemMapStartsAt['1']).toBeGreaterThanOrEqual(0); expect(itemMapStartsAt[1]).toBeGreaterThanOrEqual(0);
expect(itemMapStartsAt['2']).toBeGreaterThanOrEqual( expect(itemMapStartsAt[2]).toBeGreaterThanOrEqual(itemMapEndsAt[1]! - 100);
itemMapEndsAt['1'] - 100,
);
expect(itemMapStartsAt['3']).toBeGreaterThanOrEqual( expect(itemMapStartsAt['3']).toBeGreaterThanOrEqual(
itemMapEndsAt['2'] - 100, itemMapEndsAt[2]! - 100,
); );
}); });
}); });

View file

@ -10,7 +10,7 @@ import {getFileLoaderUtils} from '../webpackUtils';
describe('getFileLoaderUtils()', () => { describe('getFileLoaderUtils()', () => {
it('plugin svgo/removeViewBox and removeTitle should be disabled', () => { it('plugin svgo/removeViewBox and removeTitle should be disabled', () => {
const {oneOf} = getFileLoaderUtils().rules.svg(); const {oneOf} = getFileLoaderUtils().rules.svg();
expect(oneOf[0].use).toContainEqual( expect(oneOf![0]!.use).toContainEqual(
expect.objectContaining({ expect.objectContaining({
loader: require.resolve('@svgr/webpack'), loader: require.resolve('@svgr/webpack'),
options: expect.objectContaining({ options: expect.objectContaining({

View file

@ -46,7 +46,7 @@ describe('flat', () => {
expect( expect(
flat({ flat({
foo: { foo: {
bar: value, bar: value as string,
}, },
}), }),
).toEqual({ ).toEqual({

View file

@ -7,13 +7,14 @@
import {jest} from '@jest/globals'; import {jest} from '@jest/globals';
import normalizeLocation from '../normalizeLocation'; import normalizeLocation from '../normalizeLocation';
import type {Location} from 'history';
describe('normalizeLocation', () => { describe('normalizeLocation', () => {
it('rewrites locations with index.html', () => { it('rewrites locations with index.html', () => {
expect( expect(
normalizeLocation({ normalizeLocation({
pathname: '/index.html', pathname: '/index.html',
}), } as Location),
).toEqual({ ).toEqual({
pathname: '/', pathname: '/',
}); });
@ -23,7 +24,7 @@ describe('normalizeLocation', () => {
pathname: '/docs/introduction/index.html', pathname: '/docs/introduction/index.html',
search: '?search=foo', search: '?search=foo',
hash: '#features', hash: '#features',
}), } as Location),
).toEqual({ ).toEqual({
pathname: '/docs/introduction', pathname: '/docs/introduction',
search: '?search=foo', search: '?search=foo',
@ -35,7 +36,7 @@ describe('normalizeLocation', () => {
pathname: '/index.html', pathname: '/index.html',
search: '', search: '',
hash: '#features', hash: '#features',
}), } as Location),
).toEqual({ ).toEqual({
pathname: '/', pathname: '/',
search: '', search: '',
@ -47,7 +48,7 @@ describe('normalizeLocation', () => {
expect( expect(
normalizeLocation({ normalizeLocation({
pathname: '/docs/installation.html', pathname: '/docs/installation.html',
}), } as Location),
).toEqual({ ).toEqual({
pathname: '/docs/installation', pathname: '/docs/installation',
}); });
@ -56,7 +57,7 @@ describe('normalizeLocation', () => {
pathname: '/docs/introduction/foo.html', pathname: '/docs/introduction/foo.html',
search: '', search: '',
hash: '#bar', hash: '#bar',
}), } as Location),
).toEqual({ ).toEqual({
pathname: '/docs/introduction/foo', pathname: '/docs/introduction/foo',
search: '', search: '',
@ -65,7 +66,7 @@ describe('normalizeLocation', () => {
}); });
it('does not strip extension if the route location has one', () => { 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', pathname: '/page.html',
}); });
}); });
@ -78,7 +79,7 @@ describe('normalizeLocation', () => {
pathname: '/docs/introduction', pathname: '/docs/introduction',
search: '', search: '',
hash: '#features', hash: '#features',
}), } as Location),
).toEqual({ ).toEqual({
pathname: '/docs/introduction', pathname: '/docs/introduction',
search: '', search: '',
@ -91,7 +92,7 @@ describe('normalizeLocation', () => {
pathname: '/docs/introduction', pathname: '/docs/introduction',
search: '', search: '',
hash: '#features', hash: '#features',
}), } as Location),
).toEqual({ ).toEqual({
pathname: '/docs/introduction', pathname: '/docs/introduction',
search: '', search: '',
@ -102,7 +103,7 @@ describe('normalizeLocation', () => {
expect( expect(
normalizeLocation({ normalizeLocation({
pathname: '/', pathname: '/',
}), } as Location),
).toEqual({ ).toEqual({
pathname: '/', pathname: '/',
}); });

View file

@ -31,7 +31,7 @@ describe('interpolate', () => {
object: {hello: 'world'}, object: {hello: 'world'},
array: ['Hello'], array: ['Hello'],
}; };
// Do we need to improve the JS type -> String conversion logic here? // @ts-expect-error: test
expect(interpolate(text, values)).toMatchInlineSnapshot( expect(interpolate(text, values)).toMatchInlineSnapshot(
`"42 Hello [object Object] Hello"`, `"42 Hello [object Object] Hello"`,
); );
@ -52,6 +52,7 @@ describe('interpolate', () => {
// Should we emit warnings in such case? // Should we emit warnings in such case?
const text = 'Hello {name} how are you {unprovidedValue}?'; const text = 'Hello {name} how are you {unprovidedValue}?';
const values = {name: 'Sébastien', extraValue: 'today'}; const values = {name: 'Sébastien', extraValue: 'today'};
// @ts-expect-error: test
expect(interpolate(text, values)).toMatchInlineSnapshot( expect(interpolate(text, values)).toMatchInlineSnapshot(
`"Hello Sébastien how are you {unprovidedValue}?"`, `"Hello Sébastien how are you {unprovidedValue}?"`,
); );
@ -61,6 +62,7 @@ describe('interpolate', () => {
// Should we emit warnings in such case? // Should we emit warnings in such case?
const text = 'Hello {name} how are you {day}?'; const text = 'Hello {name} how are you {day}?';
expect(interpolate(text)).toEqual(text); expect(interpolate(text)).toEqual(text);
// @ts-expect-error: test
expect(interpolate(text, {})).toEqual(text); expect(interpolate(text, {})).toEqual(text);
}); });
@ -84,6 +86,7 @@ describe('interpolate', () => {
extraUselessValue1: <div>test</div>, extraUselessValue1: <div>test</div>,
extraUselessValue2: 'hi', extraUselessValue2: 'hi',
}; };
// @ts-expect-error: test
expect(interpolate(text, values)).toMatchSnapshot(); expect(interpolate(text, values)).toMatchSnapshot();
}); });
}); });
@ -133,6 +136,7 @@ describe('<Interpolate>', () => {
`"The Docusaurus <Interpolate> component only accept simple string values. Received: React element"`, `"The Docusaurus <Interpolate> component only accept simple string values. Received: React element"`,
); );
expect(() => expect(() =>
// @ts-expect-error: test
renderer.create(<Interpolate>{null}</Interpolate>), renderer.create(<Interpolate>{null}</Interpolate>),
).toThrowErrorMatchingInlineSnapshot( ).toThrowErrorMatchingInlineSnapshot(
`"The Docusaurus <Interpolate> component only accept simple string values. Received: object"`, `"The Docusaurus <Interpolate> component only accept simple string values. Received: object"`,

View file

@ -28,7 +28,7 @@ describe('useBaseUrl', () => {
baseUrl: '/', baseUrl: '/',
url: 'https://docusaurus.io', url: 'https://docusaurus.io',
}, },
}); } as DocusaurusContext);
expect(mockUseBaseUrl('hello')).toBe('/hello'); expect(mockUseBaseUrl('hello')).toBe('/hello');
expect(mockUseBaseUrl('/hello')).toBe('/hello'); expect(mockUseBaseUrl('/hello')).toBe('/hello');
@ -56,7 +56,7 @@ describe('useBaseUrl', () => {
baseUrl: '/docusaurus/', baseUrl: '/docusaurus/',
url: 'https://docusaurus.io', url: 'https://docusaurus.io',
}, },
}); } as DocusaurusContext);
expect(mockUseBaseUrl('')).toBe(''); expect(mockUseBaseUrl('')).toBe('');
expect(mockUseBaseUrl('hello')).toBe('/docusaurus/hello'); expect(mockUseBaseUrl('hello')).toBe('/docusaurus/hello');
@ -97,7 +97,7 @@ describe('useBaseUrlUtils().withBaseUrl()', () => {
baseUrl: '/', baseUrl: '/',
url: 'https://docusaurus.io', url: 'https://docusaurus.io',
}, },
}); } as DocusaurusContext);
expect(withBaseUrl('hello')).toBe('/hello'); expect(withBaseUrl('hello')).toBe('/hello');
expect(withBaseUrl('/hello')).toBe('/hello'); expect(withBaseUrl('/hello')).toBe('/hello');
@ -125,7 +125,7 @@ describe('useBaseUrlUtils().withBaseUrl()', () => {
baseUrl: '/docusaurus/', baseUrl: '/docusaurus/',
url: 'https://docusaurus.io', url: 'https://docusaurus.io',
}, },
}); } as DocusaurusContext);
expect(withBaseUrl('hello')).toBe('/docusaurus/hello'); expect(withBaseUrl('hello')).toBe('/docusaurus/hello');
expect(withBaseUrl('/hello')).toBe('/docusaurus/hello'); expect(withBaseUrl('/hello')).toBe('/docusaurus/hello');

View file

@ -7,6 +7,7 @@
import path from 'path'; import path from 'path';
import {loadPlugins} from '..'; import {loadPlugins} from '..';
import type {Props} from '@docusaurus/types';
describe('loadPlugins', () => { describe('loadPlugins', () => {
it('loads plugins', async () => { it('loads plugins', async () => {
@ -16,7 +17,6 @@ describe('loadPlugins', () => {
siteDir, siteDir,
generatedFilesDir: path.join(siteDir, '.docusaurus'), generatedFilesDir: path.join(siteDir, '.docusaurus'),
outDir: path.join(siteDir, 'build'), outDir: path.join(siteDir, 'build'),
// @ts-expect-error: good enough
siteConfig: { siteConfig: {
baseUrl: '/', baseUrl: '/',
trailingSlash: true, trailingSlash: true,
@ -51,7 +51,7 @@ describe('loadPlugins', () => {
], ],
}, },
siteConfigPath: path.join(siteDir, 'docusaurus.config.js'), siteConfigPath: path.join(siteDir, 'docusaurus.config.js'),
}), } as unknown as Props),
).resolves.toMatchSnapshot(); ).resolves.toMatchSnapshot();
}); });
}); });

View file

@ -24,14 +24,14 @@ describe('initPlugins', () => {
expect(context.siteConfig.plugins).toHaveLength(4); expect(context.siteConfig.plugins).toHaveLength(4);
expect(plugins).toHaveLength(8); expect(plugins).toHaveLength(8);
expect(plugins[0].name).toBe('preset-plugin1'); expect(plugins[0]!.name).toBe('preset-plugin1');
expect(plugins[1].name).toBe('preset-plugin2'); expect(plugins[1]!.name).toBe('preset-plugin2');
expect(plugins[2].name).toBe('preset-theme1'); expect(plugins[2]!.name).toBe('preset-theme1');
expect(plugins[3].name).toBe('preset-theme2'); expect(plugins[3]!.name).toBe('preset-theme2');
expect(plugins[4].name).toBe('first-plugin'); expect(plugins[4]!.name).toBe('first-plugin');
expect(plugins[5].name).toBe('second-plugin'); expect(plugins[5]!.name).toBe('second-plugin');
expect(plugins[6].name).toBe('third-plugin'); expect(plugins[6]!.name).toBe('third-plugin');
expect(plugins[7].name).toBe('fourth-plugin'); expect(plugins[7]!.name).toBe('fourth-plugin');
expect(context.siteConfig.themeConfig).toEqual({a: 1}); expect(context.siteConfig.themeConfig).toEqual({a: 1});
}); });

View file

@ -8,12 +8,11 @@
import {ensureUniquePluginInstanceIds} from '../pluginIds'; import {ensureUniquePluginInstanceIds} from '../pluginIds';
import type {InitializedPlugin} from '@docusaurus/types'; import type {InitializedPlugin} from '@docusaurus/types';
function createTestPlugin(name: string, id?: string): InitializedPlugin { function createTestPlugin(name: string, id?: string) {
// @ts-expect-error: good enough for tests
return { return {
name, name,
options: {id}, options: {id: id ?? 'default'},
}; } as InitializedPlugin;
} }
describe('ensureUniquePluginInstanceIds', () => { describe('ensureUniquePluginInstanceIds', () => {

View file

@ -62,7 +62,7 @@ describe('loadPresets', () => {
[path.join(__dirname, '__fixtures__/presets/preset-plugins.js')], [path.join(__dirname, '__fixtures__/presets/preset-plugins.js')],
], ],
}, },
} as Partial<LoadContext>; } as unknown as LoadContext;
const presets = await loadPresets(context); const presets = await loadPresets(context);
expect(presets).toMatchSnapshot(); expect(presets).toMatchSnapshot();
}); });
@ -78,7 +78,7 @@ describe('loadPresets', () => {
], ],
], ],
}, },
} as Partial<LoadContext>; } as unknown as LoadContext;
const presets = await loadPresets(context); const presets = await loadPresets(context);
expect(presets).toMatchSnapshot(); expect(presets).toMatchSnapshot();
}); });
@ -98,7 +98,7 @@ describe('loadPresets', () => {
], ],
], ],
}, },
} as Partial<LoadContext>; } as unknown as LoadContext;
const presets = await loadPresets(context); const presets = await loadPresets(context);
expect(presets).toMatchSnapshot(); expect(presets).toMatchSnapshot();
}); });

View file

@ -20,6 +20,7 @@ import {
} from '../translations'; } from '../translations';
import type { import type {
InitializedPlugin, InitializedPlugin,
LoadedPlugin,
TranslationFile, TranslationFile,
TranslationFileContent, TranslationFileContent,
} from '@docusaurus/types'; } from '@docusaurus/types';
@ -399,7 +400,7 @@ describe('writePluginTranslations', () => {
options: { options: {
id: 'my-plugin-id', id: 'my-plugin-id',
}, },
}, } as LoadedPlugin,
options: {}, options: {},
}), }),
@ -426,11 +427,10 @@ describe('localizePluginTranslationFile', () => {
siteDir, siteDir,
locale: 'fr', locale: 'fr',
translationFile, translationFile,
// @ts-expect-error: enough for this test
plugin: { plugin: {
name: 'my-plugin-name', name: 'my-plugin-name',
options: {}, options: {},
}, } as LoadedPlugin,
}); });
expect(localizedTranslationFile).toEqual(translationFile); expect(localizedTranslationFile).toEqual(translationFile);
@ -466,11 +466,10 @@ describe('localizePluginTranslationFile', () => {
siteDir, siteDir,
locale: 'fr', locale: 'fr',
translationFile, translationFile,
// @ts-expect-error: enough for this test
plugin: { plugin: {
name: 'my-plugin-name', name: 'my-plugin-name',
options: {}, options: {},
}, } as LoadedPlugin,
}); });
expect(localizedTranslationFile).toEqual({ expect(localizedTranslationFile).toEqual({
@ -521,25 +520,30 @@ describe('readCodeTranslationFileContent', () => {
it('fails for invalid translation file content', async () => { it('fails for invalid translation file content', async () => {
await expect(() => await expect(() =>
// @ts-expect-error: test
testReadTranslation('HEY'), testReadTranslation('HEY'),
).rejects.toThrowErrorMatchingInlineSnapshot( ).rejects.toThrowErrorMatchingInlineSnapshot(
`""value" must be of type object"`, `""value" must be of type object"`,
); );
await expect(() => await expect(() =>
// @ts-expect-error: test
testReadTranslation(42), testReadTranslation(42),
).rejects.toThrowErrorMatchingInlineSnapshot( ).rejects.toThrowErrorMatchingInlineSnapshot(
`""value" must be of type object"`, `""value" must be of type object"`,
); );
await expect(() => await expect(() =>
// @ts-expect-error: test
testReadTranslation({key: {description: 'no message'}}), testReadTranslation({key: {description: 'no message'}}),
).rejects.toThrowErrorMatchingInlineSnapshot(`""key.message" is required"`); ).rejects.toThrowErrorMatchingInlineSnapshot(`""key.message" is required"`);
await expect(() => await expect(() =>
// @ts-expect-error: test
testReadTranslation({key: {message: 42}}), testReadTranslation({key: {message: 42}}),
).rejects.toThrowErrorMatchingInlineSnapshot( ).rejects.toThrowErrorMatchingInlineSnapshot(
`""key.message" must be a string"`, `""key.message" must be a string"`,
); );
await expect(() => await expect(() =>
testReadTranslation({ testReadTranslation({
// @ts-expect-error: test
key: {message: 'Message', description: 42}, key: {message: 'Message', description: 42},
}), }),
).rejects.toThrowErrorMatchingInlineSnapshot( ).rejects.toThrowErrorMatchingInlineSnapshot(

View file

@ -15,7 +15,7 @@ import {
extractSiteSourceCodeTranslations, extractSiteSourceCodeTranslations,
} from '../translationsExtractor'; } from '../translationsExtractor';
import {getBabelOptions} from '../../../webpack/utils'; import {getBabelOptions} from '../../../webpack/utils';
import type {InitializedPlugin} from '@docusaurus/types'; import type {InitializedPlugin, LoadedPlugin} from '@docusaurus/types';
const TestBabelOptions = getBabelOptions({ const TestBabelOptions = getBabelOptions({
isServer: true, isServer: true,
@ -693,7 +693,7 @@ export default function MyComponent(props: Props) {
plugin1, plugin1,
plugin2, plugin2,
{name: 'dummy', options: {}, version: {type: 'synthetic'}} as const, {name: 'dummy', options: {}, version: {type: 'synthetic'}} as const,
]; ] as LoadedPlugin[];
const translations = await extractSiteSourceCodeTranslations( const translations = await extractSiteSourceCodeTranslations(
siteDir, siteDir,
plugins, plugins,

View file

@ -63,7 +63,7 @@ describe('babel transpilation exclude logic', () => {
}); });
describe('base webpack config', () => { describe('base webpack config', () => {
const props: Props = { const props = {
outDir: '', outDir: '',
siteDir: path.resolve(__dirname, '__fixtures__', 'base_test_site'), siteDir: path.resolve(__dirname, '__fixtures__', 'base_test_site'),
siteConfig: {staticDirectories: ['static']}, siteConfig: {staticDirectories: ['static']},
@ -98,7 +98,7 @@ describe('base webpack config', () => {
}, },
}, },
], ],
}; } as Props;
afterEach(() => { afterEach(() => {
jest.restoreAllMocks(); jest.restoreAllMocks();

View file

@ -15,7 +15,11 @@ describe('webpack production config', () => {
it('simple', async () => { it('simple', async () => {
jest.spyOn(console, 'log').mockImplementation(() => {}); jest.spyOn(console, 'log').mockImplementation(() => {});
const props = await loadSetup('simple'); const props = await loadSetup('simple');
const config = await createServerConfig({props}); const config = await createServerConfig({
props,
onHeadTagsCollected: () => {},
onLinksCollected: () => {},
});
const errors = webpack.validate(config); const errors = webpack.validate(config);
expect(errors).toBeUndefined(); expect(errors).toBeUndefined();
}); });
@ -23,7 +27,11 @@ describe('webpack production config', () => {
it('custom', async () => { it('custom', async () => {
jest.spyOn(console, 'log').mockImplementation(() => {}); jest.spyOn(console, 'log').mockImplementation(() => {});
const props = await loadSetup('custom'); const props = await loadSetup('custom');
const config = await createServerConfig({props}); const config = await createServerConfig({
props,
onHeadTagsCollected: () => {},
onLinksCollected: () => {},
});
const errors = webpack.validate(config); const errors = webpack.validate(config);
expect(errors).toBeUndefined(); expect(errors).toBeUndefined();
}); });

View file

@ -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'] = ( const configureWebpack: Plugin['configureWebpack'] = (
generatedConfig, generatedConfig,
isServer, isServer,
@ -125,9 +126,11 @@ describe('extending generated webpack config', () => {
}, },
}; };
const createConfigureWebpack: (mergeStrategy?: { const createConfigureWebpack =
(mergeStrategy?: {
[key: string]: 'prepend' | 'append'; [key: string]: 'prepend' | 'append';
}) => Plugin['configureWebpack'] = (mergeStrategy) => () => ({ }): Plugin['configureWebpack'] =>
() => ({
module: { module: {
rules: [{use: 'zzz'}], rules: [{use: 'zzz'}],
}, },

View file

@ -8,12 +8,7 @@
import rule from '../no-untranslated-text'; import rule from '../no-untranslated-text';
import {getCommonValidTests, RuleTester} from './testUtils'; import {getCommonValidTests, RuleTester} from './testUtils';
const errorsJSX = [ const errorsJSX = [{messageId: 'translateChildren'}] as const;
{messageId: 'translateChildren', type: 'JSXElement'},
] as const;
const errorsJSXFragment = [
{messageId: 'translateChildren', type: 'JSXFragment'},
];
const ruleTester = new RuleTester({ const ruleTester = new RuleTester({
parser: '@typescript-eslint/parser', parser: '@typescript-eslint/parser',
@ -110,7 +105,7 @@ ruleTester.run('no-untranslated-text', rule, {
}, },
{ {
code: '<>text</>', code: '<>text</>',
errors: errorsJSXFragment, errors: errorsJSX,
}, },
{ {
code: '<Component>· — ×</Component>', code: '<Component>· — ×</Component>',

View file

@ -8,12 +8,8 @@
import rule from '../string-literal-i18n-messages'; import rule from '../string-literal-i18n-messages';
import {getCommonValidTests, RuleTester} from './testUtils'; import {getCommonValidTests, RuleTester} from './testUtils';
const errorsJSX = [ const errorsJSX = [{messageId: 'translateChildren'}] as const;
{messageId: 'translateChildren', type: 'JSXElement'}, const errorsFunc = [{messageId: 'translateArg'}] as const;
] as const;
const errorsFunc = [
{messageId: 'translateArg', type: 'CallExpression'},
] as const;
const ruleTester = new RuleTester({ const ruleTester = new RuleTester({
parser: '@typescript-eslint/parser', parser: '@typescript-eslint/parser',