test(theme-common): improve test coverage (#6902)

* test(theme-common): improve test coverage

* revert
This commit is contained in:
Joshua Chen 2022-03-12 13:17:21 +08:00 committed by GitHub
parent aa5a2d4c04
commit f6baaa6b75
No known key found for this signature in database
GPG key ID: 4AEE18F83AFDEB23
59 changed files with 1183 additions and 755 deletions

View file

@ -211,8 +211,12 @@ module.exports = {
WARNING, WARNING,
{maxSize: Infinity, inlineMaxSize: 10}, {maxSize: Infinity, inlineMaxSize: 10},
], ],
'jest/no-test-return-statement': ERROR,
'jest/prefer-expect-resolves': WARNING, 'jest/prefer-expect-resolves': WARNING,
'jest/prefer-lowercase-title': [WARNING, {ignore: ['describe']}], 'jest/prefer-lowercase-title': [WARNING, {ignore: ['describe']}],
'jest/prefer-spy-on': WARNING,
'jest/prefer-to-be': WARNING,
'jest/prefer-to-have-length': WARNING,
'jest/require-top-level-describe': ERROR, 'jest/require-top-level-describe': ERROR,
'jest/valid-title': [ 'jest/valid-title': [
ERROR, ERROR,

View file

@ -64,6 +64,7 @@
"@babel/core": "^7.17.5", "@babel/core": "^7.17.5",
"@babel/preset-typescript": "^7.16.7", "@babel/preset-typescript": "^7.16.7",
"@crowdin/cli": "^3.7.8", "@crowdin/cli": "^3.7.8",
"@testing-library/react-hooks": "^7.0.2",
"@types/fs-extra": "^9.0.13", "@types/fs-extra": "^9.0.13",
"@types/jest": "^27.4.1", "@types/jest": "^27.4.1",
"@types/lodash": "^4.14.179", "@types/lodash": "^4.14.179",

View file

@ -1,6 +1,6 @@
// Jest Snapshot v1, https://goo.gl/fbAQLP // Jest Snapshot v1, https://goo.gl/fbAQLP
exports[`migration test complex website: copy 1`] = ` exports[`migration CLI migrates complex website: copy 1`] = `
Array [ Array [
Array [ Array [
"<PROJECT_ROOT>/packages/docusaurus-migrate/src/__tests__/__fixtures__/complex_website/website/blog", "<PROJECT_ROOT>/packages/docusaurus-migrate/src/__tests__/__fixtures__/complex_website/website/blog",
@ -17,7 +17,7 @@ Array [
] ]
`; `;
exports[`migration test complex website: mkdirp 1`] = ` exports[`migration CLI migrates complex website: mkdirp 1`] = `
Array [ Array [
Array [ Array [
"<PROJECT_ROOT>/packages/docusaurus-migrate/src/__tests__/__fixtures__/migrated_complex_site/src/pages", "<PROJECT_ROOT>/packages/docusaurus-migrate/src/__tests__/__fixtures__/migrated_complex_site/src/pages",
@ -25,9 +25,9 @@ Array [
] ]
`; `;
exports[`migration test complex website: mkdirs 1`] = `Array []`; exports[`migration CLI migrates complex website: mkdirs 1`] = `Array []`;
exports[`migration test complex website: write 1`] = ` exports[`migration CLI migrates complex website: write 1`] = `
Array [ Array [
Array [ Array [
"<PROJECT_ROOT>/packages/docusaurus-migrate/src/__tests__/__fixtures__/migrated_complex_site/docusaurus.config.js", "<PROJECT_ROOT>/packages/docusaurus-migrate/src/__tests__/__fixtures__/migrated_complex_site/docusaurus.config.js",
@ -183,7 +183,7 @@ Array [
] ]
`; `;
exports[`migration test missing versions: copy 1`] = ` exports[`migration CLI migrates missing versions: copy 1`] = `
Array [ Array [
Array [ Array [
"<PROJECT_ROOT>/packages/docusaurus-migrate/src/__tests__/__fixtures__/missing_version_website/website/blog", "<PROJECT_ROOT>/packages/docusaurus-migrate/src/__tests__/__fixtures__/missing_version_website/website/blog",
@ -200,7 +200,7 @@ Array [
] ]
`; `;
exports[`migration test missing versions: mkdirp 1`] = ` exports[`migration CLI migrates missing versions: mkdirp 1`] = `
Array [ Array [
Array [ Array [
"<PROJECT_ROOT>/packages/docusaurus-migrate/src/__tests__/__fixtures__/migrated_missing_version_site/src/pages", "<PROJECT_ROOT>/packages/docusaurus-migrate/src/__tests__/__fixtures__/migrated_missing_version_site/src/pages",
@ -208,9 +208,9 @@ Array [
] ]
`; `;
exports[`migration test missing versions: mkdirs 1`] = `Array []`; exports[`migration CLI migrates missing versions: mkdirs 1`] = `Array []`;
exports[`migration test missing versions: write 1`] = ` exports[`migration CLI migrates missing versions: write 1`] = `
Array [ Array [
Array [ Array [
"<PROJECT_ROOT>/packages/docusaurus-migrate/src/__tests__/__fixtures__/migrated_missing_version_site/docusaurus.config.js", "<PROJECT_ROOT>/packages/docusaurus-migrate/src/__tests__/__fixtures__/migrated_missing_version_site/docusaurus.config.js",
@ -366,7 +366,7 @@ Array [
] ]
`; `;
exports[`migration test simple website: copy 1`] = ` exports[`migration CLI migrates simple website: copy 1`] = `
Array [ Array [
Array [ Array [
"<PROJECT_ROOT>/packages/docusaurus-migrate/src/__tests__/__fixtures__/simple_website/website/pages/en", "<PROJECT_ROOT>/packages/docusaurus-migrate/src/__tests__/__fixtures__/simple_website/website/pages/en",
@ -379,7 +379,7 @@ Array [
] ]
`; `;
exports[`migration test simple website: mkdirp 1`] = ` exports[`migration CLI migrates simple website: mkdirp 1`] = `
Array [ Array [
Array [ Array [
"<PROJECT_ROOT>/packages/docusaurus-migrate/src/__tests__/__fixtures__/migrated_simple_site/src/pages", "<PROJECT_ROOT>/packages/docusaurus-migrate/src/__tests__/__fixtures__/migrated_simple_site/src/pages",
@ -387,9 +387,9 @@ Array [
] ]
`; `;
exports[`migration test simple website: mkdirs 1`] = `Array []`; exports[`migration CLI migrates simple website: mkdirs 1`] = `Array []`;
exports[`migration test simple website: write 1`] = ` exports[`migration CLI migrates simple website: write 1`] = `
Array [ Array [
Array [ Array [
"<PROJECT_ROOT>/packages/docusaurus-migrate/src/__tests__/__fixtures__/migrated_simple_site/docusaurus.config.js", "<PROJECT_ROOT>/packages/docusaurus-migrate/src/__tests__/__fixtures__/migrated_simple_site/docusaurus.config.js",

View file

@ -9,19 +9,19 @@ import {shouldQuotifyFrontMatter} from '../frontMatter';
describe('shouldQuotifyFrontMatter', () => { describe('shouldQuotifyFrontMatter', () => {
it('works', () => { it('works', () => {
expect(shouldQuotifyFrontMatter(['id', 'value'])).toEqual(false); expect(shouldQuotifyFrontMatter(['id', 'value'])).toBe(false);
expect( expect(
shouldQuotifyFrontMatter([ shouldQuotifyFrontMatter([
'title', 'title',
"Some title front matter with allowed special chars like sàáâãäåçèéêëìíîïðòóôõöùúûüýÿ!;,=+-_?'`&#()[]§%€$", "Some title front matter with allowed special chars like sàáâãäåçèéêëìíîïðòóôõöùúûüýÿ!;,=+-_?'`&#()[]§%€$",
]), ]),
).toEqual(false); ).toBe(false);
expect(shouldQuotifyFrontMatter(['title', 'Special char :'])).toEqual(true); expect(shouldQuotifyFrontMatter(['title', 'Special char :'])).toBe(true);
expect(shouldQuotifyFrontMatter(['title', 'value!'])).toEqual(false); expect(shouldQuotifyFrontMatter(['title', 'value!'])).toBe(false);
expect(shouldQuotifyFrontMatter(['title', '!value'])).toEqual(true); expect(shouldQuotifyFrontMatter(['title', '!value'])).toBe(true);
expect(shouldQuotifyFrontMatter(['tags', '[tag1, tag2]'])).toEqual(false); expect(shouldQuotifyFrontMatter(['tags', '[tag1, tag2]'])).toBe(false);
}); });
}); });

View file

@ -43,20 +43,21 @@ async function testMigration(siteDir: string, newDir: string) {
copyMock.mockRestore(); copyMock.mockRestore();
} }
describe('migration test', () => { describe('migration CLI', () => {
const fixtureDir = path.join(__dirname, '__fixtures__'); const fixtureDir = path.join(__dirname, '__fixtures__');
it('simple website', async () => { it('migrates simple website', async () => {
const siteDir = path.join(fixtureDir, 'simple_website', 'website'); const siteDir = path.join(fixtureDir, 'simple_website', 'website');
const newDir = path.join(fixtureDir, 'migrated_simple_site'); const newDir = path.join(fixtureDir, 'migrated_simple_site');
await testMigration(siteDir, newDir); await testMigration(siteDir, newDir);
}); });
it('complex website', async () => {
it('migrates complex website', async () => {
const siteDir = path.join(fixtureDir, 'complex_website', 'website'); const siteDir = path.join(fixtureDir, 'complex_website', 'website');
const newDir = path.join(fixtureDir, 'migrated_complex_site'); const newDir = path.join(fixtureDir, 'migrated_complex_site');
await testMigration(siteDir, newDir); await testMigration(siteDir, newDir);
}); });
it('missing versions', async () => { it('migrates missing versions', async () => {
const siteDir = path.join(fixtureDir, 'missing_version_website', 'website'); const siteDir = path.join(fixtureDir, 'missing_version_website', 'website');
const newDir = path.join(fixtureDir, 'migrated_missing_version_site'); const newDir = path.join(fixtureDir, 'migrated_missing_version_site');
await testMigration(siteDir, newDir); await testMigration(siteDir, newDir);

View file

@ -35,14 +35,8 @@ declare module '@generated/registry' {
} }
declare module '@generated/routes' { declare module '@generated/routes' {
import type {RouteConfig} from 'react-router-config'; import type {Route} from '@docusaurus/types';
export type Route = {
readonly path: string;
readonly component: RouteConfig['component'];
readonly exact?: boolean;
readonly routes?: Route[];
};
const routes: Route[]; const routes: Route[];
export default routes; export default routes;
} }

View file

@ -18,25 +18,25 @@ import writeRedirectFiles, {
// - https://github.com/facebook/docusaurus/issues/3925 // - https://github.com/facebook/docusaurus/issues/3925
describe('createToUrl', () => { describe('createToUrl', () => {
it('creates appropriate redirect urls', async () => { it('creates appropriate redirect urls', async () => {
expect(createToUrl('/', '/docs/something/else')).toEqual( expect(createToUrl('/', '/docs/something/else')).toBe(
'/docs/something/else', '/docs/something/else',
); );
expect(createToUrl('/', '/docs/something/else/')).toEqual( expect(createToUrl('/', '/docs/something/else/')).toBe(
'/docs/something/else/', '/docs/something/else/',
); );
expect(createToUrl('/', 'docs/something/else')).toEqual( expect(createToUrl('/', 'docs/something/else')).toBe(
'/docs/something/else', '/docs/something/else',
); );
}); });
it('creates appropriate redirect urls with baseUrl', async () => { it('creates appropriate redirect urls with baseUrl', async () => {
expect(createToUrl('/baseUrl/', '/docs/something/else')).toEqual( expect(createToUrl('/baseUrl/', '/docs/something/else')).toBe(
'/baseUrl/docs/something/else', '/baseUrl/docs/something/else',
); );
expect(createToUrl('/baseUrl/', '/docs/something/else/')).toEqual( expect(createToUrl('/baseUrl/', '/docs/something/else/')).toBe(
'/baseUrl/docs/something/else/', '/baseUrl/docs/something/else/',
); );
expect(createToUrl('/baseUrl/', 'docs/something/else')).toEqual( expect(createToUrl('/baseUrl/', 'docs/something/else')).toBe(
'/baseUrl/docs/something/else', '/baseUrl/docs/something/else',
); );
}); });
@ -177,11 +177,11 @@ describe('writeRedirectFiles', () => {
await expect( await expect(
fs.readFile(filesMetadata[0].fileAbsolutePath, 'utf8'), fs.readFile(filesMetadata[0].fileAbsolutePath, 'utf8'),
).resolves.toEqual('content 1'); ).resolves.toBe('content 1');
await expect( await expect(
fs.readFile(filesMetadata[1].fileAbsolutePath, 'utf8'), fs.readFile(filesMetadata[1].fileAbsolutePath, 'utf8'),
).resolves.toEqual('content 2'); ).resolves.toBe('content 2');
}); });
it('avoid overwriting existing files', async () => { it('avoid overwriting existing files', async () => {

View file

@ -75,17 +75,17 @@ describe('truncate', () => {
it('truncates texts', () => { it('truncates texts', () => {
expect( expect(
truncate('aaa\n<!-- truncate -->\nbbb\nccc', /<!-- truncate -->/), truncate('aaa\n<!-- truncate -->\nbbb\nccc', /<!-- truncate -->/),
).toEqual('aaa\n'); ).toBe('aaa\n');
expect( expect(truncate('\n<!-- truncate -->\nbbb\nccc', /<!-- truncate -->/)).toBe(
truncate('\n<!-- truncate -->\nbbb\nccc', /<!-- truncate -->/), '\n',
).toEqual('\n'); );
}); });
it('leaves texts without markers', () => { it('leaves texts without markers', () => {
expect(truncate('aaa\nbbb\nccc', /<!-- truncate -->/)).toEqual( expect(truncate('aaa\nbbb\nccc', /<!-- truncate -->/)).toBe(
'aaa\nbbb\nccc', 'aaa\nbbb\nccc',
); );
expect(truncate('', /<!-- truncate -->/)).toEqual(''); expect(truncate('', /<!-- truncate -->/)).toBe('');
}); });
}); });

View file

@ -341,7 +341,7 @@ describe('blog plugin', () => {
(v) => v.metadata.title === 'Happy 1st Birthday Slash! (translated)', (v) => v.metadata.title === 'Happy 1st Birthday Slash! (translated)',
)!; )!;
expect(localizedBlogPost.metadata.editUrl).toEqual( expect(localizedBlogPost.metadata.editUrl).toBe(
`${BaseEditUrl}/i18n/en/docusaurus-plugin-content-blog/2018-12-14-Happy-First-Birthday-Slash.md`, `${BaseEditUrl}/i18n/en/docusaurus-plugin-content-blog/2018-12-14-Happy-First-Birthday-Slash.md`,
); );
}); });
@ -478,7 +478,7 @@ describe('blog plugin', () => {
postsPerPage: 2, postsPerPage: 2,
}); });
expect(Object.keys(blogTags).length).toEqual(2); expect(Object.keys(blogTags)).toHaveLength(2);
expect(blogTags).toMatchSnapshot(); expect(blogTags).toMatchSnapshot();
}); });

View file

@ -15,7 +15,7 @@ describe('blog plugin options schema', () => {
it('normalizes options', () => { it('normalizes options', () => {
const {value, error} = PluginOptionSchema.validate({}); const {value, error} = PluginOptionSchema.validate({});
expect(value).toEqual(DEFAULT_OPTIONS); expect(value).toEqual(DEFAULT_OPTIONS);
expect(error).toBe(undefined); expect(error).toBeUndefined();
}); });
it('accepts correctly defined user options', () => { it('accepts correctly defined user options', () => {
@ -32,7 +32,7 @@ describe('blog plugin options schema', () => {
...userOptions, ...userOptions,
feedOptions: {type: ['rss'], title: 'myTitle', copyright: ''}, feedOptions: {type: ['rss'], title: 'myTitle', copyright: ''},
}); });
expect(error).toBe(undefined); expect(error).toBeUndefined();
}); });
it('accepts valid user options', async () => { it('accepts valid user options', async () => {
@ -49,7 +49,7 @@ describe('blog plugin options schema', () => {
}; };
const {value, error} = PluginOptionSchema.validate(userOptions); const {value, error} = PluginOptionSchema.validate(userOptions);
expect(value).toEqual(userOptions); expect(value).toEqual(userOptions);
expect(error).toBe(undefined); expect(error).toBeUndefined();
}); });
it('throws Error in case of invalid options', () => { it('throws Error in case of invalid options', () => {
@ -91,7 +91,7 @@ describe('blog plugin options schema', () => {
...DEFAULT_OPTIONS, ...DEFAULT_OPTIONS,
feedOptions: {type: null}, feedOptions: {type: null},
}); });
expect(error).toBe(undefined); expect(error).toBeUndefined();
}); });
it('contains array with rss + atom for missing feed type', () => { it('contains array with rss + atom for missing feed type', () => {
@ -117,14 +117,14 @@ describe('blog sidebar', () => {
const userOptions = {blogSidebarCount: 0}; const userOptions = {blogSidebarCount: 0};
const {value, error} = PluginOptionSchema.validate(userOptions); const {value, error} = PluginOptionSchema.validate(userOptions);
expect(value).toEqual({...DEFAULT_OPTIONS, ...userOptions}); expect(value).toEqual({...DEFAULT_OPTIONS, ...userOptions});
expect(error).toBe(undefined); expect(error).toBeUndefined();
}); });
it('accepts "ALL" sidebar count', () => { it('accepts "ALL" sidebar count', () => {
const userOptions = {blogSidebarCount: 'ALL'}; const userOptions = {blogSidebarCount: 'ALL'};
const {value, error} = PluginOptionSchema.validate(userOptions); const {value, error} = PluginOptionSchema.validate(userOptions);
expect(value).toEqual({...DEFAULT_OPTIONS, ...userOptions}); expect(value).toEqual({...DEFAULT_OPTIONS, ...userOptions});
expect(error).toBe(undefined); expect(error).toBeUndefined();
}); });
it('rejects "abcdef" sidebar count', () => { it('rejects "abcdef" sidebar count', () => {
@ -139,7 +139,7 @@ describe('blog sidebar', () => {
const userOptions = {blogSidebarTitle: 'all posts'}; const userOptions = {blogSidebarTitle: 'all posts'};
const {value, error} = PluginOptionSchema.validate(userOptions); const {value, error} = PluginOptionSchema.validate(userOptions);
expect(value).toEqual({...DEFAULT_OPTIONS, ...userOptions}); expect(value).toEqual({...DEFAULT_OPTIONS, ...userOptions});
expect(error).toBe(undefined); expect(error).toBeUndefined();
}); });
it('rejects 42 sidebar title', () => { it('rejects 42 sidebar title', () => {

View file

@ -16,6 +16,29 @@ Object {
} }
`; `;
exports[`sidebar site with wrong sidebar content 1`] = `
"Invalid sidebar file at \\"packages/docusaurus-plugin-content-docs/src/__tests__/__fixtures__/simple-site/wrong-sidebars.json\\".
These sidebar document ids do not exist:
- goku
Available document ids are:
- doc with space
- foo/bar
- foo/baz
- headingAsTitle
- hello
- ipsum
- lorem
- rootAbsoluteSlug
- rootRelativeSlug
- rootResolvedSlug
- rootTryToEscapeSlug
- slugs/absoluteSlug
- slugs/relativeSlug
- slugs/resolvedSlug
- slugs/tryToEscapeSlug"
`;
exports[`simple website content 1`] = ` exports[`simple website content 1`] = `
Object { Object {
"description": "Images", "description": "Images",

View file

@ -176,7 +176,7 @@ describe('simple site', () => {
context, context,
options, options,
}); });
expect(versionsMetadata.length).toEqual(1); expect(versionsMetadata).toHaveLength(1);
const [currentVersion] = versionsMetadata; const [currentVersion] = versionsMetadata;
const defaultTestUtils = createTestUtils({ const defaultTestUtils = createTestUtils({
@ -533,7 +533,7 @@ describe('versioned site', () => {
context, context,
options, options,
}); });
expect(versionsMetadata.length).toEqual(4); expect(versionsMetadata).toHaveLength(4);
const [currentVersion, version101, version100, versionWithSlugs] = const [currentVersion, version101, version100, versionWithSlugs] =
versionsMetadata; versionsMetadata;
@ -947,28 +947,28 @@ describe('isConventionalDocIndex', () => {
directories: ['doesNotMatter'], directories: ['doesNotMatter'],
extension: '.md', extension: '.md',
}), }),
).toEqual(true); ).toBe(true);
expect( expect(
isCategoryIndex({ isCategoryIndex({
fileName: 'readme', fileName: 'readme',
directories: ['doesNotMatter'], directories: ['doesNotMatter'],
extension: '.mdx', extension: '.mdx',
}), }),
).toEqual(true); ).toBe(true);
expect( expect(
isCategoryIndex({ isCategoryIndex({
fileName: 'README', fileName: 'README',
directories: ['doesNotMatter'], directories: ['doesNotMatter'],
extension: '.md', extension: '.md',
}), }),
).toEqual(true); ).toBe(true);
expect( expect(
isCategoryIndex({ isCategoryIndex({
fileName: 'ReAdMe', fileName: 'ReAdMe',
directories: ['doesNotMatter'], directories: ['doesNotMatter'],
extension: '', extension: '',
}), }),
).toEqual(true); ).toBe(true);
}); });
it('supports index', () => { it('supports index', () => {
@ -978,28 +978,28 @@ describe('isConventionalDocIndex', () => {
directories: ['doesNotMatter'], directories: ['doesNotMatter'],
extension: '.md', extension: '.md',
}), }),
).toEqual(true); ).toBe(true);
expect( expect(
isCategoryIndex({ isCategoryIndex({
fileName: 'index', fileName: 'index',
directories: ['doesNotMatter'], directories: ['doesNotMatter'],
extension: '.mdx', extension: '.mdx',
}), }),
).toEqual(true); ).toBe(true);
expect( expect(
isCategoryIndex({ isCategoryIndex({
fileName: 'INDEX', fileName: 'INDEX',
directories: ['doesNotMatter'], directories: ['doesNotMatter'],
extension: '.md', extension: '.md',
}), }),
).toEqual(true); ).toBe(true);
expect( expect(
isCategoryIndex({ isCategoryIndex({
fileName: 'InDeX', fileName: 'InDeX',
directories: ['doesNotMatter'], directories: ['doesNotMatter'],
extension: '', extension: '',
}), }),
).toEqual(true); ).toBe(true);
}); });
it('supports <categoryName>/<categoryName>.md', () => { it('supports <categoryName>/<categoryName>.md', () => {
@ -1009,35 +1009,35 @@ describe('isConventionalDocIndex', () => {
directories: ['someCategory', 'doesNotMatter'], directories: ['someCategory', 'doesNotMatter'],
extension: '', extension: '',
}), }),
).toEqual(true); ).toBe(true);
expect( expect(
isCategoryIndex({ isCategoryIndex({
fileName: 'someCategory', fileName: 'someCategory',
directories: ['someCategory'], directories: ['someCategory'],
extension: '.md', extension: '.md',
}), }),
).toEqual(true); ).toBe(true);
expect( expect(
isCategoryIndex({ isCategoryIndex({
fileName: 'someCategory', fileName: 'someCategory',
directories: ['someCategory'], directories: ['someCategory'],
extension: '.mdx', extension: '.mdx',
}), }),
).toEqual(true); ).toBe(true);
expect( expect(
isCategoryIndex({ isCategoryIndex({
fileName: 'SOME_CATEGORY', fileName: 'SOME_CATEGORY',
directories: ['some_category'], directories: ['some_category'],
extension: '.md', extension: '.md',
}), }),
).toEqual(true); ).toBe(true);
expect( expect(
isCategoryIndex({ isCategoryIndex({
fileName: 'some_category', fileName: 'some_category',
directories: ['some_category'], directories: ['some_category'],
extension: '', extension: '',
}), }),
).toEqual(true); ).toBe(true);
}); });
it('reject other cases', () => { it('reject other cases', () => {
@ -1047,20 +1047,20 @@ describe('isConventionalDocIndex', () => {
directories: ['someCategory'], directories: ['someCategory'],
extension: '', extension: '',
}), }),
).toEqual(false); ).toBe(false);
expect( expect(
isCategoryIndex({ isCategoryIndex({
fileName: 'read_me', fileName: 'read_me',
directories: ['doesNotMatter'], directories: ['doesNotMatter'],
extension: '', extension: '',
}), }),
).toEqual(false); ).toBe(false);
expect( expect(
isCategoryIndex({ isCategoryIndex({
fileName: 'the index', fileName: 'the index',
directories: ['doesNotMatter'], directories: ['doesNotMatter'],
extension: '', extension: '',
}), }),
).toEqual(false); ).toBe(false);
}); });
}); });

View file

@ -123,29 +123,7 @@ describe('sidebar', () => {
sidebarPath, sidebarPath,
}), }),
); );
await expect(plugin.loadContent!()).rejects await expect(plugin.loadContent!()).rejects.toThrowErrorMatchingSnapshot();
.toThrowErrorMatchingInlineSnapshot(`
"Invalid sidebar file at \\"packages/docusaurus-plugin-content-docs/src/__tests__/__fixtures__/simple-site/wrong-sidebars.json\\".
These sidebar document ids do not exist:
- goku
Available document ids are:
- doc with space
- foo/bar
- foo/baz
- headingAsTitle
- hello
- ipsum
- lorem
- rootAbsoluteSlug
- rootRelativeSlug
- rootResolvedSlug
- rootTryToEscapeSlug
- slugs/absoluteSlug
- slugs/relativeSlug
- slugs/resolvedSlug
- slugs/tryToEscapeSlug"
`);
}); });
it('site with wrong sidebar file path', async () => { it('site with wrong sidebar file path', async () => {
@ -281,17 +259,17 @@ describe('simple website', () => {
posixPath(path.relative(siteDir, filepath)), posixPath(path.relative(siteDir, filepath)),
); );
expect(matchPattern).toMatchSnapshot(); expect(matchPattern).toMatchSnapshot();
expect(isMatch('docs/hello.md', matchPattern)).toEqual(true); expect(isMatch('docs/hello.md', matchPattern)).toBe(true);
expect(isMatch('docs/hello.mdx', matchPattern)).toEqual(true); expect(isMatch('docs/hello.mdx', matchPattern)).toBe(true);
expect(isMatch('docs/foo/bar.md', matchPattern)).toEqual(true); expect(isMatch('docs/foo/bar.md', matchPattern)).toBe(true);
expect(isMatch('docs/hello.js', matchPattern)).toEqual(false); expect(isMatch('docs/hello.js', matchPattern)).toBe(false);
expect(isMatch('docs/super.mdl', matchPattern)).toEqual(false); expect(isMatch('docs/super.mdl', matchPattern)).toBe(false);
expect(isMatch('docs/mdx', matchPattern)).toEqual(false); expect(isMatch('docs/mdx', matchPattern)).toBe(false);
expect(isMatch('docs/headingAsTitle.md', matchPattern)).toEqual(true); expect(isMatch('docs/headingAsTitle.md', matchPattern)).toBe(true);
expect(isMatch('sidebars.json', matchPattern)).toEqual(true); expect(isMatch('sidebars.json', matchPattern)).toBe(true);
expect(isMatch('versioned_docs/hello.md', matchPattern)).toEqual(false); expect(isMatch('versioned_docs/hello.md', matchPattern)).toBe(false);
expect(isMatch('hello.md', matchPattern)).toEqual(false); expect(isMatch('hello.md', matchPattern)).toBe(false);
expect(isMatch('super/docs/hello.md', matchPattern)).toEqual(false); expect(isMatch('super/docs/hello.md', matchPattern)).toBe(false);
}); });
it('configureWebpack', async () => { it('configureWebpack', async () => {
@ -319,7 +297,7 @@ describe('simple website', () => {
it('content', async () => { it('content', async () => {
const {plugin, pluginContentDir} = await loadSite(); const {plugin, pluginContentDir} = await loadSite();
const content = await plugin.loadContent!(); const content = await plugin.loadContent!();
expect(content.loadedVersions.length).toEqual(1); expect(content.loadedVersions).toHaveLength(1);
const [currentVersion] = content.loadedVersions; const [currentVersion] = content.loadedVersions;
expect(findDocById(currentVersion, 'foo/baz')).toMatchSnapshot(); expect(findDocById(currentVersion, 'foo/baz')).toMatchSnapshot();
@ -398,42 +376,42 @@ describe('versioned website', () => {
); );
expect(matchPattern).not.toEqual([]); expect(matchPattern).not.toEqual([]);
expect(matchPattern).toMatchSnapshot(); expect(matchPattern).toMatchSnapshot();
expect(isMatch('docs/hello.md', matchPattern)).toEqual(true); expect(isMatch('docs/hello.md', matchPattern)).toBe(true);
expect(isMatch('docs/hello.mdx', matchPattern)).toEqual(true); expect(isMatch('docs/hello.mdx', matchPattern)).toBe(true);
expect(isMatch('docs/foo/bar.md', matchPattern)).toEqual(true); expect(isMatch('docs/foo/bar.md', matchPattern)).toBe(true);
expect(isMatch('sidebars.json', matchPattern)).toEqual(true); expect(isMatch('sidebars.json', matchPattern)).toBe(true);
expect( expect(isMatch('versioned_docs/version-1.0.0/hello.md', matchPattern)).toBe(
isMatch('versioned_docs/version-1.0.0/hello.md', matchPattern), true,
).toEqual(true); );
expect( expect(
isMatch('versioned_docs/version-1.0.0/foo/bar.md', matchPattern), isMatch('versioned_docs/version-1.0.0/foo/bar.md', matchPattern),
).toEqual(true); ).toBe(true);
expect( expect(
isMatch('versioned_sidebars/version-1.0.0-sidebars.json', matchPattern), isMatch('versioned_sidebars/version-1.0.0-sidebars.json', matchPattern),
).toEqual(true); ).toBe(true);
// Non existing version // Non existing version
expect( expect(
isMatch('versioned_docs/version-2.0.0/foo/bar.md', matchPattern), isMatch('versioned_docs/version-2.0.0/foo/bar.md', matchPattern),
).toEqual(false); ).toBe(false);
expect( expect(isMatch('versioned_docs/version-2.0.0/hello.md', matchPattern)).toBe(
isMatch('versioned_docs/version-2.0.0/hello.md', matchPattern), false,
).toEqual(false); );
expect( expect(
isMatch('versioned_sidebars/version-2.0.0-sidebars.json', matchPattern), isMatch('versioned_sidebars/version-2.0.0-sidebars.json', matchPattern),
).toEqual(false); ).toBe(false);
expect(isMatch('docs/hello.js', matchPattern)).toEqual(false); expect(isMatch('docs/hello.js', matchPattern)).toBe(false);
expect(isMatch('docs/super.mdl', matchPattern)).toEqual(false); expect(isMatch('docs/super.mdl', matchPattern)).toBe(false);
expect(isMatch('docs/mdx', matchPattern)).toEqual(false); expect(isMatch('docs/mdx', matchPattern)).toBe(false);
expect(isMatch('hello.md', matchPattern)).toEqual(false); expect(isMatch('hello.md', matchPattern)).toBe(false);
expect(isMatch('super/docs/hello.md', matchPattern)).toEqual(false); expect(isMatch('super/docs/hello.md', matchPattern)).toBe(false);
}); });
it('content', async () => { it('content', async () => {
const {plugin, pluginContentDir} = await loadSite(); const {plugin, pluginContentDir} = await loadSite();
const content = await plugin.loadContent!(); const content = await plugin.loadContent!();
expect(content.loadedVersions.length).toEqual(4); expect(content.loadedVersions).toHaveLength(4);
const [currentVersion, version101, version100, versionWithSlugs] = const [currentVersion, version101, version100, versionWithSlugs] =
content.loadedVersions; content.loadedVersions;
@ -529,32 +507,32 @@ describe('versioned website (community)', () => {
); );
expect(matchPattern).not.toEqual([]); expect(matchPattern).not.toEqual([]);
expect(matchPattern).toMatchSnapshot(); expect(matchPattern).toMatchSnapshot();
expect(isMatch('community/team.md', matchPattern)).toEqual(true); expect(isMatch('community/team.md', matchPattern)).toBe(true);
expect( expect(
isMatch('community_versioned_docs/version-1.0.0/team.md', matchPattern), isMatch('community_versioned_docs/version-1.0.0/team.md', matchPattern),
).toEqual(true); ).toBe(true);
// Non existing version // Non existing version
expect( expect(
isMatch('community_versioned_docs/version-2.0.0/team.md', matchPattern), isMatch('community_versioned_docs/version-2.0.0/team.md', matchPattern),
).toEqual(false); ).toBe(false);
expect( expect(
isMatch( isMatch(
'community_versioned_sidebars/version-2.0.0-sidebars.json', 'community_versioned_sidebars/version-2.0.0-sidebars.json',
matchPattern, matchPattern,
), ),
).toEqual(false); ).toBe(false);
expect(isMatch('community/team.js', matchPattern)).toEqual(false); expect(isMatch('community/team.js', matchPattern)).toBe(false);
expect( expect(
isMatch('community_versioned_docs/version-1.0.0/team.js', matchPattern), isMatch('community_versioned_docs/version-1.0.0/team.js', matchPattern),
).toEqual(false); ).toBe(false);
}); });
it('content', async () => { it('content', async () => {
const {plugin, pluginContentDir} = await loadSite(); const {plugin, pluginContentDir} = await loadSite();
const content = await plugin.loadContent!(); const content = await plugin.loadContent!();
expect(content.loadedVersions.length).toEqual(2); expect(content.loadedVersions).toHaveLength(2);
const [currentVersion, version100] = content.loadedVersions; const [currentVersion, version100] = content.loadedVersions;
expect(getDocById(currentVersion, 'team')).toMatchSnapshot(); expect(getDocById(currentVersion, 'team')).toMatchSnapshot();
@ -600,7 +578,7 @@ describe('site with doc label', () => {
const loadedVersion = content.loadedVersions[0]; const loadedVersion = content.loadedVersions[0];
const sidebarProps = toSidebarsProp(loadedVersion); const sidebarProps = toSidebarsProp(loadedVersion);
expect(sidebarProps.docs[0].label).toEqual('Hello One'); expect(sidebarProps.docs[0].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 () => {
@ -608,7 +586,7 @@ describe('site with doc label', () => {
const loadedVersion = content.loadedVersions[0]; const loadedVersion = content.loadedVersions[0];
const sidebarProps = toSidebarsProp(loadedVersion); const sidebarProps = toSidebarsProp(loadedVersion);
expect(sidebarProps.docs[1].label).toEqual('Hello 2 From Doc'); expect(sidebarProps.docs[1].label).toBe('Hello 2 From Doc');
}); });
}); });

View file

@ -70,45 +70,37 @@ describe('stripNumberPrefix', () => {
} }
it('strips number prefix if present', () => { it('strips number prefix if present', () => {
expect(stripNumberPrefixDefault('1-My Doc')).toEqual('My Doc'); expect(stripNumberPrefixDefault('1-My Doc')).toBe('My Doc');
expect(stripNumberPrefixDefault('01-My Doc')).toEqual('My Doc'); expect(stripNumberPrefixDefault('01-My Doc')).toBe('My Doc');
expect(stripNumberPrefixDefault('001-My Doc')).toEqual('My Doc'); expect(stripNumberPrefixDefault('001-My Doc')).toBe('My Doc');
expect(stripNumberPrefixDefault('001 - My Doc')).toEqual('My Doc'); expect(stripNumberPrefixDefault('001 - My Doc')).toBe('My Doc');
expect(stripNumberPrefixDefault('001 - My Doc')).toEqual('My Doc'); expect(stripNumberPrefixDefault('001 - My Doc')).toBe('My Doc');
expect(stripNumberPrefixDefault('999 - My Doc')).toEqual( expect(stripNumberPrefixDefault('999 - My Doc')).toBe('My Doc');
//
expect(stripNumberPrefixDefault('1---My Doc')).toBe('My Doc');
expect(stripNumberPrefixDefault('01---My Doc')).toBe('My Doc');
expect(stripNumberPrefixDefault('001---My Doc')).toBe('My Doc');
expect(stripNumberPrefixDefault('001 --- My Doc')).toBe('My Doc');
expect(stripNumberPrefixDefault('001 --- My Doc')).toBe('My Doc');
expect(stripNumberPrefixDefault('999 --- My Doc')).toBe(
'My Doc', 'My Doc',
); );
// //
expect(stripNumberPrefixDefault('1---My Doc')).toEqual('My Doc'); expect(stripNumberPrefixDefault('1___My Doc')).toBe('My Doc');
expect(stripNumberPrefixDefault('01---My Doc')).toEqual('My Doc'); expect(stripNumberPrefixDefault('01___My Doc')).toBe('My Doc');
expect(stripNumberPrefixDefault('001---My Doc')).toEqual('My Doc'); expect(stripNumberPrefixDefault('001___My Doc')).toBe('My Doc');
expect(stripNumberPrefixDefault('001 --- My Doc')).toEqual('My Doc'); expect(stripNumberPrefixDefault('001 ___ My Doc')).toBe('My Doc');
expect(stripNumberPrefixDefault('001 --- My Doc')).toEqual( expect(stripNumberPrefixDefault('001 ___ My Doc')).toBe('My Doc');
'My Doc', expect(stripNumberPrefixDefault('999 ___ My Doc')).toBe(
);
expect(stripNumberPrefixDefault('999 --- My Doc')).toEqual(
'My Doc', 'My Doc',
); );
// //
expect(stripNumberPrefixDefault('1___My Doc')).toEqual('My Doc'); expect(stripNumberPrefixDefault('1.My Doc')).toBe('My Doc');
expect(stripNumberPrefixDefault('01___My Doc')).toEqual('My Doc'); expect(stripNumberPrefixDefault('01.My Doc')).toBe('My Doc');
expect(stripNumberPrefixDefault('001___My Doc')).toEqual('My Doc'); expect(stripNumberPrefixDefault('001.My Doc')).toBe('My Doc');
expect(stripNumberPrefixDefault('001 ___ My Doc')).toEqual('My Doc'); expect(stripNumberPrefixDefault('001 . My Doc')).toBe('My Doc');
expect(stripNumberPrefixDefault('001 ___ My Doc')).toEqual( expect(stripNumberPrefixDefault('001 . My Doc')).toBe('My Doc');
'My Doc', expect(stripNumberPrefixDefault('999 . My Doc')).toBe('My Doc');
);
expect(stripNumberPrefixDefault('999 ___ My Doc')).toEqual(
'My Doc',
);
//
expect(stripNumberPrefixDefault('1.My Doc')).toEqual('My Doc');
expect(stripNumberPrefixDefault('01.My Doc')).toEqual('My Doc');
expect(stripNumberPrefixDefault('001.My Doc')).toEqual('My Doc');
expect(stripNumberPrefixDefault('001 . My Doc')).toEqual('My Doc');
expect(stripNumberPrefixDefault('001 . My Doc')).toEqual('My Doc');
expect(stripNumberPrefixDefault('999 . My Doc')).toEqual(
'My Doc',
);
}); });
it('does not strip number prefix if pattern does not match', () => { it('does not strip number prefix if pattern does not match', () => {
@ -125,7 +117,7 @@ describe('stripPathNumberPrefix', () => {
'0-MyRootFolder0/1 - MySubFolder1/2. MyDeepFolder2/3 _MyDoc3', '0-MyRootFolder0/1 - MySubFolder1/2. MyDeepFolder2/3 _MyDoc3',
DefaultNumberPrefixParser, DefaultNumberPrefixParser,
), ),
).toEqual('MyRootFolder0/MySubFolder1/MyDeepFolder2/MyDoc3'); ).toBe('MyRootFolder0/MySubFolder1/MyDeepFolder2/MyDoc3');
}); });
it('strips number prefixes in paths with custom parser', () => { it('strips number prefixes in paths with custom parser', () => {
@ -138,7 +130,7 @@ describe('stripPathNumberPrefix', () => {
expect( expect(
stripPathNumberPrefixes('aaaa/bbbb/cccc', stripPathNumberPrefixCustom), stripPathNumberPrefixes('aaaa/bbbb/cccc', stripPathNumberPrefixCustom),
).toEqual('aaa/bbb/ccc'); ).toBe('aaa/bbb/ccc');
}); });
it('does not strip number prefixes in paths with disabled parser', () => { it('does not strip number prefixes in paths with disabled parser', () => {
@ -147,7 +139,7 @@ describe('stripPathNumberPrefix', () => {
'0-MyRootFolder0/1 - MySubFolder1/2. MyDeepFolder2/3 _MyDoc3', '0-MyRootFolder0/1 - MySubFolder1/2. MyDeepFolder2/3 _MyDoc3',
DisabledNumberPrefixParser, DisabledNumberPrefixParser,
), ),
).toEqual('0-MyRootFolder0/1 - MySubFolder1/2. MyDeepFolder2/3 _MyDoc3'); ).toBe('0-MyRootFolder0/1 - MySubFolder1/2. MyDeepFolder2/3 _MyDoc3');
}); });
}); });

View file

@ -33,7 +33,7 @@ describe('normalizeDocsPluginOptions', () => {
it('returns default options for undefined user options', async () => { it('returns default options for undefined user options', async () => {
const {value, error} = await OptionsSchema.validate({}); const {value, error} = await OptionsSchema.validate({});
expect(value).toEqual(DEFAULT_OPTIONS); expect(value).toEqual(DEFAULT_OPTIONS);
expect(error).toBe(undefined); expect(error).toBeUndefined();
}); });
it('accepts correctly defined user options', async () => { it('accepts correctly defined user options', async () => {
@ -79,7 +79,7 @@ describe('normalizeDocsPluginOptions', () => {
}; };
const {value, error} = await OptionsSchema.validate(userOptions); const {value, error} = await OptionsSchema.validate(userOptions);
expect(value).toEqual(userOptions); expect(value).toEqual(userOptions);
expect(error).toBe(undefined); expect(error).toBeUndefined();
}); });
it('accepts correctly defined remark and rehype plugin options', async () => { it('accepts correctly defined remark and rehype plugin options', async () => {
@ -95,7 +95,7 @@ describe('normalizeDocsPluginOptions', () => {
}; };
const {value, error} = await OptionsSchema.validate(userOptions); const {value, error} = await OptionsSchema.validate(userOptions);
expect(value).toEqual(userOptions); expect(value).toEqual(userOptions);
expect(error).toBe(undefined); expect(error).toBeUndefined();
}); });
it('accepts admonitions false', async () => { it('accepts admonitions false', async () => {
@ -105,7 +105,7 @@ describe('normalizeDocsPluginOptions', () => {
}; };
const {value, error} = OptionsSchema.validate(admonitionsFalse); const {value, error} = OptionsSchema.validate(admonitionsFalse);
expect(value).toEqual(admonitionsFalse); expect(value).toEqual(admonitionsFalse);
expect(error).toBe(undefined); expect(error).toBeUndefined();
}); });
it('accepts numberPrefixParser function', () => { it('accepts numberPrefixParser function', () => {
@ -256,7 +256,7 @@ describe('normalizeDocsPluginOptions', () => {
sidebarCollapsible: true, sidebarCollapsible: true,
sidebarCollapsed: undefined, sidebarCollapsed: undefined,
}).sidebarCollapsed, }).sidebarCollapsed,
).toEqual(true); ).toBe(true);
expect( expect(
testValidateOptions({ testValidateOptions({
@ -264,7 +264,7 @@ describe('normalizeDocsPluginOptions', () => {
sidebarCollapsible: false, sidebarCollapsible: false,
sidebarCollapsed: undefined, sidebarCollapsed: undefined,
}).sidebarCollapsed, }).sidebarCollapsed,
).toEqual(false); ).toBe(false);
expect( expect(
testValidateOptions({ testValidateOptions({
@ -272,6 +272,6 @@ describe('normalizeDocsPluginOptions', () => {
sidebarCollapsible: false, sidebarCollapsible: false,
sidebarCollapsed: true, sidebarCollapsed: true,
}).sidebarCollapsed, }).sidebarCollapsed,
).toEqual(false); ).toBe(false);
}); });
}); });

View file

@ -15,14 +15,14 @@ describe('getSlug', () => {
source: '@site/docs/dir/doc.md', source: '@site/docs/dir/doc.md',
sourceDirName: '/dir', sourceDirName: '/dir',
}), }),
).toEqual('/dir/doc'); ).toBe('/dir/doc');
expect( expect(
getSlug({ getSlug({
baseID: 'doc', baseID: 'doc',
source: '@site/docs/dir/subdir/doc.md', source: '@site/docs/dir/subdir/doc.md',
sourceDirName: '/dir/subdir', sourceDirName: '/dir/subdir',
}), }),
).toEqual('/dir/subdir/doc'); ).toBe('/dir/subdir/doc');
}); });
it('handles conventional doc indexes', () => { it('handles conventional doc indexes', () => {
@ -32,42 +32,42 @@ describe('getSlug', () => {
source: '@site/docs/dir/subdir/index.md', source: '@site/docs/dir/subdir/index.md',
sourceDirName: '/dir/subdir', sourceDirName: '/dir/subdir',
}), }),
).toEqual('/dir/subdir/'); ).toBe('/dir/subdir/');
expect( expect(
getSlug({ getSlug({
baseID: 'doc', baseID: 'doc',
source: '@site/docs/dir/subdir/inDEx.mdx', source: '@site/docs/dir/subdir/inDEx.mdx',
sourceDirName: '/dir/subdir', sourceDirName: '/dir/subdir',
}), }),
).toEqual('/dir/subdir/'); ).toBe('/dir/subdir/');
expect( expect(
getSlug({ getSlug({
baseID: 'doc', baseID: 'doc',
source: '@site/docs/dir/subdir/readme.md', source: '@site/docs/dir/subdir/readme.md',
sourceDirName: '/dir/subdir', sourceDirName: '/dir/subdir',
}), }),
).toEqual('/dir/subdir/'); ).toBe('/dir/subdir/');
expect( expect(
getSlug({ getSlug({
baseID: 'doc', baseID: 'doc',
source: '@site/docs/dir/subdir/reADMe.mdx', source: '@site/docs/dir/subdir/reADMe.mdx',
sourceDirName: '/dir/subdir', sourceDirName: '/dir/subdir',
}), }),
).toEqual('/dir/subdir/'); ).toBe('/dir/subdir/');
expect( expect(
getSlug({ getSlug({
baseID: 'doc', baseID: 'doc',
source: '@site/docs/dir/subdir/subdir.md', source: '@site/docs/dir/subdir/subdir.md',
sourceDirName: '/dir/subdir', sourceDirName: '/dir/subdir',
}), }),
).toEqual('/dir/subdir/'); ).toBe('/dir/subdir/');
expect( expect(
getSlug({ getSlug({
baseID: 'doc', baseID: 'doc',
source: '@site/docs/dir/subdir/suBDir.mdx', source: '@site/docs/dir/subdir/suBDir.mdx',
sourceDirName: '/dir/subdir', sourceDirName: '/dir/subdir',
}), }),
).toEqual('/dir/subdir/'); ).toBe('/dir/subdir/');
}); });
it('ignores conventional doc index when explicit slug front matter is provided', () => { it('ignores conventional doc index when explicit slug front matter is provided', () => {
@ -78,7 +78,7 @@ describe('getSlug', () => {
sourceDirName: '/dir/subdir', sourceDirName: '/dir/subdir',
frontMatterSlug: '/my/frontMatterSlug', frontMatterSlug: '/my/frontMatterSlug',
}), }),
).toEqual('/my/frontMatterSlug'); ).toBe('/my/frontMatterSlug');
}); });
it('can strip dir number prefixes', () => { it('can strip dir number prefixes', () => {
@ -89,7 +89,7 @@ describe('getSlug', () => {
sourceDirName: '/001-dir1/002-dir2', sourceDirName: '/001-dir1/002-dir2',
stripDirNumberPrefixes: true, stripDirNumberPrefixes: true,
}), }),
).toEqual('/dir1/dir2/doc'); ).toBe('/dir1/dir2/doc');
expect( expect(
getSlug({ getSlug({
baseID: 'doc', baseID: 'doc',
@ -97,7 +97,7 @@ describe('getSlug', () => {
sourceDirName: '/001-dir1/002-dir2', sourceDirName: '/001-dir1/002-dir2',
stripDirNumberPrefixes: false, stripDirNumberPrefixes: false,
}), }),
).toEqual('/001-dir1/002-dir2/doc'); ).toBe('/001-dir1/002-dir2/doc');
}); });
// See https://github.com/facebook/docusaurus/issues/3223 // See https://github.com/facebook/docusaurus/issues/3223
@ -108,16 +108,16 @@ describe('getSlug', () => {
source: '@site/docs/dir with spâce/hey $hello/doc.md', source: '@site/docs/dir with spâce/hey $hello/doc.md',
sourceDirName: '/dir with spâce/hey $hello', sourceDirName: '/dir with spâce/hey $hello',
}), }),
).toEqual('/dir with spâce/hey $hello/my dôc'); ).toBe('/dir with spâce/hey $hello/my dôc');
}); });
it('handles current dir', () => { it('handles current dir', () => {
expect( expect(
getSlug({baseID: 'doc', source: '@site/docs/doc.md', sourceDirName: '.'}), getSlug({baseID: 'doc', source: '@site/docs/doc.md', sourceDirName: '.'}),
).toEqual('/doc'); ).toBe('/doc');
expect( expect(
getSlug({baseID: 'doc', source: '@site/docs/doc.md', sourceDirName: '/'}), getSlug({baseID: 'doc', source: '@site/docs/doc.md', sourceDirName: '/'}),
).toEqual('/doc'); ).toBe('/doc');
}); });
it('resolves absolute slug front matter', () => { it('resolves absolute slug front matter', () => {
@ -128,7 +128,7 @@ describe('getSlug', () => {
sourceDirName: '.', sourceDirName: '.',
frontMatterSlug: '/abc/def', frontMatterSlug: '/abc/def',
}), }),
).toEqual('/abc/def'); ).toBe('/abc/def');
expect( expect(
getSlug({ getSlug({
baseID: 'any', baseID: 'any',
@ -136,7 +136,7 @@ describe('getSlug', () => {
sourceDirName: './any', sourceDirName: './any',
frontMatterSlug: '/abc/def', frontMatterSlug: '/abc/def',
}), }),
).toEqual('/abc/def'); ).toBe('/abc/def');
expect( expect(
getSlug({ getSlug({
baseID: 'any', baseID: 'any',
@ -144,7 +144,7 @@ describe('getSlug', () => {
sourceDirName: './any/any', sourceDirName: './any/any',
frontMatterSlug: '/abc/def', frontMatterSlug: '/abc/def',
}), }),
).toEqual('/abc/def'); ).toBe('/abc/def');
}); });
it('resolves relative slug front matter', () => { it('resolves relative slug front matter', () => {
@ -155,7 +155,7 @@ describe('getSlug', () => {
sourceDirName: '.', sourceDirName: '.',
frontMatterSlug: 'abc/def', frontMatterSlug: 'abc/def',
}), }),
).toEqual('/abc/def'); ).toBe('/abc/def');
expect( expect(
getSlug({ getSlug({
baseID: 'any', baseID: 'any',
@ -163,7 +163,7 @@ describe('getSlug', () => {
sourceDirName: '/dir', sourceDirName: '/dir',
frontMatterSlug: 'abc/def', frontMatterSlug: 'abc/def',
}), }),
).toEqual('/dir/abc/def'); ).toBe('/dir/abc/def');
expect( expect(
getSlug({ getSlug({
baseID: 'any', baseID: 'any',
@ -171,7 +171,7 @@ describe('getSlug', () => {
sourceDirName: 'unslashedDir', sourceDirName: 'unslashedDir',
frontMatterSlug: 'abc/def', frontMatterSlug: 'abc/def',
}), }),
).toEqual('/unslashedDir/abc/def'); ).toBe('/unslashedDir/abc/def');
expect( expect(
getSlug({ getSlug({
baseID: 'any', baseID: 'any',
@ -179,7 +179,7 @@ describe('getSlug', () => {
sourceDirName: 'dir/subdir', sourceDirName: 'dir/subdir',
frontMatterSlug: 'abc/def', frontMatterSlug: 'abc/def',
}), }),
).toEqual('/dir/subdir/abc/def'); ).toBe('/dir/subdir/abc/def');
expect( expect(
getSlug({ getSlug({
baseID: 'any', baseID: 'any',
@ -187,7 +187,7 @@ describe('getSlug', () => {
sourceDirName: '/dir', sourceDirName: '/dir',
frontMatterSlug: './abc/def', frontMatterSlug: './abc/def',
}), }),
).toEqual('/dir/abc/def'); ).toBe('/dir/abc/def');
expect( expect(
getSlug({ getSlug({
baseID: 'any', baseID: 'any',
@ -195,7 +195,7 @@ describe('getSlug', () => {
sourceDirName: '/dir', sourceDirName: '/dir',
frontMatterSlug: './abc/../def', frontMatterSlug: './abc/../def',
}), }),
).toEqual('/dir/def'); ).toBe('/dir/def');
expect( expect(
getSlug({ getSlug({
baseID: 'any', baseID: 'any',
@ -203,7 +203,7 @@ describe('getSlug', () => {
sourceDirName: '/dir/subdir', sourceDirName: '/dir/subdir',
frontMatterSlug: '../abc/def', frontMatterSlug: '../abc/def',
}), }),
).toEqual('/dir/abc/def'); ).toBe('/dir/abc/def');
expect( expect(
getSlug({ getSlug({
baseID: 'any', baseID: 'any',
@ -211,6 +211,6 @@ describe('getSlug', () => {
sourceDirName: '/dir/subdir', sourceDirName: '/dir/subdir',
frontMatterSlug: '../../../../../abc/../def', frontMatterSlug: '../../../../../abc/../def',
}), }),
).toEqual('/def'); ).toBe('/def');
}); });
}); });

View file

@ -32,8 +32,8 @@ describe('docsClientUtils', () => {
}, },
}; };
expect(getActivePlugin(data, '/')).toEqual(undefined); expect(getActivePlugin(data, '/')).toBeUndefined();
expect(getActivePlugin(data, '/xyz')).toEqual(undefined); expect(getActivePlugin(data, '/xyz')).toBeUndefined();
expect(() => expect(() =>
getActivePlugin(data, '/', {failfast: true}), getActivePlugin(data, '/', {failfast: true}),
@ -73,7 +73,7 @@ describe('docsClientUtils', () => {
versions: [], versions: [],
}, },
}; };
expect(getActivePlugin(onePluginAtRoot, '/android/foo').pluginId).toEqual( expect(getActivePlugin(onePluginAtRoot, '/android/foo').pluginId).toBe(
'pluginAndroidId', 'pluginAndroidId',
); );
const onePluginAtRootReversed = { const onePluginAtRootReversed = {
@ -88,7 +88,7 @@ describe('docsClientUtils', () => {
}; };
expect( expect(
getActivePlugin(onePluginAtRootReversed, '/android/foo').pluginId, getActivePlugin(onePluginAtRootReversed, '/android/foo').pluginId,
).toEqual('pluginAndroidId'); ).toBe('pluginAndroidId');
}); });
it('getLatestVersion', () => { it('getLatestVersion', () => {
@ -158,19 +158,19 @@ describe('docsClientUtils', () => {
], ],
}; };
expect(getActiveVersion(data, '/someUnknownPath')).toEqual(undefined); expect(getActiveVersion(data, '/someUnknownPath')).toBeUndefined();
expect(getActiveVersion(data, '/docs/next')?.name).toEqual('next'); expect(getActiveVersion(data, '/docs/next')?.name).toBe('next');
expect(getActiveVersion(data, '/docs/next/')?.name).toEqual('next'); expect(getActiveVersion(data, '/docs/next/')?.name).toBe('next');
expect(getActiveVersion(data, '/docs/next/someDoc')?.name).toEqual('next'); expect(getActiveVersion(data, '/docs/next/someDoc')?.name).toBe('next');
expect(getActiveVersion(data, '/docs')?.name).toEqual('version2'); expect(getActiveVersion(data, '/docs')?.name).toBe('version2');
expect(getActiveVersion(data, '/docs/')?.name).toEqual('version2'); expect(getActiveVersion(data, '/docs/')?.name).toBe('version2');
expect(getActiveVersion(data, '/docs/someDoc')?.name).toEqual('version2'); expect(getActiveVersion(data, '/docs/someDoc')?.name).toBe('version2');
expect(getActiveVersion(data, '/docs/version1')?.name).toEqual('version1'); expect(getActiveVersion(data, '/docs/version1')?.name).toBe('version1');
expect(getActiveVersion(data, '/docs/version1')?.name).toEqual('version1'); expect(getActiveVersion(data, '/docs/version1')?.name).toBe('version1');
expect(getActiveVersion(data, '/docs/version1/someDoc')?.name).toEqual( expect(getActiveVersion(data, '/docs/version1/someDoc')?.name).toBe(
'version1', 'version1',
); );
}); });

View file

@ -132,18 +132,18 @@ describe('createSidebarsUtils', () => {
} = createSidebarsUtils(sidebars); } = createSidebarsUtils(sidebars);
it('getFirstDocIdOfFirstSidebar', async () => { it('getFirstDocIdOfFirstSidebar', async () => {
expect(getFirstDocIdOfFirstSidebar()).toEqual('doc1'); expect(getFirstDocIdOfFirstSidebar()).toBe('doc1');
}); });
it('getSidebarNameByDocId', async () => { it('getSidebarNameByDocId', async () => {
expect(getSidebarNameByDocId('doc1')).toEqual('sidebar1'); expect(getSidebarNameByDocId('doc1')).toBe('sidebar1');
expect(getSidebarNameByDocId('doc2')).toEqual('sidebar1'); expect(getSidebarNameByDocId('doc2')).toBe('sidebar1');
expect(getSidebarNameByDocId('doc3')).toEqual('sidebar2'); expect(getSidebarNameByDocId('doc3')).toBe('sidebar2');
expect(getSidebarNameByDocId('doc4')).toEqual('sidebar2'); expect(getSidebarNameByDocId('doc4')).toBe('sidebar2');
expect(getSidebarNameByDocId('doc5')).toEqual('sidebar3'); expect(getSidebarNameByDocId('doc5')).toBe('sidebar3');
expect(getSidebarNameByDocId('doc6')).toEqual('sidebar3'); expect(getSidebarNameByDocId('doc6')).toBe('sidebar3');
expect(getSidebarNameByDocId('doc7')).toEqual('sidebar3'); expect(getSidebarNameByDocId('doc7')).toBe('sidebar3');
expect(getSidebarNameByDocId('unknown_id')).toEqual(undefined); expect(getSidebarNameByDocId('unknown_id')).toBeUndefined();
}); });
it('getDocNavigation', async () => { it('getDocNavigation', async () => {

View file

@ -31,7 +31,6 @@
"devDependencies": { "devDependencies": {
"@docusaurus/core": "2.0.0-beta.17", "@docusaurus/core": "2.0.0-beta.17",
"@docusaurus/types": "2.0.0-beta.17", "@docusaurus/types": "2.0.0-beta.17",
"@testing-library/react-hooks": "^7.0.2",
"fs-extra": "^10.0.1", "fs-extra": "^10.0.1",
"lodash": "^4.17.21" "lodash": "^4.17.21"
}, },

View file

@ -0,0 +1,40 @@
// Jest Snapshot v1, https://goo.gl/fbAQLP
exports[`useTreeifiedTOC treeifies TOC without filtering 1`] = `
Array [
Object {
"children": Array [
Object {
"children": Array [
Object {
"children": Array [
Object {
"children": Array [
Object {
"children": Array [],
"id": "foxtrot",
"level": 6,
"value": "Foxtrot",
},
],
"id": "echo",
"level": 5,
"value": "Echo",
},
],
"id": "delta",
"level": 4,
"value": "Delta",
},
],
"id": "charlie",
"level": 3,
"value": "Charlie",
},
],
"id": "bravo",
"level": 2,
"value": "Bravo",
},
]
`;

View file

@ -13,45 +13,45 @@ import {
describe('parseCodeBlockTitle', () => { describe('parseCodeBlockTitle', () => {
it('parses double quote delimited title', () => { it('parses double quote delimited title', () => {
expect(parseCodeBlockTitle(`title="index.js"`)).toEqual(`index.js`); expect(parseCodeBlockTitle(`title="index.js"`)).toBe(`index.js`);
}); });
it('parses single quote delimited title', () => { it('parses single quote delimited title', () => {
expect(parseCodeBlockTitle(`title='index.js'`)).toEqual(`index.js`); expect(parseCodeBlockTitle(`title='index.js'`)).toBe(`index.js`);
}); });
it('does not parse mismatched quote delimiters', () => { it('does not parse mismatched quote delimiters', () => {
expect(parseCodeBlockTitle(`title="index.js'`)).toEqual(``); expect(parseCodeBlockTitle(`title="index.js'`)).toBe(``);
}); });
it('parses undefined metastring', () => { it('parses undefined metastring', () => {
expect(parseCodeBlockTitle(undefined)).toEqual(``); expect(parseCodeBlockTitle(undefined)).toBe(``);
}); });
it('parses metastring with no title specified', () => { it('parses metastring with no title specified', () => {
expect(parseCodeBlockTitle(`{1,2-3}`)).toEqual(``); expect(parseCodeBlockTitle(`{1,2-3}`)).toBe(``);
}); });
it('parses with multiple metadata title first', () => { it('parses with multiple metadata title first', () => {
expect(parseCodeBlockTitle(`title="index.js" label="JavaScript"`)).toEqual( expect(parseCodeBlockTitle(`title="index.js" label="JavaScript"`)).toBe(
`index.js`, `index.js`,
); );
}); });
it('parses with multiple metadata title last', () => { it('parses with multiple metadata title last', () => {
expect(parseCodeBlockTitle(`label="JavaScript" title="index.js"`)).toEqual( expect(parseCodeBlockTitle(`label="JavaScript" title="index.js"`)).toBe(
`index.js`, `index.js`,
); );
}); });
it('parses double quotes when delimited by single quotes', () => { it('parses double quotes when delimited by single quotes', () => {
expect(parseCodeBlockTitle(`title='console.log("Hello, World!")'`)).toEqual( expect(parseCodeBlockTitle(`title='console.log("Hello, World!")'`)).toBe(
`console.log("Hello, World!")`, `console.log("Hello, World!")`,
); );
}); });
it('parses single quotes when delimited by double quotes', () => { it('parses single quotes when delimited by double quotes', () => {
expect(parseCodeBlockTitle(`title="console.log('Hello, World!')"`)).toEqual( expect(parseCodeBlockTitle(`title="console.log('Hello, World!')"`)).toBe(
`console.log('Hello, World!')`, `console.log('Hello, World!')`,
); );
}); });
@ -59,8 +59,8 @@ describe('parseCodeBlockTitle', () => {
describe('parseLanguage', () => { describe('parseLanguage', () => {
it('works', () => { it('works', () => {
expect(parseLanguage('language-foo xxx yyy')).toEqual('foo'); expect(parseLanguage('language-foo xxx yyy')).toBe('foo');
expect(parseLanguage('xxxxx language-foo yyy')).toEqual('foo'); expect(parseLanguage('xxxxx language-foo yyy')).toBe('foo');
expect(parseLanguage('xx-language-foo yyyy')).toBeUndefined(); expect(parseLanguage('xx-language-foo yyyy')).toBeUndefined();
expect(parseLanguage('xxx yyy zzz')).toBeUndefined(); expect(parseLanguage('xxx yyy zzz')).toBeUndefined();
}); });

View file

@ -16,8 +16,11 @@ import {
useDocsSidebar, useDocsSidebar,
DocsSidebarProvider, DocsSidebarProvider,
findSidebarCategory, findSidebarCategory,
getBreadcrumbs, useCurrentSidebarCategory,
useSidebarBreadcrumbs,
} from '../docsUtils'; } from '../docsUtils';
import {StaticRouter} from 'react-router-dom';
import {Context} from '@docusaurus/docusaurusContext';
import type { import type {
PropSidebar, PropSidebar,
PropSidebarItem, PropSidebarItem,
@ -123,7 +126,7 @@ describe('useDocById', () => {
}, },
}); });
function callHook(docId: string | undefined) { function mockUseDocById(docId: string | undefined) {
const {result} = renderHook(() => useDocById(docId), { const {result} = renderHook(() => useDocById(docId), {
wrapper: ({children}) => ( wrapper: ({children}) => (
<DocsVersionProvider version={version}>{children}</DocsVersionProvider> <DocsVersionProvider version={version}>{children}</DocsVersionProvider>
@ -133,25 +136,25 @@ describe('useDocById', () => {
} }
it('accepts undefined', () => { it('accepts undefined', () => {
expect(callHook(undefined)).toBeUndefined(); expect(mockUseDocById(undefined)).toBeUndefined();
}); });
it('finds doc1', () => { it('finds doc1', () => {
expect(callHook('doc1')).toMatchObject({id: 'doc1'}); expect(mockUseDocById('doc1')).toMatchObject({id: 'doc1'});
}); });
it('finds doc2', () => { it('finds doc2', () => {
expect(callHook('doc2')).toMatchObject({id: 'doc2'}); expect(mockUseDocById('doc2')).toMatchObject({id: 'doc2'});
}); });
it('throws for doc3', () => { it('throws for doc3', () => {
expect(() => callHook('doc3')).toThrowErrorMatchingInlineSnapshot( expect(() => mockUseDocById('doc3')).toThrowErrorMatchingInlineSnapshot(
`"no version doc found by id=doc3"`, `"no version doc found by id=doc3"`,
); );
}); });
}); });
describe('findSidebarCategory', () => { describe('findSidebarCategory', () => {
it('os able to return undefined', () => { it('is able to return undefined', () => {
expect(findSidebarCategory([], () => false)).toBeUndefined(); expect(findSidebarCategory([], () => false)).toBeUndefined();
expect( expect(
findSidebarCategory([testCategory(), testCategory()], () => false), findSidebarCategory([testCategory(), testCategory()], () => false),
@ -207,7 +210,7 @@ describe('findFirstCategoryLink', () => {
href: undefined, href: undefined,
}), }),
), ),
).toEqual(undefined); ).toBeUndefined();
}); });
it('works with category with link', () => { it('works with category with link', () => {
@ -217,7 +220,7 @@ describe('findFirstCategoryLink', () => {
href: '/itemPath', href: '/itemPath',
}), }),
), ),
).toEqual('/itemPath'); ).toBe('/itemPath');
}); });
it('works with category with deeply nested category link', () => { it('works with category with deeply nested category link', () => {
@ -239,7 +242,7 @@ describe('findFirstCategoryLink', () => {
], ],
}), }),
), ),
).toEqual('/itemPath'); ).toBe('/itemPath');
}); });
it('works with category with deeply nested link', () => { it('works with category with deeply nested link', () => {
@ -255,7 +258,7 @@ describe('findFirstCategoryLink', () => {
], ],
}), }),
), ),
).toEqual('/itemPath'); ).toBe('/itemPath');
}); });
}); });
@ -267,15 +270,15 @@ describe('isActiveSidebarItem', () => {
label: 'Label', label: 'Label',
}; };
expect(isActiveSidebarItem(item, '/unexistingPath')).toEqual(false); expect(isActiveSidebarItem(item, '/unexistingPath')).toBe(false);
expect(isActiveSidebarItem(item, '/itemPath')).toEqual(true); expect(isActiveSidebarItem(item, '/itemPath')).toBe(true);
// Ensure it's not trailing slash sensitive: // Ensure it's not trailing slash sensitive:
expect(isActiveSidebarItem(item, '/itemPath/')).toEqual(true); expect(isActiveSidebarItem(item, '/itemPath/')).toBe(true);
expect( expect(
isActiveSidebarItem({...item, href: '/itemPath/'}, '/itemPath'), isActiveSidebarItem({...item, href: '/itemPath/'}, '/itemPath'),
).toEqual(true); ).toBe(true);
}); });
it('works with category href', () => { it('works with category href', () => {
@ -283,15 +286,15 @@ describe('isActiveSidebarItem', () => {
href: '/itemPath', href: '/itemPath',
}); });
expect(isActiveSidebarItem(item, '/unexistingPath')).toEqual(false); expect(isActiveSidebarItem(item, '/unexistingPath')).toBe(false);
expect(isActiveSidebarItem(item, '/itemPath')).toEqual(true); expect(isActiveSidebarItem(item, '/itemPath')).toBe(true);
// Ensure it's not trailing slash sensitive: // Ensure it's not trailing slash sensitive:
expect(isActiveSidebarItem(item, '/itemPath/')).toEqual(true); expect(isActiveSidebarItem(item, '/itemPath/')).toBe(true);
expect( expect(
isActiveSidebarItem({...item, href: '/itemPath/'}, '/itemPath'), isActiveSidebarItem({...item, href: '/itemPath/'}, '/itemPath'),
).toEqual(true); ).toBe(true);
}); });
it('works with category nested items', () => { it('works with category nested items', () => {
@ -316,63 +319,70 @@ describe('isActiveSidebarItem', () => {
], ],
}); });
expect(isActiveSidebarItem(item, '/unexistingPath')).toEqual(false); expect(isActiveSidebarItem(item, '/unexistingPath')).toBe(false);
expect(isActiveSidebarItem(item, '/category-path')).toEqual(true); expect(isActiveSidebarItem(item, '/category-path')).toBe(true);
expect(isActiveSidebarItem(item, '/sub-link-path')).toEqual(true); expect(isActiveSidebarItem(item, '/sub-link-path')).toBe(true);
expect(isActiveSidebarItem(item, '/sub-category-path')).toEqual(true); expect(isActiveSidebarItem(item, '/sub-category-path')).toBe(true);
expect(isActiveSidebarItem(item, '/sub-sub-link-path')).toEqual(true); expect(isActiveSidebarItem(item, '/sub-sub-link-path')).toBe(true);
// Ensure it's not trailing slash sensitive: // Ensure it's not trailing slash sensitive:
expect(isActiveSidebarItem(item, '/category-path/')).toEqual(true); expect(isActiveSidebarItem(item, '/category-path/')).toBe(true);
expect(isActiveSidebarItem(item, '/sub-link-path/')).toEqual(true); expect(isActiveSidebarItem(item, '/sub-link-path/')).toBe(true);
expect(isActiveSidebarItem(item, '/sub-category-path/')).toEqual(true); expect(isActiveSidebarItem(item, '/sub-category-path/')).toBe(true);
expect(isActiveSidebarItem(item, '/sub-sub-link-path/')).toEqual(true); expect(isActiveSidebarItem(item, '/sub-sub-link-path/')).toBe(true);
}); });
}); });
describe('getBreadcrumbs', () => { describe('useSidebarBreadcrumbs', () => {
const createUseSidebarBreadcrumbsMock =
(sidebar: PropSidebar, breadcrumbsOption?: boolean) => (location: string) =>
renderHook(() => useSidebarBreadcrumbs(), {
wrapper: ({children}) => (
<StaticRouter location={location}>
<Context.Provider
// eslint-disable-next-line react/jsx-no-constructed-context-values
value={{
globalData: {
'docusaurus-plugin-content-docs': {
default: {path: '/', breadcrumbs: breadcrumbsOption},
},
},
}}>
<DocsSidebarProvider sidebar={sidebar}>
{children}
</DocsSidebarProvider>
</Context.Provider>
</StaticRouter>
),
}).result.current;
it('returns empty for empty sidebar', () => { it('returns empty for empty sidebar', () => {
expect( expect(createUseSidebarBreadcrumbsMock([])('/doesNotExist')).toEqual([]);
getBreadcrumbs({
sidebar: [],
pathname: '/doesNotExist',
}),
).toEqual([]);
}); });
it('returns empty for sidebar but unknown pathname', () => { it('returns empty for sidebar but unknown pathname', () => {
const sidebar = [testCategory(), testLink()]; const sidebar = [testCategory(), testLink()];
expect( expect(createUseSidebarBreadcrumbsMock(sidebar)('/doesNotExist')).toEqual(
getBreadcrumbs({ [],
sidebar, );
pathname: '/doesNotExist',
}),
).toEqual([]);
}); });
it('returns first level category', () => { it('returns first level category', () => {
const pathname = '/somePathName'; const pathname = '/somePathName';
const sidebar = [testCategory({href: pathname}), testLink()]; const sidebar = [testCategory({href: pathname}), testLink()];
expect( expect(createUseSidebarBreadcrumbsMock(sidebar)(pathname)).toEqual([
getBreadcrumbs({ sidebar[0],
sidebar, ]);
pathname,
}),
).toEqual([sidebar[0]]);
}); });
it('returns first level link', () => { it('returns first level link', () => {
const pathname = '/somePathName'; const pathname = '/somePathName';
const sidebar = [testCategory(), testLink({href: pathname})]; const sidebar = [testCategory(), testLink({href: pathname})];
expect( expect(createUseSidebarBreadcrumbsMock(sidebar)(pathname)).toEqual([
getBreadcrumbs({ sidebar[1],
sidebar, ]);
pathname,
}),
).toEqual([sidebar[1]]);
}); });
it('returns nested category', () => { it('returns nested category', () => {
@ -403,12 +413,11 @@ describe('getBreadcrumbs', () => {
testCategory(), testCategory(),
]; ];
expect( expect(createUseSidebarBreadcrumbsMock(sidebar)(pathname)).toEqual([
getBreadcrumbs({ categoryLevel1,
sidebar, categoryLevel2,
pathname, categoryLevel3,
}), ]);
).toEqual([categoryLevel1, categoryLevel2, categoryLevel3]);
}); });
it('returns nested link', () => { it('returns nested link', () => {
@ -441,11 +450,75 @@ describe('getBreadcrumbs', () => {
testCategory(), testCategory(),
]; ];
expect( expect(createUseSidebarBreadcrumbsMock(sidebar)(pathname)).toEqual([
getBreadcrumbs({ categoryLevel1,
sidebar, categoryLevel2,
pathname, categoryLevel3,
}), link,
).toEqual([categoryLevel1, categoryLevel2, categoryLevel3, link]); ]);
});
it('returns null when breadcrumbs disabled', () => {
expect(createUseSidebarBreadcrumbsMock([], false)('/foo')).toBeNull();
});
it('returns null when there is no sidebar', () => {
expect(createUseSidebarBreadcrumbsMock(null, false)('/foo')).toBeNull();
});
});
describe('useCurrentSidebarCategory', () => {
const createUseCurrentSidebarCategoryMock =
(sidebar?: PropSidebar) => (location: string) =>
renderHook(() => useCurrentSidebarCategory(), {
wrapper: ({children}) => (
<DocsSidebarProvider sidebar={sidebar}>
<StaticRouter location={location}>{children}</StaticRouter>
</DocsSidebarProvider>
),
}).result.current;
it('works', () => {
const category = {
type: 'category',
href: '/cat',
items: [
{type: 'link', href: '/cat/foo', label: 'Foo'},
{type: 'link', href: '/cat/bar', label: 'Bar'},
{type: 'link', href: '/baz', label: 'Baz'},
],
};
const mockUseCurrentSidebarCategory = createUseCurrentSidebarCategoryMock([
{type: 'link', href: '/cat/fake', label: 'Fake'},
category,
]);
expect(mockUseCurrentSidebarCategory('/cat')).toEqual(category);
});
it('throws for non-category index page', () => {
const category = {
type: 'category',
items: [
{type: 'link', href: '/cat/foo', label: 'Foo'},
{type: 'link', href: '/cat/bar', label: 'Bar'},
{type: 'link', href: '/baz', label: 'Baz'},
],
};
const mockUseCurrentSidebarCategory = createUseCurrentSidebarCategoryMock([
category,
]);
expect(() => mockUseCurrentSidebarCategory('/cat'))
.toThrowErrorMatchingInlineSnapshot(`
"Unexpected: sidebar category could not be found for pathname='/cat'.
Hook useCurrentSidebarCategory() should only be used on Category pages"
`);
});
it('throws when sidebar is missing', () => {
const mockUseCurrentSidebarCategory = createUseCurrentSidebarCategoryMock();
expect(() =>
mockUseCurrentSidebarCategory('/cat'),
).toThrowErrorMatchingInlineSnapshot(
`"Unexpected: cant find current sidebar in context"`,
);
}); });
}); });

View file

@ -0,0 +1,37 @@
/**
* Copyright (c) Facebook, Inc. and its affiliates.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/
import {isMultiColumnFooterLinks} from '../footerUtils';
describe('isMultiColumnFooterLinks', () => {
it('works', () => {
expect(
isMultiColumnFooterLinks([
{
title: 'section',
items: [
{href: '/foo', label: 'Foo'},
{href: '/bar', label: 'Bar'},
],
},
{
title: 'section2',
items: [
{href: '/foo', label: 'Foo2'},
{href: '/bar', label: 'Bar2'},
],
},
]),
).toBe(true);
expect(
isMultiColumnFooterLinks([
{href: '/foo', label: 'Foo'},
{href: '/bar', label: 'Bar'},
]),
).toBe(false);
});
});

View file

@ -0,0 +1,33 @@
/**
* Copyright (c) Facebook, Inc. and its affiliates.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/
import React from 'react';
import {useTitleFormatter} from '../generalUtils';
import {renderHook} from '@testing-library/react-hooks';
import {Context} from '@docusaurus/docusaurusContext';
import type {DocusaurusContext} from '@docusaurus/types';
describe('useTitleFormatter', () => {
const createUseTitleFormatterMock =
(context: DocusaurusContext) => (title?: string) =>
renderHook(() => useTitleFormatter(title), {
wrapper: ({children}) => (
<Context.Provider value={context}>{children}</Context.Provider>
),
}).result.current;
it('works', () => {
const mockUseTitleFormatter = createUseTitleFormatterMock({
siteConfig: {
title: 'my site',
titleDelimiter: '·',
},
});
expect(mockUseTitleFormatter('a page')).toBe('a page · my site');
expect(mockUseTitleFormatter(undefined)).toBe('my site');
expect(mockUseTitleFormatter(' ')).toBe('my site');
});
});

View file

@ -9,13 +9,13 @@ import {isRegexpStringMatch} from '../regexpUtils';
describe('isRegexpStringMatch', () => { describe('isRegexpStringMatch', () => {
it('works', () => { it('works', () => {
expect(isRegexpStringMatch(undefined, 'foo')).toEqual(false); expect(isRegexpStringMatch(undefined, 'foo')).toBe(false);
expect(isRegexpStringMatch('bar', undefined)).toEqual(false); expect(isRegexpStringMatch('bar', undefined)).toBe(false);
expect(isRegexpStringMatch('foo', 'bar')).toEqual(false); expect(isRegexpStringMatch('foo', 'bar')).toBe(false);
expect(isRegexpStringMatch('foo', 'foo')).toEqual(true); expect(isRegexpStringMatch('foo', 'foo')).toBe(true);
expect(isRegexpStringMatch('fooooooooooo', 'foo')).toEqual(false); expect(isRegexpStringMatch('fooooooooooo', 'foo')).toBe(false);
expect(isRegexpStringMatch('foo', 'fooooooo')).toEqual(true); expect(isRegexpStringMatch('foo', 'fooooooo')).toBe(true);
expect(isRegexpStringMatch('f.*o', 'fggo')).toEqual(true); expect(isRegexpStringMatch('f.*o', 'fggo')).toBe(true);
expect(isRegexpStringMatch('FOO', 'foo')).toEqual(true); expect(isRegexpStringMatch('FOO', 'foo')).toBe(true);
}); });
}); });

View file

@ -5,7 +5,7 @@
* LICENSE file in the root directory of this source tree. * LICENSE file in the root directory of this source tree.
*/ */
import {type Route} from '@generated/routes'; import type {Route} from '@docusaurus/types';
import {findHomePageRoute} from '../routesUtils'; import {findHomePageRoute} from '../routesUtils';
describe('findHomePageRoute', () => { describe('findHomePageRoute', () => {
@ -15,7 +15,7 @@ describe('findHomePageRoute', () => {
}; };
it('returns undefined for no routes', () => { it('returns undefined for no routes', () => {
expect(findHomePageRoute({baseUrl: '/', routes: []})).toEqual(undefined); expect(findHomePageRoute({baseUrl: '/', routes: []})).toBeUndefined();
}); });
it('returns undefined for no homepage', () => { it('returns undefined for no homepage', () => {
@ -37,7 +37,7 @@ describe('findHomePageRoute', () => {
}, },
], ],
}), }),
).toEqual(undefined); ).toBeUndefined();
}); });
it('finds top-level homepage', () => { it('finds top-level homepage', () => {

View file

@ -9,6 +9,6 @@ import {docVersionSearchTag} from '../searchUtils';
describe('docVersionSearchTag', () => { describe('docVersionSearchTag', () => {
it('works', () => { it('works', () => {
expect(docVersionSearchTag('foo', 'bar')).toEqual('docs-foo-bar'); expect(docVersionSearchTag('foo', 'bar')).toBe('docs-foo-bar');
}); });
}); });

View file

@ -7,16 +7,9 @@
import type {TOCItem} from '@docusaurus/types'; import type {TOCItem} from '@docusaurus/types';
import {renderHook} from '@testing-library/react-hooks'; import {renderHook} from '@testing-library/react-hooks';
import {useFilteredAndTreeifiedTOC} from '../tocUtils'; import {useFilteredAndTreeifiedTOC, useTreeifiedTOC} from '../tocUtils';
describe('useFilteredAndTreeifiedTOC', () => { const mockTOC: TOCItem[] = [
it('filters a toc with all heading levels', () => {
const toc: TOCItem[] = [
{
id: 'alpha',
level: 1,
value: 'alpha',
},
{ {
id: 'bravo', id: 'bravo',
level: 2, level: 2,
@ -42,12 +35,22 @@ describe('useFilteredAndTreeifiedTOC', () => {
level: 6, level: 6,
value: 'Foxtrot', value: 'Foxtrot',
}, },
]; ];
describe('useTreeifiedTOC', () => {
it('treeifies TOC without filtering', () => {
expect(
renderHook(() => useTreeifiedTOC(mockTOC)).result.current,
).toMatchSnapshot();
});
});
describe('useFilteredAndTreeifiedTOC', () => {
it('filters a toc with all heading levels', () => {
expect( expect(
renderHook(() => renderHook(() =>
useFilteredAndTreeifiedTOC({ useFilteredAndTreeifiedTOC({
toc, toc: mockTOC,
minHeadingLevel: 2, minHeadingLevel: 2,
maxHeadingLevel: 2, maxHeadingLevel: 2,
}), }),
@ -64,7 +67,7 @@ describe('useFilteredAndTreeifiedTOC', () => {
expect( expect(
renderHook(() => renderHook(() =>
useFilteredAndTreeifiedTOC({ useFilteredAndTreeifiedTOC({
toc, toc: mockTOC,
minHeadingLevel: 3, minHeadingLevel: 3,
maxHeadingLevel: 3, maxHeadingLevel: 3,
}), }),
@ -81,7 +84,7 @@ describe('useFilteredAndTreeifiedTOC', () => {
expect( expect(
renderHook(() => renderHook(() =>
useFilteredAndTreeifiedTOC({ useFilteredAndTreeifiedTOC({
toc, toc: mockTOC,
minHeadingLevel: 2, minHeadingLevel: 2,
maxHeadingLevel: 3, maxHeadingLevel: 3,
}), }),
@ -105,7 +108,7 @@ describe('useFilteredAndTreeifiedTOC', () => {
expect( expect(
renderHook(() => renderHook(() =>
useFilteredAndTreeifiedTOC({ useFilteredAndTreeifiedTOC({
toc, toc: mockTOC,
minHeadingLevel: 2, minHeadingLevel: 2,
maxHeadingLevel: 4, maxHeadingLevel: 4,
}), }),

View file

@ -0,0 +1,124 @@
/**
* Copyright (c) Facebook, Inc. and its affiliates.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/
import React from 'react';
import {useAlternatePageUtils} from '../useAlternatePageUtils';
import {renderHook} from '@testing-library/react-hooks';
import {StaticRouter} from 'react-router-dom';
import {Context} from '@docusaurus/docusaurusContext';
import type {DocusaurusContext} from '@docusaurus/types';
describe('useAlternatePageUtils', () => {
const createUseAlternatePageUtilsMock =
(context: DocusaurusContext) => (location: string) =>
renderHook(() => useAlternatePageUtils(), {
wrapper: ({children}) => (
<Context.Provider value={context}>
<StaticRouter location={location}>{children}</StaticRouter>
</Context.Provider>
),
}).result.current;
it('works for baseUrl: / and currentLocale = defaultLocale', () => {
const mockUseAlternatePageUtils = createUseAlternatePageUtilsMock({
siteConfig: {baseUrl: '/', url: 'https://example.com'},
i18n: {defaultLocale: 'en', currentLocale: 'en'},
});
expect(
mockUseAlternatePageUtils('/').createUrl({
locale: 'zh-Hans',
fullyQualified: false,
}),
).toBe('/zh-Hans/');
expect(
mockUseAlternatePageUtils('/foo').createUrl({
locale: 'zh-Hans',
fullyQualified: false,
}),
).toBe('/zh-Hans/foo');
expect(
mockUseAlternatePageUtils('/foo').createUrl({
locale: 'zh-Hans',
fullyQualified: true,
}),
).toBe('https://example.com/zh-Hans/foo');
});
it('works for baseUrl: / and currentLocale /= defaultLocale', () => {
const mockUseAlternatePageUtils = createUseAlternatePageUtilsMock({
siteConfig: {baseUrl: '/zh-Hans/', url: 'https://example.com'},
i18n: {defaultLocale: 'en', currentLocale: 'zh-Hans'},
});
expect(
mockUseAlternatePageUtils('/zh-Hans/').createUrl({
locale: 'en',
fullyQualified: false,
}),
).toBe('/');
expect(
mockUseAlternatePageUtils('/zh-Hans/foo').createUrl({
locale: 'en',
fullyQualified: false,
}),
).toBe('/foo');
expect(
mockUseAlternatePageUtils('/zh-Hans/foo').createUrl({
locale: 'en',
fullyQualified: true,
}),
).toBe('https://example.com/foo');
});
it('works for non-root base URL and currentLocale = defaultLocale', () => {
const mockUseAlternatePageUtils = createUseAlternatePageUtilsMock({
siteConfig: {baseUrl: '/base/', url: 'https://example.com'},
i18n: {defaultLocale: 'en', currentLocale: 'en'},
});
expect(
mockUseAlternatePageUtils('/base/').createUrl({
locale: 'zh-Hans',
fullyQualified: false,
}),
).toBe('/base/zh-Hans/');
expect(
mockUseAlternatePageUtils('/base/foo').createUrl({
locale: 'zh-Hans',
fullyQualified: false,
}),
).toBe('/base/zh-Hans/foo');
expect(
mockUseAlternatePageUtils('/base/foo').createUrl({
locale: 'zh-Hans',
fullyQualified: true,
}),
).toBe('https://example.com/base/zh-Hans/foo');
});
it('works for non-root base URL and currentLocale /= defaultLocale', () => {
const mockUseAlternatePageUtils = createUseAlternatePageUtilsMock({
siteConfig: {baseUrl: '/base/zh-Hans/', url: 'https://example.com'},
i18n: {defaultLocale: 'en', currentLocale: 'zh-Hans'},
});
expect(
mockUseAlternatePageUtils('/base/zh-Hans/').createUrl({
locale: 'en',
fullyQualified: false,
}),
).toBe('/base/');
expect(
mockUseAlternatePageUtils('/base/zh-Hans/foo').createUrl({
locale: 'en',
fullyQualified: false,
}),
).toBe('/base/foo');
expect(
mockUseAlternatePageUtils('/base/zh-Hans/foo').createUrl({
locale: 'en',
fullyQualified: true,
}),
).toBe('https://example.com/base/foo');
});
});

View file

@ -0,0 +1,38 @@
/**
* Copyright (c) Facebook, Inc. and its affiliates.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/
import React from 'react';
import {useLocalPathname} from '../useLocalPathname';
import {renderHook} from '@testing-library/react-hooks';
import {StaticRouter} from 'react-router-dom';
import {Context} from '@docusaurus/docusaurusContext';
import type {DocusaurusContext} from '@docusaurus/types';
describe('useLocalPathname', () => {
const createUseLocalPathnameMock =
(context: DocusaurusContext) => (location: string) =>
renderHook(() => useLocalPathname(), {
wrapper: ({children}) => (
<Context.Provider value={context}>
<StaticRouter location={location}>{children}</StaticRouter>
</Context.Provider>
),
}).result.current;
it('works for baseUrl: /', () => {
const mockUseLocalPathname = createUseLocalPathnameMock({
siteConfig: {baseUrl: '/'},
});
expect(mockUseLocalPathname('/foo')).toBe('/foo');
});
it('works for non-root baseUrl', () => {
const mockUseLocalPathname = createUseLocalPathnameMock({
siteConfig: {baseUrl: '/base/'},
});
expect(mockUseLocalPathname('/base/foo')).toBe('/foo');
});
});

View file

@ -0,0 +1,79 @@
/**
* Copyright (c) Facebook, Inc. and its affiliates.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/
import {jest} from '@jest/globals';
import React from 'react';
import {usePluralForm} from '../usePluralForm';
import {renderHook} from '@testing-library/react-hooks';
import {Context} from '@docusaurus/docusaurusContext';
import type {DocusaurusContext} from '@docusaurus/types';
describe('usePluralForm', () => {
const createUsePluralFormMock = (context: DocusaurusContext) => () =>
renderHook(() => usePluralForm(), {
wrapper: ({children}) => (
<Context.Provider value={context}>{children}</Context.Provider>
),
}).result.current;
it('returns the right plural', () => {
const mockUsePluralForm = createUsePluralFormMock({
i18n: {
currentLocale: 'en',
},
});
expect(mockUsePluralForm().selectMessage(1, 'one|many')).toBe('one');
expect(mockUsePluralForm().selectMessage(10, 'one|many')).toBe('many');
});
it('warns against too many plurals', () => {
const mockUsePluralForm = createUsePluralFormMock({
i18n: {
currentLocale: 'zh-Hans',
},
});
const consoleMock = jest
.spyOn(console, 'error')
.mockImplementation(() => {});
expect(mockUsePluralForm().selectMessage(1, 'one|many')).toBe('one');
expect(mockUsePluralForm().selectMessage(10, 'one|many')).toBe('one');
expect(consoleMock.mock.calls[0][0]).toMatchInlineSnapshot(
`"For locale=zh-Hans, a maximum of 1 plural forms are expected (other), but the message contains 2: one|many"`,
);
});
it('uses the last with not enough plurals', () => {
const mockUsePluralForm = createUsePluralFormMock({
i18n: {
currentLocale: 'en',
},
});
expect(mockUsePluralForm().selectMessage(10, 'many')).toBe('many');
});
it('falls back when Intl.PluralForms is not available', () => {
const mockUsePluralForm = createUsePluralFormMock({
i18n: {
currentLocale: 'zh-Hans',
},
});
const consoleMock = jest
.spyOn(console, 'error')
.mockImplementation(() => {});
const pluralMock = jest
.spyOn(Intl, 'PluralRules')
.mockImplementation(() => undefined);
expect(mockUsePluralForm().selectMessage(1, 'one|many')).toBe('one');
expect(mockUsePluralForm().selectMessage(10, 'one|many')).toBe('many');
expect(consoleMock.mock.calls[0][0]).toMatchInlineSnapshot(`
"Failed to use Intl.PluralRules for locale \\"zh-Hans\\".
Docusaurus will fallback to the default (English) implementation.
Error: pluralRules.resolvedOptions is not a function
"
`);
pluralMock.mockRestore();
});
});

View file

@ -187,7 +187,7 @@ export function isActiveSidebarItem(
return false; return false;
} }
export function getBreadcrumbs({ function getBreadcrumbs({
sidebar, sidebar,
pathname, pathname,
}: { }: {

View file

@ -7,10 +7,10 @@
import useDocusaurusContext from '@docusaurus/useDocusaurusContext'; import useDocusaurusContext from '@docusaurus/useDocusaurusContext';
export const useTitleFormatter = (title?: string | undefined): string => { export function useTitleFormatter(title?: string | undefined): string {
const {siteConfig} = useDocusaurusContext(); const {siteConfig} = useDocusaurusContext();
const {title: siteTitle, titleDelimiter} = siteConfig; const {title: siteTitle, titleDelimiter} = siteConfig;
return title && title.trim().length return title && title.trim().length
? `${title.trim()} ${titleDelimiter} ${siteTitle}` ? `${title.trim()} ${titleDelimiter} ${siteTitle}`
: siteTitle; : siteTitle;
}; }

View file

@ -5,9 +5,10 @@
* LICENSE file in the root directory of this source tree. * LICENSE file in the root directory of this source tree.
*/ */
import GeneratedRoutes, {type Route} from '@generated/routes'; import generatedRoutes from '@generated/routes';
import {useMemo} from 'react'; import {useMemo} from 'react';
import useDocusaurusContext from '@docusaurus/useDocusaurusContext'; import useDocusaurusContext from '@docusaurus/useDocusaurusContext';
import type {Route} from '@docusaurus/types';
// Note that all sites don't always have a homepage in practice // Note that all sites don't always have a homepage in practice
// See https://github.com/facebook/docusaurus/pull/6517#issuecomment-1048709116 // See https://github.com/facebook/docusaurus/pull/6517#issuecomment-1048709116
@ -48,7 +49,7 @@ export function useHomePageRoute(): Route | undefined {
return useMemo( return useMemo(
() => () =>
findHomePageRoute({ findHomePageRoute({
routes: GeneratedRoutes, routes: generatedRoutes,
baseUrl, baseUrl,
}), }),
[baseUrl], [baseUrl],

View file

@ -70,23 +70,15 @@ function useLocalePluralForms(): LocalePluralForms {
i18n: {currentLocale}, i18n: {currentLocale},
} = useDocusaurusContext(); } = useDocusaurusContext();
return useMemo(() => { return useMemo(() => {
// @ts-expect-error checking Intl.PluralRules in case browser doesn't
// have it (e.g Safari 12-)
if (Intl.PluralRules) {
try { try {
return createLocalePluralForms(currentLocale); return createLocalePluralForms(currentLocale);
} catch { } catch (err) {
console.error(`Failed to use Intl.PluralRules for locale "${currentLocale}". console.error(`Failed to use Intl.PluralRules for locale "${currentLocale}".
Docusaurus will fallback to a default/fallback (English) Intl.PluralRules implementation. Docusaurus will fallback to the default (English) implementation.
Error: ${(err as Error).message}
`); `);
return EnglishPluralForms; return EnglishPluralForms;
} }
} else {
console.error(`Intl.PluralRules not available!
Docusaurus will fallback to a default/fallback (English) Intl.PluralRules implementation.
`);
return EnglishPluralForms;
}
}, [currentLocale]); }, [currentLocale]);
} }
@ -103,7 +95,7 @@ function selectPluralMessage(
} }
if (parts.length > localePluralForms.pluralForms.length) { if (parts.length > localePluralForms.pluralForms.length) {
console.error( console.error(
`For locale=${localePluralForms.locale}, a maximum of ${localePluralForms.pluralForms.length} plural forms are expected (${localePluralForms.pluralForms}), but the message contains ${parts.length} plural forms: ${pluralMessages} `, `For locale=${localePluralForms.locale}, a maximum of ${localePluralForms.pluralForms.length} plural forms are expected (${localePluralForms.pluralForms}), but the message contains ${parts.length}: ${pluralMessages}`,
); );
} }
const pluralForm = localePluralForms.select(count); const pluralForm = localePluralForms.select(count);

View file

@ -372,6 +372,14 @@ export interface RouteConfig {
[propName: string]: unknown; [propName: string]: unknown;
} }
export type Route = {
readonly path: string;
// eslint-disable-next-line @typescript-eslint/no-explicit-any
readonly component: any;
readonly exact?: boolean;
readonly routes?: Route[];
};
// Aliases used for Webpack resolution (when using docusaurus swizzle) // Aliases used for Webpack resolution (when using docusaurus swizzle)
export interface ThemeAliases { export interface ThemeAliases {
[alias: string]: string; [alias: string]: string;

View file

@ -18,161 +18,161 @@ function params(
describe('applyTrailingSlash', () => { describe('applyTrailingSlash', () => {
it('applies to empty', () => { it('applies to empty', () => {
expect(applyTrailingSlash('', params(true))).toEqual('/'); expect(applyTrailingSlash('', params(true))).toBe('/');
expect(applyTrailingSlash('', params(false))).toEqual(''); expect(applyTrailingSlash('', params(false))).toBe('');
expect(applyTrailingSlash('', params(undefined))).toEqual(''); expect(applyTrailingSlash('', params(undefined))).toBe('');
}); });
it('does not apply to /', () => { it('does not apply to /', () => {
expect(applyTrailingSlash('/', params(true))).toEqual('/'); expect(applyTrailingSlash('/', params(true))).toBe('/');
expect(applyTrailingSlash('/', params(false))).toEqual('/'); expect(applyTrailingSlash('/', params(false))).toBe('/');
expect(applyTrailingSlash('/', params(undefined))).toEqual('/'); expect(applyTrailingSlash('/', params(undefined))).toBe('/');
expect(applyTrailingSlash('/?query#anchor', params(true))).toEqual( expect(applyTrailingSlash('/?query#anchor', params(true))).toBe(
'/?query#anchor', '/?query#anchor',
); );
expect(applyTrailingSlash('/?query#anchor', params(false))).toEqual( expect(applyTrailingSlash('/?query#anchor', params(false))).toBe(
'/?query#anchor', '/?query#anchor',
); );
expect(applyTrailingSlash('/?query#anchor', params(undefined))).toEqual( expect(applyTrailingSlash('/?query#anchor', params(undefined))).toBe(
'/?query#anchor', '/?query#anchor',
); );
}); });
it('does not apply to /baseUrl/', () => { it('does not apply to /baseUrl/', () => {
const baseUrl = '/baseUrl/'; const baseUrl = '/baseUrl/';
expect(applyTrailingSlash('/baseUrl/', params(true, baseUrl))).toEqual( expect(applyTrailingSlash('/baseUrl/', params(true, baseUrl))).toBe(
'/baseUrl/', '/baseUrl/',
); );
expect(applyTrailingSlash('/baseUrl/', params(false, baseUrl))).toEqual( expect(applyTrailingSlash('/baseUrl/', params(false, baseUrl))).toBe(
'/baseUrl/', '/baseUrl/',
); );
expect(applyTrailingSlash('/baseUrl/', params(undefined, baseUrl))).toEqual( expect(applyTrailingSlash('/baseUrl/', params(undefined, baseUrl))).toBe(
'/baseUrl/', '/baseUrl/',
); );
expect( expect(
applyTrailingSlash('/baseUrl/?query#anchor', params(true, baseUrl)), applyTrailingSlash('/baseUrl/?query#anchor', params(true, baseUrl)),
).toEqual('/baseUrl/?query#anchor'); ).toBe('/baseUrl/?query#anchor');
expect( expect(
applyTrailingSlash('/baseUrl/?query#anchor', params(false, baseUrl)), applyTrailingSlash('/baseUrl/?query#anchor', params(false, baseUrl)),
).toEqual('/baseUrl/?query#anchor'); ).toBe('/baseUrl/?query#anchor');
expect( expect(
applyTrailingSlash('/baseUrl/?query#anchor', params(undefined, baseUrl)), applyTrailingSlash('/baseUrl/?query#anchor', params(undefined, baseUrl)),
).toEqual('/baseUrl/?query#anchor'); ).toBe('/baseUrl/?query#anchor');
}); });
it('does not apply to #anchor links', () => { it('does not apply to #anchor links', () => {
expect(applyTrailingSlash('#', params(true))).toEqual('#'); expect(applyTrailingSlash('#', params(true))).toBe('#');
expect(applyTrailingSlash('#', params(false))).toEqual('#'); expect(applyTrailingSlash('#', params(false))).toBe('#');
expect(applyTrailingSlash('#', params(undefined))).toEqual('#'); expect(applyTrailingSlash('#', params(undefined))).toBe('#');
expect(applyTrailingSlash('#anchor', params(true))).toEqual('#anchor'); expect(applyTrailingSlash('#anchor', params(true))).toBe('#anchor');
expect(applyTrailingSlash('#anchor', params(false))).toEqual('#anchor'); expect(applyTrailingSlash('#anchor', params(false))).toBe('#anchor');
expect(applyTrailingSlash('#anchor', params(undefined))).toEqual('#anchor'); expect(applyTrailingSlash('#anchor', params(undefined))).toBe('#anchor');
}); });
it('applies to simple paths', () => { it('applies to simple paths', () => {
expect(applyTrailingSlash('abc', params(true))).toEqual('abc/'); expect(applyTrailingSlash('abc', params(true))).toBe('abc/');
expect(applyTrailingSlash('abc', params(false))).toEqual('abc'); expect(applyTrailingSlash('abc', params(false))).toBe('abc');
expect(applyTrailingSlash('abc', params(undefined))).toEqual('abc'); expect(applyTrailingSlash('abc', params(undefined))).toBe('abc');
expect(applyTrailingSlash('abc/', params(true))).toEqual('abc/'); expect(applyTrailingSlash('abc/', params(true))).toBe('abc/');
expect(applyTrailingSlash('abc/', params(false))).toEqual('abc'); expect(applyTrailingSlash('abc/', params(false))).toBe('abc');
expect(applyTrailingSlash('abc/', params(undefined))).toEqual('abc/'); expect(applyTrailingSlash('abc/', params(undefined))).toBe('abc/');
expect(applyTrailingSlash('/abc', params(true))).toEqual('/abc/'); expect(applyTrailingSlash('/abc', params(true))).toBe('/abc/');
expect(applyTrailingSlash('/abc', params(false))).toEqual('/abc'); expect(applyTrailingSlash('/abc', params(false))).toBe('/abc');
expect(applyTrailingSlash('/abc', params(undefined))).toEqual('/abc'); expect(applyTrailingSlash('/abc', params(undefined))).toBe('/abc');
expect(applyTrailingSlash('/abc/', params(true))).toEqual('/abc/'); expect(applyTrailingSlash('/abc/', params(true))).toBe('/abc/');
expect(applyTrailingSlash('/abc/', params(false))).toEqual('/abc'); expect(applyTrailingSlash('/abc/', params(false))).toBe('/abc');
expect(applyTrailingSlash('/abc/', params(undefined))).toEqual('/abc/'); expect(applyTrailingSlash('/abc/', params(undefined))).toBe('/abc/');
}); });
it('applies to path with #anchor', () => { it('applies to path with #anchor', () => {
expect(applyTrailingSlash('/abc#anchor', params(true))).toEqual( expect(applyTrailingSlash('/abc#anchor', params(true))).toBe(
'/abc/#anchor', '/abc/#anchor',
); );
expect(applyTrailingSlash('/abc#anchor', params(false))).toEqual( expect(applyTrailingSlash('/abc#anchor', params(false))).toBe(
'/abc#anchor', '/abc#anchor',
); );
expect(applyTrailingSlash('/abc#anchor', params(undefined))).toEqual( expect(applyTrailingSlash('/abc#anchor', params(undefined))).toBe(
'/abc#anchor', '/abc#anchor',
); );
expect(applyTrailingSlash('/abc/#anchor', params(true))).toEqual( expect(applyTrailingSlash('/abc/#anchor', params(true))).toBe(
'/abc/#anchor', '/abc/#anchor',
); );
expect(applyTrailingSlash('/abc/#anchor', params(false))).toEqual( expect(applyTrailingSlash('/abc/#anchor', params(false))).toBe(
'/abc#anchor', '/abc#anchor',
); );
expect(applyTrailingSlash('/abc/#anchor', params(undefined))).toEqual( expect(applyTrailingSlash('/abc/#anchor', params(undefined))).toBe(
'/abc/#anchor', '/abc/#anchor',
); );
}); });
it('applies to path with ?search', () => { it('applies to path with ?search', () => {
expect(applyTrailingSlash('/abc?search', params(true))).toEqual( expect(applyTrailingSlash('/abc?search', params(true))).toBe(
'/abc/?search', '/abc/?search',
); );
expect(applyTrailingSlash('/abc?search', params(false))).toEqual( expect(applyTrailingSlash('/abc?search', params(false))).toBe(
'/abc?search', '/abc?search',
); );
expect(applyTrailingSlash('/abc?search', params(undefined))).toEqual( expect(applyTrailingSlash('/abc?search', params(undefined))).toBe(
'/abc?search', '/abc?search',
); );
expect(applyTrailingSlash('/abc/?search', params(true))).toEqual( expect(applyTrailingSlash('/abc/?search', params(true))).toBe(
'/abc/?search', '/abc/?search',
); );
expect(applyTrailingSlash('/abc/?search', params(false))).toEqual( expect(applyTrailingSlash('/abc/?search', params(false))).toBe(
'/abc?search', '/abc?search',
); );
expect(applyTrailingSlash('/abc/?search', params(undefined))).toEqual( expect(applyTrailingSlash('/abc/?search', params(undefined))).toBe(
'/abc/?search', '/abc/?search',
); );
}); });
it('applies to path with ?search#anchor', () => { it('applies to path with ?search#anchor', () => {
expect(applyTrailingSlash('/abc?search#anchor', params(true))).toEqual( expect(applyTrailingSlash('/abc?search#anchor', params(true))).toBe(
'/abc/?search#anchor', '/abc/?search#anchor',
); );
expect(applyTrailingSlash('/abc?search#anchor', params(false))).toEqual( expect(applyTrailingSlash('/abc?search#anchor', params(false))).toBe(
'/abc?search#anchor', '/abc?search#anchor',
); );
expect(applyTrailingSlash('/abc?search#anchor', params(undefined))).toEqual( expect(applyTrailingSlash('/abc?search#anchor', params(undefined))).toBe(
'/abc?search#anchor', '/abc?search#anchor',
); );
expect(applyTrailingSlash('/abc/?search#anchor', params(true))).toEqual( expect(applyTrailingSlash('/abc/?search#anchor', params(true))).toBe(
'/abc/?search#anchor', '/abc/?search#anchor',
); );
expect(applyTrailingSlash('/abc/?search#anchor', params(false))).toEqual( expect(applyTrailingSlash('/abc/?search#anchor', params(false))).toBe(
'/abc?search#anchor', '/abc?search#anchor',
); );
expect( expect(applyTrailingSlash('/abc/?search#anchor', params(undefined))).toBe(
applyTrailingSlash('/abc/?search#anchor', params(undefined)), '/abc/?search#anchor',
).toEqual('/abc/?search#anchor'); );
}); });
it('applies to fully qualified urls', () => { it('applies to fully qualified urls', () => {
expect( expect(
applyTrailingSlash('https://xyz.com/abc?search#anchor', params(true)), applyTrailingSlash('https://xyz.com/abc?search#anchor', params(true)),
).toEqual('https://xyz.com/abc/?search#anchor'); ).toBe('https://xyz.com/abc/?search#anchor');
expect( expect(
applyTrailingSlash('https://xyz.com/abc?search#anchor', params(false)), applyTrailingSlash('https://xyz.com/abc?search#anchor', params(false)),
).toEqual('https://xyz.com/abc?search#anchor'); ).toBe('https://xyz.com/abc?search#anchor');
expect( expect(
applyTrailingSlash( applyTrailingSlash(
'https://xyz.com/abc?search#anchor', 'https://xyz.com/abc?search#anchor',
params(undefined), params(undefined),
), ),
).toEqual('https://xyz.com/abc?search#anchor'); ).toBe('https://xyz.com/abc?search#anchor');
expect( expect(
applyTrailingSlash('https://xyz.com/abc/?search#anchor', params(true)), applyTrailingSlash('https://xyz.com/abc/?search#anchor', params(true)),
).toEqual('https://xyz.com/abc/?search#anchor'); ).toBe('https://xyz.com/abc/?search#anchor');
expect( expect(
applyTrailingSlash('https://xyz.com/abc/?search#anchor', params(false)), applyTrailingSlash('https://xyz.com/abc/?search#anchor', params(false)),
).toEqual('https://xyz.com/abc?search#anchor'); ).toBe('https://xyz.com/abc?search#anchor');
expect( expect(
applyTrailingSlash( applyTrailingSlash(
'https://xyz.com/abc/?search#anchor', 'https://xyz.com/abc/?search#anchor',
params(undefined), params(undefined),
), ),
).toEqual('https://xyz.com/abc/?search#anchor'); ).toBe('https://xyz.com/abc/?search#anchor');
}); });
}); });

View file

@ -67,28 +67,28 @@ describe('readOutputHTMLFile', () => {
path.join(__dirname, '__fixtures__/build-snap'), path.join(__dirname, '__fixtures__/build-snap'),
undefined, undefined,
).then(String), ).then(String),
).resolves.toEqual('file\n'); ).resolves.toBe('file\n');
await expect( await expect(
readOutputHTMLFile( readOutputHTMLFile(
'/folder', '/folder',
path.join(__dirname, '__fixtures__/build-snap'), path.join(__dirname, '__fixtures__/build-snap'),
undefined, undefined,
).then(String), ).then(String),
).resolves.toEqual('folder\n'); ).resolves.toBe('folder\n');
await expect( await expect(
readOutputHTMLFile( readOutputHTMLFile(
'/file/', '/file/',
path.join(__dirname, '__fixtures__/build-snap'), path.join(__dirname, '__fixtures__/build-snap'),
undefined, undefined,
).then(String), ).then(String),
).resolves.toEqual('file\n'); ).resolves.toBe('file\n');
await expect( await expect(
readOutputHTMLFile( readOutputHTMLFile(
'/folder/', '/folder/',
path.join(__dirname, '__fixtures__/build-snap'), path.join(__dirname, '__fixtures__/build-snap'),
undefined, undefined,
).then(String), ).then(String),
).resolves.toEqual('folder\n'); ).resolves.toBe('folder\n');
}); });
it('trailing slash true', async () => { it('trailing slash true', async () => {
await expect( await expect(
@ -97,14 +97,14 @@ describe('readOutputHTMLFile', () => {
path.join(__dirname, '__fixtures__/build-snap'), path.join(__dirname, '__fixtures__/build-snap'),
true, true,
).then(String), ).then(String),
).resolves.toEqual('folder\n'); ).resolves.toBe('folder\n');
await expect( await expect(
readOutputHTMLFile( readOutputHTMLFile(
'/folder/', '/folder/',
path.join(__dirname, '__fixtures__/build-snap'), path.join(__dirname, '__fixtures__/build-snap'),
true, true,
).then(String), ).then(String),
).resolves.toEqual('folder\n'); ).resolves.toBe('folder\n');
}); });
it('trailing slash false', async () => { it('trailing slash false', async () => {
await expect( await expect(
@ -113,14 +113,14 @@ describe('readOutputHTMLFile', () => {
path.join(__dirname, '__fixtures__/build-snap'), path.join(__dirname, '__fixtures__/build-snap'),
false, false,
).then(String), ).then(String),
).resolves.toEqual('file\n'); ).resolves.toBe('file\n');
await expect( await expect(
readOutputHTMLFile( readOutputHTMLFile(
'/file/', '/file/',
path.join(__dirname, '__fixtures__/build-snap'), path.join(__dirname, '__fixtures__/build-snap'),
false, false,
).then(String), ).then(String),
).resolves.toEqual('file\n'); ).resolves.toBe('file\n');
}); });
}); });

View file

@ -15,53 +15,53 @@ describe('createMatcher', () => {
const matcher = createMatcher(GlobExcludeDefault); const matcher = createMatcher(GlobExcludeDefault);
it('match default exclude MD/MDX partials correctly', () => { it('match default exclude MD/MDX partials correctly', () => {
expect(matcher('doc.md')).toEqual(false); expect(matcher('doc.md')).toBe(false);
expect(matcher('category/doc.md')).toEqual(false); expect(matcher('category/doc.md')).toBe(false);
expect(matcher('category/subcategory/doc.md')).toEqual(false); expect(matcher('category/subcategory/doc.md')).toBe(false);
// //
expect(matcher('doc.mdx')).toEqual(false); expect(matcher('doc.mdx')).toBe(false);
expect(matcher('category/doc.mdx')).toEqual(false); expect(matcher('category/doc.mdx')).toBe(false);
expect(matcher('category/subcategory/doc.mdx')).toEqual(false); expect(matcher('category/subcategory/doc.mdx')).toBe(false);
// //
expect(matcher('_doc.md')).toEqual(true); expect(matcher('_doc.md')).toBe(true);
expect(matcher('category/_doc.md')).toEqual(true); expect(matcher('category/_doc.md')).toBe(true);
expect(matcher('category/subcategory/_doc.md')).toEqual(true); expect(matcher('category/subcategory/_doc.md')).toBe(true);
expect(matcher('_category/doc.md')).toEqual(true); expect(matcher('_category/doc.md')).toBe(true);
expect(matcher('_category/subcategory/doc.md')).toEqual(true); expect(matcher('_category/subcategory/doc.md')).toBe(true);
expect(matcher('category/_subcategory/doc.md')).toEqual(true); expect(matcher('category/_subcategory/doc.md')).toBe(true);
}); });
it('match default exclude tests correctly', () => { it('match default exclude tests correctly', () => {
expect(matcher('xyz.js')).toEqual(false); expect(matcher('xyz.js')).toBe(false);
expect(matcher('xyz.ts')).toEqual(false); expect(matcher('xyz.ts')).toBe(false);
expect(matcher('xyz.jsx')).toEqual(false); expect(matcher('xyz.jsx')).toBe(false);
expect(matcher('xyz.tsx')).toEqual(false); expect(matcher('xyz.tsx')).toBe(false);
expect(matcher('folder/xyz.js')).toEqual(false); expect(matcher('folder/xyz.js')).toBe(false);
expect(matcher('folder/xyz.ts')).toEqual(false); expect(matcher('folder/xyz.ts')).toBe(false);
expect(matcher('folder/xyz.jsx')).toEqual(false); expect(matcher('folder/xyz.jsx')).toBe(false);
expect(matcher('folder/xyz.tsx')).toEqual(false); expect(matcher('folder/xyz.tsx')).toBe(false);
// //
expect(matcher('xyz.test.js')).toEqual(true); expect(matcher('xyz.test.js')).toBe(true);
expect(matcher('xyz.test.ts')).toEqual(true); expect(matcher('xyz.test.ts')).toBe(true);
expect(matcher('xyz.test.jsx')).toEqual(true); expect(matcher('xyz.test.jsx')).toBe(true);
expect(matcher('xyz.test.tsx')).toEqual(true); expect(matcher('xyz.test.tsx')).toBe(true);
expect(matcher('folder/xyz.test.js')).toEqual(true); expect(matcher('folder/xyz.test.js')).toBe(true);
expect(matcher('folder/xyz.test.ts')).toEqual(true); expect(matcher('folder/xyz.test.ts')).toBe(true);
expect(matcher('folder/xyz.test.jsx')).toEqual(true); expect(matcher('folder/xyz.test.jsx')).toBe(true);
expect(matcher('folder/xyz.test.tsx')).toEqual(true); expect(matcher('folder/xyz.test.tsx')).toBe(true);
expect(matcher('folder/subfolder/xyz.test.js')).toEqual(true); expect(matcher('folder/subfolder/xyz.test.js')).toBe(true);
expect(matcher('folder/subfolder/xyz.test.ts')).toEqual(true); expect(matcher('folder/subfolder/xyz.test.ts')).toBe(true);
expect(matcher('folder/subfolder/xyz.test.jsx')).toEqual(true); expect(matcher('folder/subfolder/xyz.test.jsx')).toBe(true);
expect(matcher('folder/subfolder/xyz.test.tsx')).toEqual(true); expect(matcher('folder/subfolder/xyz.test.tsx')).toBe(true);
// //
expect(matcher('__tests__/subfolder/xyz.js')).toEqual(true); expect(matcher('__tests__/subfolder/xyz.js')).toBe(true);
expect(matcher('__tests__/subfolder/xyz.ts')).toEqual(true); expect(matcher('__tests__/subfolder/xyz.ts')).toBe(true);
expect(matcher('__tests__/subfolder/xyz.jsx')).toEqual(true); expect(matcher('__tests__/subfolder/xyz.jsx')).toBe(true);
expect(matcher('__tests__/subfolder/xyz.tsx')).toEqual(true); expect(matcher('__tests__/subfolder/xyz.tsx')).toBe(true);
expect(matcher('folder/__tests__/xyz.js')).toEqual(true); expect(matcher('folder/__tests__/xyz.js')).toBe(true);
expect(matcher('folder/__tests__/xyz.ts')).toEqual(true); expect(matcher('folder/__tests__/xyz.ts')).toBe(true);
expect(matcher('folder/__tests__/xyz.jsx')).toEqual(true); expect(matcher('folder/__tests__/xyz.jsx')).toBe(true);
expect(matcher('folder/__tests__/xyz.tsx')).toEqual(true); expect(matcher('folder/__tests__/xyz.tsx')).toBe(true);
}); });
}); });
@ -74,29 +74,29 @@ describe('createAbsoluteFilePathMatcher', () => {
); );
it('match default exclude MD/MDX partials correctly', () => { it('match default exclude MD/MDX partials correctly', () => {
expect(matcher('/_root/docs/myDoc.md')).toEqual(false); expect(matcher('/_root/docs/myDoc.md')).toBe(false);
expect(matcher('/_root/docs/myDoc.mdx')).toEqual(false); expect(matcher('/_root/docs/myDoc.mdx')).toBe(false);
expect(matcher('/root/_docs/myDoc.md')).toEqual(false); expect(matcher('/root/_docs/myDoc.md')).toBe(false);
expect(matcher('/root/_docs/myDoc.mdx')).toEqual(false); expect(matcher('/root/_docs/myDoc.mdx')).toBe(false);
expect(matcher('/_root/docs/category/myDoc.md')).toEqual(false); expect(matcher('/_root/docs/category/myDoc.md')).toBe(false);
expect(matcher('/_root/docs/category/myDoc.mdx')).toEqual(false); expect(matcher('/_root/docs/category/myDoc.mdx')).toBe(false);
expect(matcher('/root/_docs/category/myDoc.md')).toEqual(false); expect(matcher('/root/_docs/category/myDoc.md')).toBe(false);
expect(matcher('/root/_docs/category/myDoc.mdx')).toEqual(false); expect(matcher('/root/_docs/category/myDoc.mdx')).toBe(false);
// //
expect(matcher('/_root/docs/_myDoc.md')).toEqual(true); expect(matcher('/_root/docs/_myDoc.md')).toBe(true);
expect(matcher('/_root/docs/_myDoc.mdx')).toEqual(true); expect(matcher('/_root/docs/_myDoc.mdx')).toBe(true);
expect(matcher('/root/_docs/_myDoc.md')).toEqual(true); expect(matcher('/root/_docs/_myDoc.md')).toBe(true);
expect(matcher('/root/_docs/_myDoc.mdx')).toEqual(true); expect(matcher('/root/_docs/_myDoc.mdx')).toBe(true);
expect(matcher('/_root/docs/_category/myDoc.md')).toEqual(true); expect(matcher('/_root/docs/_category/myDoc.md')).toBe(true);
expect(matcher('/_root/docs/_category/myDoc.mdx')).toEqual(true); expect(matcher('/_root/docs/_category/myDoc.mdx')).toBe(true);
expect(matcher('/root/_docs/_category/myDoc.md')).toEqual(true); expect(matcher('/root/_docs/_category/myDoc.md')).toBe(true);
expect(matcher('/root/_docs/_category/myDoc.mdx')).toEqual(true); expect(matcher('/root/_docs/_category/myDoc.mdx')).toBe(true);
}); });
it('match default exclude tests correctly', () => { it('match default exclude tests correctly', () => {
expect(matcher('/__test__/website/src/xyz.js')).toEqual(false); expect(matcher('/__test__/website/src/xyz.js')).toBe(false);
expect(matcher('/__test__/website/src/__test__/xyz.js')).toEqual(true); expect(matcher('/__test__/website/src/__test__/xyz.js')).toBe(true);
expect(matcher('/__test__/website/src/xyz.test.js')).toEqual(true); expect(matcher('/__test__/website/src/xyz.test.js')).toBe(true);
}); });
it('throw if file is not contained in any root doc', () => { it('throw if file is not contained in any root doc', () => {

View file

@ -18,23 +18,23 @@ import _ from 'lodash';
describe('removeSuffix', () => { describe('removeSuffix', () => {
it("is no-op when suffix doesn't exist", () => { it("is no-op when suffix doesn't exist", () => {
expect(removeSuffix('abcdef', 'ijk')).toEqual('abcdef'); expect(removeSuffix('abcdef', 'ijk')).toBe('abcdef');
expect(removeSuffix('abcdef', 'abc')).toEqual('abcdef'); expect(removeSuffix('abcdef', 'abc')).toBe('abcdef');
expect(removeSuffix('abcdef', '')).toEqual('abcdef'); expect(removeSuffix('abcdef', '')).toBe('abcdef');
}); });
it('removes suffix', () => { it('removes suffix', () => {
expect(removeSuffix('abcdef', 'ef')).toEqual('abcd'); expect(removeSuffix('abcdef', 'ef')).toBe('abcd');
}); });
}); });
describe('removePrefix', () => { describe('removePrefix', () => {
it("is no-op when prefix doesn't exist", () => { it("is no-op when prefix doesn't exist", () => {
expect(removePrefix('abcdef', 'ijk')).toEqual('abcdef'); expect(removePrefix('abcdef', 'ijk')).toBe('abcdef');
expect(removePrefix('abcdef', 'def')).toEqual('abcdef'); expect(removePrefix('abcdef', 'def')).toBe('abcdef');
expect(removePrefix('abcdef', '')).toEqual('abcdef'); expect(removePrefix('abcdef', '')).toBe('abcdef');
}); });
it('removes prefix', () => { it('removes prefix', () => {
expect(removePrefix('abcdef', 'ab')).toEqual('cdef'); expect(removePrefix('abcdef', 'ab')).toBe('cdef');
}); });
}); });
@ -133,7 +133,7 @@ describe('findAsyncSequential', () => {
}); });
const timeBefore = Date.now(); const timeBefore = Date.now();
await expect(findAsyncSequential(items, findFn)).resolves.toEqual('2'); await expect(findAsyncSequential(items, findFn)).resolves.toBe('2');
const timeAfter = Date.now(); const timeAfter = Date.now();
expect(findFn).toHaveBeenCalledTimes(2); expect(findFn).toHaveBeenCalledTimes(2);

View file

@ -21,7 +21,7 @@ describe('createExcerpt', () => {
Nunc porttitor libero nec vulputate venenatis. Nam nec rhoncus mauris. Morbi tempus est et nibh maximus, tempus venenatis arcu lobortis. Nunc porttitor libero nec vulputate venenatis. Nam nec rhoncus mauris. Morbi tempus est et nibh maximus, tempus venenatis arcu lobortis.
`), `),
).toEqual( ).toBe(
'Lorem ipsum dolor sit amet, consectetur adipiscing elit. Vestibulum ex urna, molestie et sagittis ut, varius ac justo.', 'Lorem ipsum dolor sit amet, consectetur adipiscing elit. Vestibulum ex urna, molestie et sagittis ut, varius ac justo.',
); );
}); });
@ -36,7 +36,7 @@ describe('createExcerpt', () => {
Nunc porttitor libero nec vulputate venenatis. Nam nec rhoncus mauris. Morbi tempus est et nibh maximus, tempus venenatis arcu lobortis. Nunc porttitor libero nec vulputate venenatis. Nam nec rhoncus mauris. Morbi tempus est et nibh maximus, tempus venenatis arcu lobortis.
`), `),
).toEqual( ).toBe(
// h1 title is skipped on purpose, because we don't want the page to have // h1 title is skipped on purpose, because we don't want the page to have
// SEO metadata title === description // SEO metadata title === description
'Lorem ipsum dolor sit amet, consectetur adipiscing elit. Vestibulum ex urna, molestie et sagittis ut, varius ac justo.', 'Lorem ipsum dolor sit amet, consectetur adipiscing elit. Vestibulum ex urna, molestie et sagittis ut, varius ac justo.',
@ -54,7 +54,7 @@ describe('createExcerpt', () => {
Nunc porttitor libero nec vulputate venenatis. Nam nec rhoncus mauris. Morbi tempus est et nibh maximus, tempus venenatis arcu lobortis. Nunc porttitor libero nec vulputate venenatis. Nam nec rhoncus mauris. Morbi tempus est et nibh maximus, tempus venenatis arcu lobortis.
`), `),
).toEqual( ).toBe(
// h1 title is skipped on purpose, because we don't want the page to have // h1 title is skipped on purpose, because we don't want the page to have
// SEO metadata title === description // SEO metadata title === description
'Lorem ipsum dolor sit amet, consectetur adipiscing elit. Vestibulum ex urna, molestie et sagittis ut, varius ac justo.', 'Lorem ipsum dolor sit amet, consectetur adipiscing elit. Vestibulum ex urna, molestie et sagittis ut, varius ac justo.',
@ -68,7 +68,7 @@ describe('createExcerpt', () => {
Nunc porttitor libero nec vulputate venenatis. Nam nec rhoncus mauris. Morbi tempus est et nibh maximus, tempus venenatis arcu lobortis. Nunc porttitor libero nec vulputate venenatis. Nam nec rhoncus mauris. Morbi tempus est et nibh maximus, tempus venenatis arcu lobortis.
`), `),
).toEqual('Lorem ipsum dolor sit amet'); ).toBe('Lorem ipsum dolor sit amet');
}); });
it('creates excerpt for content beginning with blockquote', () => { it('creates excerpt for content beginning with blockquote', () => {
@ -78,7 +78,7 @@ describe('createExcerpt', () => {
Nunc porttitor libero nec vulputate venenatis. Nam nec rhoncus mauris. Morbi tempus est et nibh maximus, tempus venenatis arcu lobortis. Nunc porttitor libero nec vulputate venenatis. Nam nec rhoncus mauris. Morbi tempus est et nibh maximus, tempus venenatis arcu lobortis.
`), `),
).toEqual('Lorem ipsum dolor sit amet'); ).toBe('Lorem ipsum dolor sit amet');
}); });
it('creates excerpt for content beginning with image (eg. blog post)', () => { it('creates excerpt for content beginning with image (eg. blog post)', () => {
@ -86,7 +86,7 @@ describe('createExcerpt', () => {
createExcerpt(dedent` createExcerpt(dedent`
![Lorem ipsum](/img/lorem-ipsum.svg) ![Lorem ipsum](/img/lorem-ipsum.svg)
`), `),
).toEqual('Lorem ipsum'); ).toBe('Lorem ipsum');
}); });
it('creates excerpt for content beginning with admonitions', () => { it('creates excerpt for content beginning with admonitions', () => {
@ -102,7 +102,7 @@ describe('createExcerpt', () => {
Nunc porttitor libero nec vulputate venenatis. Nam nec rhoncus mauris. Morbi tempus est et nibh maximus, tempus venenatis arcu lobortis. Nunc porttitor libero nec vulputate venenatis. Nam nec rhoncus mauris. Morbi tempus est et nibh maximus, tempus venenatis arcu lobortis.
`), `),
).toEqual('Lorem ipsum dolor sit amet, consectetur adipiscing elit.'); ).toBe('Lorem ipsum dolor sit amet, consectetur adipiscing elit.');
}); });
it('creates excerpt for content with imports/exports declarations and Markdown markup, as well as Emoji', () => { it('creates excerpt for content with imports/exports declarations and Markdown markup, as well as Emoji', () => {
@ -120,7 +120,7 @@ describe('createExcerpt', () => {
Nunc porttitor libero nec vulputate venenatis. Nam nec rhoncus mauris. Morbi tempus est et nibh maximus, tempus venenatis arcu lobortis. Nunc porttitor libero nec vulputate venenatis. Nam nec rhoncus mauris. Morbi tempus est et nibh maximus, tempus venenatis arcu lobortis.
`), `),
).toEqual( ).toBe(
'Lorem ipsum dolor sit amet, consectetur adipiscing elit. Vestibulum ex urna, molestie et sagittis ut, varius ac justo.', 'Lorem ipsum dolor sit amet, consectetur adipiscing elit. Vestibulum ex urna, molestie et sagittis ut, varius ac justo.',
); );
}); });
@ -130,7 +130,7 @@ describe('createExcerpt', () => {
createExcerpt(dedent` createExcerpt(dedent`
## Markdown title {#my-anchor-id} ## Markdown title {#my-anchor-id}
`), `),
).toEqual('Markdown title'); ).toBe('Markdown title');
}); });
it('creates excerpt for content with various code blocks', () => { it('creates excerpt for content with various code blocks', () => {
@ -143,7 +143,7 @@ describe('createExcerpt', () => {
Lorem \`ipsum\` dolor sit amet, consectetur \`adipiscing elit\`. Lorem \`ipsum\` dolor sit amet, consectetur \`adipiscing elit\`.
`), `),
).toEqual('Lorem ipsum dolor sit amet, consectetur adipiscing elit.'); ).toBe('Lorem ipsum dolor sit amet, consectetur adipiscing elit.');
}); });
}); });

View file

@ -123,9 +123,9 @@ describe('toMessageRelativeFilePath', () => {
jest jest
.spyOn(process, 'cwd') .spyOn(process, 'cwd')
.mockImplementationOnce(() => path.join(__dirname, '..')); .mockImplementationOnce(() => path.join(__dirname, '..'));
expect( expect(toMessageRelativeFilePath(path.join(__dirname, 'foo/bar.js'))).toBe(
toMessageRelativeFilePath(path.join(__dirname, 'foo/bar.js')), '__tests__/foo/bar.js',
).toEqual('__tests__/foo/bar.js'); );
}); });
}); });

View file

@ -10,18 +10,18 @@ import {createSlugger} from '../slugger';
describe('createSlugger', () => { describe('createSlugger', () => {
it('can create unique slugs', () => { it('can create unique slugs', () => {
const slugger = createSlugger(); const slugger = createSlugger();
expect(slugger.slug('Some$/vaLue$!^')).toEqual('somevalue'); expect(slugger.slug('Some$/vaLue$!^')).toBe('somevalue');
expect(slugger.slug('Some$/vaLue$!^')).toEqual('somevalue-1'); expect(slugger.slug('Some$/vaLue$!^')).toBe('somevalue-1');
expect(slugger.slug('Some$/vaLue$!^')).toEqual('somevalue-2'); expect(slugger.slug('Some$/vaLue$!^')).toBe('somevalue-2');
expect(slugger.slug('Some$/vaLue$!^-1')).toEqual('somevalue-1-1'); expect(slugger.slug('Some$/vaLue$!^-1')).toBe('somevalue-1-1');
}); });
it('can create unique slugs respecting case', () => { it('can create unique slugs respecting case', () => {
const slugger = createSlugger(); const slugger = createSlugger();
const opt = {maintainCase: true}; const opt = {maintainCase: true};
expect(slugger.slug('Some$/vaLue$!^', opt)).toEqual('SomevaLue'); expect(slugger.slug('Some$/vaLue$!^', opt)).toBe('SomevaLue');
expect(slugger.slug('Some$/vaLue$!^', opt)).toEqual('SomevaLue-1'); expect(slugger.slug('Some$/vaLue$!^', opt)).toBe('SomevaLue-1');
expect(slugger.slug('Some$/vaLue$!^', opt)).toEqual('SomevaLue-2'); expect(slugger.slug('Some$/vaLue$!^', opt)).toBe('SomevaLue-2');
expect(slugger.slug('Some$/vaLue$!^-1', opt)).toEqual('SomevaLue-1-1'); expect(slugger.slug('Some$/vaLue$!^-1', opt)).toBe('SomevaLue-1-1');
}); });
}); });

View file

@ -146,15 +146,15 @@ describe('getEditUrl', () => {
it('returns right path', () => { it('returns right path', () => {
expect( expect(
getEditUrl('foo/bar.md', 'https://github.com/facebook/docusaurus'), getEditUrl('foo/bar.md', 'https://github.com/facebook/docusaurus'),
).toEqual('https://github.com/facebook/docusaurus/foo/bar.md'); ).toBe('https://github.com/facebook/docusaurus/foo/bar.md');
expect( expect(
getEditUrl('foo/你好.md', 'https://github.com/facebook/docusaurus'), getEditUrl('foo/你好.md', 'https://github.com/facebook/docusaurus'),
).toEqual('https://github.com/facebook/docusaurus/foo/你好.md'); ).toBe('https://github.com/facebook/docusaurus/foo/你好.md');
}); });
it('always returns valid URL', () => { it('always returns valid URL', () => {
expect( expect(
getEditUrl('foo\\你好.md', 'https://github.com/facebook/docusaurus'), getEditUrl('foo\\你好.md', 'https://github.com/facebook/docusaurus'),
).toEqual('https://github.com/facebook/docusaurus/foo/你好.md'); ).toBe('https://github.com/facebook/docusaurus/foo/你好.md');
}); });
it('returns undefined for undefined', () => { it('returns undefined for undefined', () => {
expect(getEditUrl('foo/bar.md')).toBeUndefined(); expect(getEditUrl('foo/bar.md')).toBeUndefined();
@ -200,28 +200,28 @@ describe('isValidPathname', () => {
describe('addTrailingSlash', () => { describe('addTrailingSlash', () => {
it('is no-op for path with trailing slash', () => { it('is no-op for path with trailing slash', () => {
expect(addTrailingSlash('/abcd/')).toEqual('/abcd/'); expect(addTrailingSlash('/abcd/')).toBe('/abcd/');
}); });
it('adds / for path without trailing slash', () => { it('adds / for path without trailing slash', () => {
expect(addTrailingSlash('/abcd')).toEqual('/abcd/'); expect(addTrailingSlash('/abcd')).toBe('/abcd/');
}); });
}); });
describe('addLeadingSlash', () => { describe('addLeadingSlash', () => {
it('is no-op for path with leading slash', () => { it('is no-op for path with leading slash', () => {
expect(addLeadingSlash('/abc')).toEqual('/abc'); expect(addLeadingSlash('/abc')).toBe('/abc');
}); });
it('adds / for path without leading slash', () => { it('adds / for path without leading slash', () => {
expect(addLeadingSlash('abc')).toEqual('/abc'); expect(addLeadingSlash('abc')).toBe('/abc');
}); });
}); });
describe('removeTrailingSlash', () => { describe('removeTrailingSlash', () => {
it('is no-op for path without trailing slash', () => { it('is no-op for path without trailing slash', () => {
expect(removeTrailingSlash('/abcd')).toEqual('/abcd'); expect(removeTrailingSlash('/abcd')).toBe('/abcd');
}); });
it('removes / for path with trailing slash', () => { it('removes / for path with trailing slash', () => {
expect(removeTrailingSlash('/abcd/')).toEqual('/abcd'); expect(removeTrailingSlash('/abcd/')).toBe('/abcd');
}); });
}); });
@ -229,21 +229,21 @@ describe('resolvePathname', () => {
it('works', () => { it('works', () => {
// These tests are directly copied from https://github.com/mjackson/resolve-pathname/blob/master/modules/__tests__/resolvePathname-test.js // These tests are directly copied from https://github.com/mjackson/resolve-pathname/blob/master/modules/__tests__/resolvePathname-test.js
// Maybe we want to wrap that logic in the future? // Maybe we want to wrap that logic in the future?
expect(resolvePathname('c')).toEqual('c'); expect(resolvePathname('c')).toBe('c');
expect(resolvePathname('c', 'a/b')).toEqual('a/c'); expect(resolvePathname('c', 'a/b')).toBe('a/c');
expect(resolvePathname('/c', '/a/b')).toEqual('/c'); expect(resolvePathname('/c', '/a/b')).toBe('/c');
expect(resolvePathname('', '/a/b')).toEqual('/a/b'); expect(resolvePathname('', '/a/b')).toBe('/a/b');
expect(resolvePathname('../c', '/a/b')).toEqual('/c'); expect(resolvePathname('../c', '/a/b')).toBe('/c');
expect(resolvePathname('c', '/a/b')).toEqual('/a/c'); expect(resolvePathname('c', '/a/b')).toBe('/a/c');
expect(resolvePathname('c', '/a/')).toEqual('/a/c'); expect(resolvePathname('c', '/a/')).toBe('/a/c');
expect(resolvePathname('..', '/a/b')).toEqual('/'); expect(resolvePathname('..', '/a/b')).toBe('/');
}); });
}); });
describe('encodePath', () => { describe('encodePath', () => {
it('works', () => { it('works', () => {
expect(encodePath('a/foo/')).toEqual('a/foo/'); expect(encodePath('a/foo/')).toBe('a/foo/');
expect(encodePath('a/<foo>/')).toEqual('a/%3Cfoo%3E/'); expect(encodePath('a/<foo>/')).toBe('a/%3Cfoo%3E/');
expect(encodePath('a/你好/')).toEqual('a/%E4%BD%A0%E5%A5%BD/'); expect(encodePath('a/你好/')).toBe('a/%E4%BD%A0%E5%A5%BD/');
}); });
}); });

View file

@ -9,15 +9,15 @@ import {translate} from '../Translate';
describe('translate', () => { describe('translate', () => {
it('accept id and use it as fallback', () => { it('accept id and use it as fallback', () => {
expect(translate({id: 'some-id'})).toEqual('some-id'); expect(translate({id: 'some-id'})).toBe('some-id');
}); });
it('accept message and use it as fallback', () => { it('accept message and use it as fallback', () => {
expect(translate({message: 'some-message'})).toEqual('some-message'); expect(translate({message: 'some-message'})).toBe('some-message');
}); });
it('accept id+message and use message as fallback', () => { it('accept id+message and use message as fallback', () => {
expect(translate({id: 'some-id', message: 'some-message'})).toEqual( expect(translate({id: 'some-id', message: 'some-message'})).toBe(
'some-message', 'some-message',
); );
}); });

View file

@ -1,140 +0,0 @@
/**
* Copyright (c) Facebook, Inc. and its affiliates.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/
import {jest} from '@jest/globals';
import useBaseUrl, {useBaseUrlUtils} from '../useBaseUrl';
import useDocusaurusContext from '../useDocusaurusContext';
jest.mock('../useDocusaurusContext');
const mockedContext = useDocusaurusContext as jest.Mock;
const forcePrepend = {forcePrependBaseUrl: true};
describe('useBaseUrl', () => {
it('empty base URL', () => {
mockedContext.mockImplementation(() => ({
siteConfig: {
baseUrl: '/',
url: 'https://docusaurus.io',
},
}));
expect(useBaseUrl('hello')).toEqual('/hello');
expect(useBaseUrl('/hello')).toEqual('/hello');
expect(useBaseUrl('hello/')).toEqual('/hello/');
expect(useBaseUrl('/hello/')).toEqual('/hello/');
expect(useBaseUrl('hello/byebye')).toEqual('/hello/byebye');
expect(useBaseUrl('/hello/byebye')).toEqual('/hello/byebye');
expect(useBaseUrl('hello/byebye/')).toEqual('/hello/byebye/');
expect(useBaseUrl('/hello/byebye/')).toEqual('/hello/byebye/');
expect(useBaseUrl('https://github.com')).toEqual('https://github.com');
expect(useBaseUrl('//reactjs.org')).toEqual('//reactjs.org');
expect(useBaseUrl('//reactjs.org', forcePrepend)).toEqual('//reactjs.org');
expect(useBaseUrl('https://site.com', forcePrepend)).toEqual(
'https://site.com',
);
expect(useBaseUrl('/hello/byebye', {absolute: true})).toEqual(
'https://docusaurus.io/hello/byebye',
);
expect(useBaseUrl('#hello')).toEqual('#hello');
});
it('non-empty base URL', () => {
mockedContext.mockImplementation(() => ({
siteConfig: {
baseUrl: '/docusaurus/',
url: 'https://docusaurus.io',
},
}));
expect(useBaseUrl('')).toEqual('');
expect(useBaseUrl('hello')).toEqual('/docusaurus/hello');
expect(useBaseUrl('/hello')).toEqual('/docusaurus/hello');
expect(useBaseUrl('hello/')).toEqual('/docusaurus/hello/');
expect(useBaseUrl('/hello/')).toEqual('/docusaurus/hello/');
expect(useBaseUrl('hello/byebye')).toEqual('/docusaurus/hello/byebye');
expect(useBaseUrl('/hello/byebye')).toEqual('/docusaurus/hello/byebye');
expect(useBaseUrl('hello/byebye/')).toEqual('/docusaurus/hello/byebye/');
expect(useBaseUrl('/hello/byebye/')).toEqual('/docusaurus/hello/byebye/');
expect(useBaseUrl('https://github.com')).toEqual('https://github.com');
expect(useBaseUrl('//reactjs.org')).toEqual('//reactjs.org');
expect(useBaseUrl('//reactjs.org', forcePrepend)).toEqual('//reactjs.org');
expect(useBaseUrl('/hello', forcePrepend)).toEqual('/docusaurus/hello');
expect(useBaseUrl('https://site.com', forcePrepend)).toEqual(
'https://site.com',
);
expect(useBaseUrl('/hello/byebye', {absolute: true})).toEqual(
'https://docusaurus.io/docusaurus/hello/byebye',
);
expect(useBaseUrl('/docusaurus/')).toEqual('/docusaurus/');
expect(useBaseUrl('/docusaurus/hello')).toEqual('/docusaurus/hello');
expect(useBaseUrl('#hello')).toEqual('#hello');
});
});
describe('useBaseUrlUtils().withBaseUrl()', () => {
it('empty base URL', () => {
mockedContext.mockImplementation(() => ({
siteConfig: {
baseUrl: '/',
url: 'https://docusaurus.io',
},
}));
const {withBaseUrl} = useBaseUrlUtils();
expect(withBaseUrl('hello')).toEqual('/hello');
expect(withBaseUrl('/hello')).toEqual('/hello');
expect(withBaseUrl('hello/')).toEqual('/hello/');
expect(withBaseUrl('/hello/')).toEqual('/hello/');
expect(withBaseUrl('hello/byebye')).toEqual('/hello/byebye');
expect(withBaseUrl('/hello/byebye')).toEqual('/hello/byebye');
expect(withBaseUrl('hello/byebye/')).toEqual('/hello/byebye/');
expect(withBaseUrl('/hello/byebye/')).toEqual('/hello/byebye/');
expect(withBaseUrl('https://github.com')).toEqual('https://github.com');
expect(withBaseUrl('//reactjs.org')).toEqual('//reactjs.org');
expect(withBaseUrl('//reactjs.org', forcePrepend)).toEqual('//reactjs.org');
expect(withBaseUrl('https://site.com', forcePrepend)).toEqual(
'https://site.com',
);
expect(withBaseUrl('/hello/byebye', {absolute: true})).toEqual(
'https://docusaurus.io/hello/byebye',
);
expect(withBaseUrl('#hello')).toEqual('#hello');
});
it('non-empty base URL', () => {
mockedContext.mockImplementation(() => ({
siteConfig: {
baseUrl: '/docusaurus/',
url: 'https://docusaurus.io',
},
}));
const {withBaseUrl} = useBaseUrlUtils();
expect(withBaseUrl('hello')).toEqual('/docusaurus/hello');
expect(withBaseUrl('/hello')).toEqual('/docusaurus/hello');
expect(withBaseUrl('hello/')).toEqual('/docusaurus/hello/');
expect(withBaseUrl('/hello/')).toEqual('/docusaurus/hello/');
expect(withBaseUrl('hello/byebye')).toEqual('/docusaurus/hello/byebye');
expect(withBaseUrl('/hello/byebye')).toEqual('/docusaurus/hello/byebye');
expect(withBaseUrl('hello/byebye/')).toEqual('/docusaurus/hello/byebye/');
expect(withBaseUrl('/hello/byebye/')).toEqual('/docusaurus/hello/byebye/');
expect(withBaseUrl('https://github.com')).toEqual('https://github.com');
expect(withBaseUrl('//reactjs.org')).toEqual('//reactjs.org');
expect(withBaseUrl('//reactjs.org', forcePrepend)).toEqual('//reactjs.org');
expect(withBaseUrl('https://site.com', forcePrepend)).toEqual(
'https://site.com',
);
expect(withBaseUrl('/hello/byebye', {absolute: true})).toEqual(
'https://docusaurus.io/docusaurus/hello/byebye',
);
expect(withBaseUrl('/docusaurus/')).toEqual('/docusaurus/');
expect(withBaseUrl('/docusaurus/hello')).toEqual('/docusaurus/hello');
expect(withBaseUrl('#hello')).toEqual('#hello');
});
});

View file

@ -0,0 +1,150 @@
/**
* Copyright (c) Facebook, Inc. and its affiliates.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/
import React from 'react';
import {renderHook} from '@testing-library/react-hooks';
import useBaseUrl, {useBaseUrlUtils} from '../useBaseUrl';
import {Context} from '../docusaurusContext';
import type {DocusaurusContext} from '@docusaurus/types';
import type {BaseUrlOptions} from '@docusaurus/useBaseUrl';
const forcePrepend = {forcePrependBaseUrl: true};
describe('useBaseUrl', () => {
const createUseBaseUrlMock =
(context: DocusaurusContext) => (url: string, options?: BaseUrlOptions) =>
renderHook(() => useBaseUrl(url, options), {
wrapper: ({children}) => (
<Context.Provider value={context}>{children}</Context.Provider>
),
}).result.current;
it('works with empty base URL', () => {
const mockUseBaseUrl = createUseBaseUrlMock({
siteConfig: {
baseUrl: '/',
url: 'https://docusaurus.io',
},
});
expect(mockUseBaseUrl('hello')).toBe('/hello');
expect(mockUseBaseUrl('/hello')).toBe('/hello');
expect(mockUseBaseUrl('hello/')).toBe('/hello/');
expect(mockUseBaseUrl('/hello/')).toBe('/hello/');
expect(mockUseBaseUrl('hello/byebye')).toBe('/hello/byebye');
expect(mockUseBaseUrl('/hello/byebye')).toBe('/hello/byebye');
expect(mockUseBaseUrl('hello/byebye/')).toBe('/hello/byebye/');
expect(mockUseBaseUrl('/hello/byebye/')).toBe('/hello/byebye/');
expect(mockUseBaseUrl('https://github.com')).toBe('https://github.com');
expect(mockUseBaseUrl('//reactjs.org')).toBe('//reactjs.org');
expect(mockUseBaseUrl('//reactjs.org', forcePrepend)).toBe('//reactjs.org');
expect(mockUseBaseUrl('https://site.com', forcePrepend)).toBe(
'https://site.com',
);
expect(mockUseBaseUrl('/hello/byebye', {absolute: true})).toBe(
'https://docusaurus.io/hello/byebye',
);
expect(mockUseBaseUrl('#hello')).toBe('#hello');
});
it('works with non-empty base URL', () => {
const mockUseBaseUrl = createUseBaseUrlMock({
siteConfig: {
baseUrl: '/docusaurus/',
url: 'https://docusaurus.io',
},
});
expect(mockUseBaseUrl('')).toBe('');
expect(mockUseBaseUrl('hello')).toBe('/docusaurus/hello');
expect(mockUseBaseUrl('/hello')).toBe('/docusaurus/hello');
expect(mockUseBaseUrl('hello/')).toBe('/docusaurus/hello/');
expect(mockUseBaseUrl('/hello/')).toBe('/docusaurus/hello/');
expect(mockUseBaseUrl('hello/byebye')).toBe('/docusaurus/hello/byebye');
expect(mockUseBaseUrl('/hello/byebye')).toBe('/docusaurus/hello/byebye');
expect(mockUseBaseUrl('hello/byebye/')).toBe('/docusaurus/hello/byebye/');
expect(mockUseBaseUrl('/hello/byebye/')).toBe('/docusaurus/hello/byebye/');
expect(mockUseBaseUrl('https://github.com')).toBe('https://github.com');
expect(mockUseBaseUrl('//reactjs.org')).toBe('//reactjs.org');
expect(mockUseBaseUrl('//reactjs.org', forcePrepend)).toBe('//reactjs.org');
expect(mockUseBaseUrl('/hello', forcePrepend)).toBe('/docusaurus/hello');
expect(mockUseBaseUrl('https://site.com', forcePrepend)).toBe(
'https://site.com',
);
expect(mockUseBaseUrl('/hello/byebye', {absolute: true})).toBe(
'https://docusaurus.io/docusaurus/hello/byebye',
);
expect(mockUseBaseUrl('/docusaurus/')).toBe('/docusaurus/');
expect(mockUseBaseUrl('/docusaurus/hello')).toBe('/docusaurus/hello');
expect(mockUseBaseUrl('#hello')).toBe('#hello');
});
});
describe('useBaseUrlUtils().withBaseUrl()', () => {
const mockUseBaseUrlUtils = (context: DocusaurusContext) =>
renderHook(() => useBaseUrlUtils(), {
wrapper: ({children}) => (
<Context.Provider value={context}>{children}</Context.Provider>
),
}).result.current;
it('empty base URL', () => {
const {withBaseUrl} = mockUseBaseUrlUtils({
siteConfig: {
baseUrl: '/',
url: 'https://docusaurus.io',
},
});
expect(withBaseUrl('hello')).toBe('/hello');
expect(withBaseUrl('/hello')).toBe('/hello');
expect(withBaseUrl('hello/')).toBe('/hello/');
expect(withBaseUrl('/hello/')).toBe('/hello/');
expect(withBaseUrl('hello/byebye')).toBe('/hello/byebye');
expect(withBaseUrl('/hello/byebye')).toBe('/hello/byebye');
expect(withBaseUrl('hello/byebye/')).toBe('/hello/byebye/');
expect(withBaseUrl('/hello/byebye/')).toBe('/hello/byebye/');
expect(withBaseUrl('https://github.com')).toBe('https://github.com');
expect(withBaseUrl('//reactjs.org')).toBe('//reactjs.org');
expect(withBaseUrl('//reactjs.org', forcePrepend)).toBe('//reactjs.org');
expect(withBaseUrl('https://site.com', forcePrepend)).toBe(
'https://site.com',
);
expect(withBaseUrl('/hello/byebye', {absolute: true})).toBe(
'https://docusaurus.io/hello/byebye',
);
expect(withBaseUrl('#hello')).toBe('#hello');
});
it('non-empty base URL', () => {
const {withBaseUrl} = mockUseBaseUrlUtils({
siteConfig: {
baseUrl: '/docusaurus/',
url: 'https://docusaurus.io',
},
});
expect(withBaseUrl('hello')).toBe('/docusaurus/hello');
expect(withBaseUrl('/hello')).toBe('/docusaurus/hello');
expect(withBaseUrl('hello/')).toBe('/docusaurus/hello/');
expect(withBaseUrl('/hello/')).toBe('/docusaurus/hello/');
expect(withBaseUrl('hello/byebye')).toBe('/docusaurus/hello/byebye');
expect(withBaseUrl('/hello/byebye')).toBe('/docusaurus/hello/byebye');
expect(withBaseUrl('hello/byebye/')).toBe('/docusaurus/hello/byebye/');
expect(withBaseUrl('/hello/byebye/')).toBe('/docusaurus/hello/byebye/');
expect(withBaseUrl('https://github.com')).toBe('https://github.com');
expect(withBaseUrl('//reactjs.org')).toBe('//reactjs.org');
expect(withBaseUrl('//reactjs.org', forcePrepend)).toBe('//reactjs.org');
expect(withBaseUrl('https://site.com', forcePrepend)).toBe(
'https://site.com',
);
expect(withBaseUrl('/hello/byebye', {absolute: true})).toBe(
'https://docusaurus.io/docusaurus/hello/byebye',
);
expect(withBaseUrl('/docusaurus/')).toBe('/docusaurus/');
expect(withBaseUrl('/docusaurus/hello')).toBe('/docusaurus/hello');
expect(withBaseUrl('#hello')).toBe('#hello');
});
});

View file

@ -10,11 +10,11 @@ import {buildSshUrl, buildHttpsUrl, hasSSHProtocol} from '../deploy';
describe('remoteBranchUrl', () => { describe('remoteBranchUrl', () => {
it('builds a normal ssh url', () => { it('builds a normal ssh url', () => {
const url = buildSshUrl('github.com', 'facebook', 'docusaurus'); const url = buildSshUrl('github.com', 'facebook', 'docusaurus');
expect(url).toEqual('git@github.com:facebook/docusaurus.git'); expect(url).toBe('git@github.com:facebook/docusaurus.git');
}); });
it('builds a ssh url with port', () => { it('builds a ssh url with port', () => {
const url = buildSshUrl('github.com', 'facebook', 'docusaurus', '422'); const url = buildSshUrl('github.com', 'facebook', 'docusaurus', '422');
expect(url).toEqual('ssh://git@github.com:422/facebook/docusaurus.git'); expect(url).toBe('ssh://git@github.com:422/facebook/docusaurus.git');
}); });
it('builds a normal http url', () => { it('builds a normal http url', () => {
const url = buildHttpsUrl( const url = buildHttpsUrl(
@ -23,7 +23,7 @@ describe('remoteBranchUrl', () => {
'facebook', 'facebook',
'docusaurus', 'docusaurus',
); );
expect(url).toEqual('https://user:pass@github.com/facebook/docusaurus.git'); expect(url).toBe('https://user:pass@github.com/facebook/docusaurus.git');
}); });
it('builds a normal http url with port', () => { it('builds a normal http url with port', () => {
const url = buildHttpsUrl( const url = buildHttpsUrl(
@ -33,7 +33,7 @@ describe('remoteBranchUrl', () => {
'docusaurus', 'docusaurus',
'5433', '5433',
); );
expect(url).toEqual( expect(url).toBe(
'https://user:pass@github.com:5433/facebook/docusaurus.git', 'https://user:pass@github.com:5433/facebook/docusaurus.git',
); );
}); });
@ -42,21 +42,21 @@ describe('remoteBranchUrl', () => {
describe('hasSSHProtocol', () => { describe('hasSSHProtocol', () => {
it('recognizes explicit SSH protocol', () => { it('recognizes explicit SSH protocol', () => {
const url = 'ssh://git@github.com:422/facebook/docusaurus.git'; const url = 'ssh://git@github.com:422/facebook/docusaurus.git';
expect(hasSSHProtocol(url)).toEqual(true); expect(hasSSHProtocol(url)).toBe(true);
}); });
it('recognizes implied SSH protocol', () => { it('recognizes implied SSH protocol', () => {
const url = 'git@github.com:facebook/docusaurus.git'; const url = 'git@github.com:facebook/docusaurus.git';
expect(hasSSHProtocol(url)).toEqual(true); expect(hasSSHProtocol(url)).toBe(true);
}); });
it('does not recognize HTTPS with credentials', () => { it('does not recognize HTTPS with credentials', () => {
const url = 'https://user:pass@github.com/facebook/docusaurus.git'; const url = 'https://user:pass@github.com/facebook/docusaurus.git';
expect(hasSSHProtocol(url)).toEqual(false); expect(hasSSHProtocol(url)).toBe(false);
}); });
it('does not recognize plain HTTPS URL', () => { it('does not recognize plain HTTPS URL', () => {
const url = 'https://github.com:5433/facebook/docusaurus.git'; const url = 'https://github.com:5433/facebook/docusaurus.git';
expect(hasSSHProtocol(url)).toEqual(false); expect(hasSSHProtocol(url)).toBe(false);
}); });
}); });

View file

@ -9,39 +9,39 @@ import {transformMarkdownContent} from '../writeHeadingIds';
describe('transformMarkdownContent', () => { describe('transformMarkdownContent', () => {
it('works for simple level-2 heading', () => { it('works for simple level-2 heading', () => {
expect(transformMarkdownContent('## ABC')).toEqual('## ABC {#abc}'); expect(transformMarkdownContent('## ABC')).toBe('## ABC {#abc}');
}); });
it('works for simple level-3 heading', () => { it('works for simple level-3 heading', () => {
expect(transformMarkdownContent('### ABC')).toEqual('### ABC {#abc}'); expect(transformMarkdownContent('### ABC')).toBe('### ABC {#abc}');
}); });
it('works for simple level-4 heading', () => { it('works for simple level-4 heading', () => {
expect(transformMarkdownContent('#### ABC')).toEqual('#### ABC {#abc}'); expect(transformMarkdownContent('#### ABC')).toBe('#### ABC {#abc}');
}); });
it('unwraps markdown links', () => { it('unwraps markdown links', () => {
const input = `## hello [facebook](https://facebook.com) [crowdin](https://crowdin.com/translate/docusaurus-v2/126/en-fr?filter=basic&value=0)`; const input = `## hello [facebook](https://facebook.com) [crowdin](https://crowdin.com/translate/docusaurus-v2/126/en-fr?filter=basic&value=0)`;
expect(transformMarkdownContent(input)).toEqual( expect(transformMarkdownContent(input)).toBe(
`${input} {#hello-facebook-crowdin}`, `${input} {#hello-facebook-crowdin}`,
); );
}); });
it('can slugify complex headings', () => { it('can slugify complex headings', () => {
const input = '## abc [Hello] How are you %Sébastien_-_$)( ## -56756'; const input = '## abc [Hello] How are you %Sébastien_-_$)( ## -56756';
expect(transformMarkdownContent(input)).toEqual( expect(transformMarkdownContent(input)).toBe(
`${input} {#abc-hello-how-are-you-sébastien_-_---56756}`, `${input} {#abc-hello-how-are-you-sébastien_-_---56756}`,
); );
}); });
it('does not duplicate duplicate id', () => { it('does not duplicate duplicate id', () => {
expect(transformMarkdownContent('## hello world {#hello-world}')).toEqual( expect(transformMarkdownContent('## hello world {#hello-world}')).toBe(
'## hello world {#hello-world}', '## hello world {#hello-world}',
); );
}); });
it('respects existing heading', () => { it('respects existing heading', () => {
expect(transformMarkdownContent('## New heading {#old-heading}')).toEqual( expect(transformMarkdownContent('## New heading {#old-heading}')).toBe(
'## New heading {#old-heading}', '## New heading {#old-heading}',
); );
}); });
@ -51,7 +51,7 @@ describe('transformMarkdownContent', () => {
transformMarkdownContent('## New heading {#old-heading}', { transformMarkdownContent('## New heading {#old-heading}', {
overwrite: true, overwrite: true,
}), }),
).toEqual('## New heading {#new-heading}'); ).toBe('## New heading {#new-heading}');
}); });
it('maintains casing when asked to', () => { it('maintains casing when asked to', () => {
@ -59,7 +59,7 @@ describe('transformMarkdownContent', () => {
transformMarkdownContent('## getDataFromAPI()', { transformMarkdownContent('## getDataFromAPI()', {
maintainCase: true, maintainCase: true,
}), }),
).toEqual('## getDataFromAPI() {#getDataFromAPI}'); ).toBe('## getDataFromAPI() {#getDataFromAPI}');
}); });
it('transform the headings', () => { it('transform the headings', () => {

View file

@ -118,15 +118,15 @@ describe('getThemeComponents', () => {
themePath, themePath,
swizzleConfig, swizzleConfig,
}); });
expect( expect(themeComponents.getDescription(Components.ComponentInFolder)).toBe(
themeComponents.getDescription(Components.ComponentInFolder), 'ComponentInFolder description',
).toEqual('ComponentInFolder description'); );
expect( expect(
themeComponents.getDescription(Components.ComponentInSubFolder), themeComponents.getDescription(Components.ComponentInSubFolder),
).toEqual('N/A'); ).toBe('N/A');
expect( expect(themeComponents.getDescription(Components.FirstLevelComponent)).toBe(
themeComponents.getDescription(Components.FirstLevelComponent), 'N/A',
).toEqual('N/A'); );
}); });
it('getActionStatus', async () => { it('getActionStatus', async () => {
@ -137,24 +137,24 @@ describe('getThemeComponents', () => {
}); });
expect( expect(
themeComponents.getActionStatus(Components.ComponentInFolder, 'wrap'), themeComponents.getActionStatus(Components.ComponentInFolder, 'wrap'),
).toEqual('safe'); ).toBe('safe');
expect( expect(
themeComponents.getActionStatus(Components.ComponentInFolder, 'eject'), themeComponents.getActionStatus(Components.ComponentInFolder, 'eject'),
).toEqual('unsafe'); ).toBe('unsafe');
expect( expect(
themeComponents.getActionStatus(Components.ComponentInSubFolder, 'wrap'), themeComponents.getActionStatus(Components.ComponentInSubFolder, 'wrap'),
).toEqual('unsafe'); ).toBe('unsafe');
expect( expect(
themeComponents.getActionStatus(Components.ComponentInSubFolder, 'eject'), themeComponents.getActionStatus(Components.ComponentInSubFolder, 'eject'),
).toEqual('safe'); ).toBe('safe');
expect( expect(
themeComponents.getActionStatus(Components.FirstLevelComponent, 'wrap'), themeComponents.getActionStatus(Components.FirstLevelComponent, 'wrap'),
).toEqual('unsafe'); ).toBe('unsafe');
expect( expect(
themeComponents.getActionStatus(Components.FirstLevelComponent, 'eject'), themeComponents.getActionStatus(Components.FirstLevelComponent, 'eject'),
).toEqual('unsafe'); ).toBe('unsafe');
}); });
it('isSafeAction', async () => { it('isSafeAction', async () => {
@ -165,24 +165,24 @@ describe('getThemeComponents', () => {
}); });
expect( expect(
themeComponents.isSafeAction(Components.ComponentInFolder, 'wrap'), themeComponents.isSafeAction(Components.ComponentInFolder, 'wrap'),
).toEqual(true); ).toBe(true);
expect( expect(
themeComponents.isSafeAction(Components.ComponentInFolder, 'eject'), themeComponents.isSafeAction(Components.ComponentInFolder, 'eject'),
).toEqual(false); ).toBe(false);
expect( expect(
themeComponents.isSafeAction(Components.ComponentInSubFolder, 'wrap'), themeComponents.isSafeAction(Components.ComponentInSubFolder, 'wrap'),
).toEqual(false); ).toBe(false);
expect( expect(
themeComponents.isSafeAction(Components.ComponentInSubFolder, 'eject'), themeComponents.isSafeAction(Components.ComponentInSubFolder, 'eject'),
).toEqual(true); ).toBe(true);
expect( expect(
themeComponents.isSafeAction(Components.FirstLevelComponent, 'wrap'), themeComponents.isSafeAction(Components.FirstLevelComponent, 'wrap'),
).toEqual(false); ).toBe(false);
expect( expect(
themeComponents.isSafeAction(Components.FirstLevelComponent, 'eject'), themeComponents.isSafeAction(Components.FirstLevelComponent, 'eject'),
).toEqual(false); ).toBe(false);
}); });
it('hasAnySafeAction', async () => { it('hasAnySafeAction', async () => {
@ -191,14 +191,14 @@ describe('getThemeComponents', () => {
themePath, themePath,
swizzleConfig, swizzleConfig,
}); });
expect( expect(themeComponents.hasAnySafeAction(Components.ComponentInFolder)).toBe(
themeComponents.hasAnySafeAction(Components.ComponentInFolder), true,
).toEqual(true); );
expect( expect(
themeComponents.hasAnySafeAction(Components.ComponentInSubFolder), themeComponents.hasAnySafeAction(Components.ComponentInSubFolder),
).toEqual(true); ).toBe(true);
expect( expect(
themeComponents.hasAnySafeAction(Components.FirstLevelComponent), themeComponents.hasAnySafeAction(Components.FirstLevelComponent),
).toEqual(false); ).toBe(false);
}); });
}); });

View file

@ -287,8 +287,8 @@ describe('config warnings', () => {
url: 'https://mysite.com/someSubpath', url: 'https://mysite.com/someSubpath',
}); });
expect(warning).toBeDefined(); expect(warning).toBeDefined();
expect(warning?.details.length).toEqual(1); 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"`, `"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

@ -181,7 +181,7 @@ describe('localizePath', () => {
}, },
options: {localizePath: true}, options: {localizePath: true},
}), }),
).toEqual('/baseUrl/fr/'); ).toBe('/baseUrl/fr/');
}); });
it('localizes fs path with current locale', () => { it('localizes fs path with current locale', () => {
@ -197,7 +197,7 @@ describe('localizePath', () => {
}, },
options: {localizePath: true}, options: {localizePath: true},
}), }),
).toEqual(`${path.sep}baseFsPath${path.sep}fr`); ).toBe(`${path.sep}baseFsPath${path.sep}fr`);
}); });
it('localizes path for default locale, if requested', () => { it('localizes path for default locale, if requested', () => {
@ -213,7 +213,7 @@ describe('localizePath', () => {
}, },
options: {localizePath: true}, options: {localizePath: true},
}), }),
).toEqual('/baseUrl/en/'); ).toBe('/baseUrl/en/');
}); });
it('does not localize path for default locale by default', () => { it('does not localize path for default locale by default', () => {
@ -229,7 +229,7 @@ describe('localizePath', () => {
}, },
// options: {localizePath: true}, // options: {localizePath: true},
}), }),
).toEqual('/baseUrl/'); ).toBe('/baseUrl/');
}); });
it('localizes path for non-default locale by default', () => { it('localizes path for non-default locale by default', () => {
@ -245,6 +245,6 @@ describe('localizePath', () => {
}, },
// options: {localizePath: true}, // options: {localizePath: true},
}), }),
).toEqual('/baseUrl/'); ).toBe('/baseUrl/');
}); });
}); });

View file

@ -1,6 +1,6 @@
// Jest Snapshot v1, https://goo.gl/fbAQLP // Jest Snapshot v1, https://goo.gl/fbAQLP
exports[`initPlugins plugins with bad values throw user-friendly error message 1`] = ` exports[`initPlugins throws user-friendly error message for plugins with bad values 1`] = `
" => Bad Docusaurus plugin value as path [plugins,0]. " => Bad Docusaurus plugin value as path [plugins,0].
Example valid plugin config: Example valid plugin config:
{ {

View file

@ -29,10 +29,10 @@ describe('initPlugins', () => {
return {siteDir, context, plugins}; return {siteDir, context, plugins};
} }
it('plugins gets parsed correctly and loads in correct order', async () => { it('parses plugins correctly and loads them in correct order', async () => {
const {context, plugins} = await loadSite(); const {context, plugins} = await loadSite();
expect(context.siteConfig.plugins?.length).toBe(4); expect(context.siteConfig.plugins?.length).toBe(4);
expect(plugins.length).toBe(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');
@ -45,7 +45,7 @@ describe('initPlugins', () => {
expect(context.siteConfig.themeConfig).toEqual({a: 1}); expect(context.siteConfig.themeConfig).toEqual({a: 1});
}); });
it('plugins with bad values throw user-friendly error message', async () => { it('throws user-friendly error message for plugins with bad values', async () => {
await expect(() => await expect(() =>
loadSite({ loadSite({
customConfigFilePath: 'badPlugins.docusaurus.config.js', customConfigFilePath: 'badPlugins.docusaurus.config.js',

View file

@ -348,9 +348,7 @@ describe('writePluginTranslations', () => {
}); });
} }
await expect(readTranslationFileContent(filePath)).resolves.toEqual( await expect(readTranslationFileContent(filePath)).resolves.toBeUndefined();
undefined,
);
await doWritePluginTranslations({ await doWritePluginTranslations({
key1: {message: 'key1 message', description: 'key1 desc'}, key1: {message: 'key1 message', description: 'key1 desc'},

View file

@ -28,7 +28,7 @@ describe('babel transpilation exclude logic', () => {
path.join('exports', 'Link.js'), path.join('exports', 'Link.js'),
]; ];
clientFiles.forEach((file) => { clientFiles.forEach((file) => {
expect(excludeJS(path.join(clientDir, file))).toEqual(false); expect(excludeJS(path.join(clientDir, file))).toBe(false);
}); });
}); });
@ -39,7 +39,7 @@ describe('babel transpilation exclude logic', () => {
'/src/theme/SearchBar/index.js', '/src/theme/SearchBar/index.js',
]; ];
moduleFiles.forEach((file) => { moduleFiles.forEach((file) => {
expect(excludeJS(file)).toEqual(false); expect(excludeJS(file)).toBe(false);
}); });
}); });
@ -50,7 +50,7 @@ describe('babel transpilation exclude logic', () => {
'/docusaurus/website/node_modules/@docusaurus/theme-search-algolia/theme/SearchBar.js', '/docusaurus/website/node_modules/@docusaurus/theme-search-algolia/theme/SearchBar.js',
]; ];
moduleFiles.forEach((file) => { moduleFiles.forEach((file) => {
expect(excludeJS(file)).toEqual(false); expect(excludeJS(file)).toBe(false);
}); });
}); });
@ -63,7 +63,7 @@ describe('babel transpilation exclude logic', () => {
'node_modules/docusaurus-theme-classic/node_modules/react-daypicker/index.js', 'node_modules/docusaurus-theme-classic/node_modules/react-daypicker/index.js',
]; ];
moduleFiles.forEach((file) => { moduleFiles.forEach((file) => {
expect(excludeJS(file)).toEqual(true); expect(excludeJS(file)).toBe(true);
}); });
}); });
}); });

View file

@ -13,7 +13,7 @@ import loadSetup from '../../server/__tests__/testUtils';
describe('webpack production config', () => { describe('webpack production config', () => {
it('simple', async () => { it('simple', async () => {
console.log = jest.fn(); 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});
const errors = webpack.validate(config); const errors = webpack.validate(config);
@ -21,7 +21,7 @@ describe('webpack production config', () => {
}); });
it('custom', async () => { it('custom', async () => {
console.log = jest.fn(); 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});
const errors = webpack.validate(config); const errors = webpack.validate(config);

View file

@ -268,7 +268,7 @@ describe('extending PostCSS', () => {
// @ts-expect-error: relax type // @ts-expect-error: relax type
const postCssLoader1 = webpackConfig.module?.rules[0].use[2]; const postCssLoader1 = webpackConfig.module?.rules[0].use[2];
expect(postCssLoader1.loader).toEqual('postcss-loader-1'); expect(postCssLoader1.loader).toBe('postcss-loader-1');
const pluginNames1 = postCssLoader1.options.postcssOptions.plugins.map( const pluginNames1 = postCssLoader1.options.postcssOptions.plugins.map(
(p: unknown) => p[0], (p: unknown) => p[0],
@ -283,7 +283,7 @@ describe('extending PostCSS', () => {
// @ts-expect-error: relax type // @ts-expect-error: relax type
const postCssLoader2 = webpackConfig.module?.rules[1].use[0]; const postCssLoader2 = webpackConfig.module?.rules[1].use[0];
expect(postCssLoader2.loader).toEqual('postcss-loader-2'); expect(postCssLoader2.loader).toBe('postcss-loader-2');
const pluginNames2 = postCssLoader2.options.postcssOptions.plugins.map( const pluginNames2 = postCssLoader2.options.postcssOptions.plugins.map(
(p: unknown) => p[0], (p: unknown) => p[0],

View file

@ -15,7 +15,7 @@ describe('toBase64', () => {
it('returns a properly formatted Base64 image string', () => { it('returns a properly formatted Base64 image string', () => {
const mockedMimeType = 'image/jpeg'; const mockedMimeType = 'image/jpeg';
const mockedBase64Data = Buffer.from('hello world'); const mockedBase64Data = Buffer.from('hello world');
expect(toBase64(mockedMimeType, mockedBase64Data)).toEqual( expect(toBase64(mockedMimeType, mockedBase64Data)).toBe(
'data:image/jpeg;base64,aGVsbG8gd29ybGQ=', 'data:image/jpeg;base64,aGVsbG8gd29ybGQ=',
); );
}); });