-
-
Notifications
You must be signed in to change notification settings - Fork 8.6k
/
index.test.ts
702 lines (640 loc) · 19.8 KB
/
index.test.ts
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
/**
* 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 path from 'path';
import {normalizePluginOptions} from '@docusaurus/utils-validation';
import {
posixPath,
getFileCommitDate,
LAST_UPDATE_FALLBACK,
} from '@docusaurus/utils';
import {DEFAULT_FUTURE_CONFIG} from '@docusaurus/core/src/server/configValidation';
import pluginContentBlog from '../index';
import {validateOptions} from '../options';
import type {
DocusaurusConfig,
LoadContext,
I18n,
Validate,
MarkdownConfig,
} from '@docusaurus/types';
import type {
BlogPost,
Options,
PluginOptions,
EditUrlFunction,
} from '@docusaurus/plugin-content-blog';
const markdown: MarkdownConfig = {
format: 'mdx',
mermaid: true,
mdx1Compat: {
comments: true,
headingIds: true,
admonitions: true,
},
parseFrontMatter: async (params) => {
// Reuse the default parser
const result = await params.defaultParseFrontMatter(params);
if (result.frontMatter.title === 'Complex Slug') {
result.frontMatter.custom_frontMatter = 'added by parseFrontMatter';
}
return result;
},
remarkRehypeOptions: undefined,
};
function findByTitle(
blogPosts: BlogPost[],
title: string,
): BlogPost | undefined {
return blogPosts.find((v) => v.metadata.title === title);
}
function getByTitle(blogPosts: BlogPost[], title: string): BlogPost {
const post = findByTitle(blogPosts, title);
if (!post) {
throw new Error(`can't find blog post with title ${title}.
Available blog post titles are:\n- ${blogPosts
.map((p) => p.metadata.title)
.join('\n- ')}`);
}
return post;
}
function getI18n(locale: string): I18n {
return {
currentLocale: locale,
locales: [locale],
defaultLocale: locale,
path: 'i18n',
localeConfigs: {
[locale]: {
calendar: 'gregory',
label: locale,
htmlLang: locale,
direction: 'ltr',
path: locale,
},
},
};
}
const DefaultI18N: I18n = getI18n('en');
const PluginPath = 'blog';
const BaseEditUrl = 'https://baseEditUrl.com/edit';
const getPlugin = async (
siteDir: string,
pluginOptions: Partial<PluginOptions> = {},
i18n: I18n = DefaultI18N,
) => {
const generatedFilesDir: string = path.resolve(siteDir, '.docusaurus');
const localizationDir = path.join(
siteDir,
i18n.path,
i18n.localeConfigs[i18n.currentLocale]!.path,
);
const siteConfig = {
title: 'Hello',
baseUrl: '/',
url: 'https://docusaurus.io',
markdown,
future: DEFAULT_FUTURE_CONFIG,
staticDirectories: ['static'],
} as DocusaurusConfig;
return pluginContentBlog(
{
siteDir,
siteConfig,
generatedFilesDir,
i18n,
localizationDir,
} as LoadContext,
validateOptions({
validate: normalizePluginOptions as Validate<
Options | undefined,
PluginOptions
>,
options: {
path: PluginPath,
editUrl: BaseEditUrl,
...pluginOptions,
},
}),
);
};
const getBlogPosts = async (
siteDir: string,
pluginOptions: Partial<PluginOptions> = {},
i18n: I18n = DefaultI18N,
) => {
const plugin = await getPlugin(siteDir, pluginOptions, i18n);
const {blogPosts} = (await plugin.loadContent!())!;
return blogPosts;
};
const getBlogTags = async (
siteDir: string,
pluginOptions: Partial<PluginOptions> = {},
i18n: I18n = DefaultI18N,
) => {
const plugin = await getPlugin(siteDir, pluginOptions, i18n);
const {blogTags} = (await plugin.loadContent!())!;
return blogTags;
};
describe('blog plugin', () => {
it('getPathsToWatch returns right files', async () => {
const siteDir = path.join(__dirname, '__fixtures__', 'website');
const plugin = await getPlugin(siteDir);
const pathsToWatch = plugin.getPathsToWatch!();
const relativePathsToWatch = pathsToWatch.map((p) =>
posixPath(path.relative(siteDir, p)),
);
expect(relativePathsToWatch).toEqual([
'i18n/en/docusaurus-plugin-content-blog/authors.yml',
'i18n/en/docusaurus-plugin-content-blog/tags.yml',
'blog/tags.yml',
'i18n/en/docusaurus-plugin-content-blog/**/*.{md,mdx}',
'blog/**/*.{md,mdx}',
]);
});
it('builds a simple website', async () => {
const siteDir = path.join(__dirname, '__fixtures__', 'website');
const blogPosts = await getBlogPosts(siteDir);
expect({
...getByTitle(blogPosts, 'date-matter').metadata,
...{prevItem: undefined},
}).toEqual({
editUrl: `${BaseEditUrl}/blog/date-matter.md`,
permalink: '/blog/date-matter',
readingTime: 0.02,
source: path.posix.join('@site', PluginPath, 'date-matter.md'),
title: 'date-matter',
description: `date inside front matter`,
authors: [],
date: new Date('2019-01-01'),
frontMatter: {
date: new Date('2019-01-01'),
tags: ['date'],
},
prevItem: undefined,
tags: [
{
description: undefined,
inline: true,
label: 'date',
permalink: '/blog/tags/date',
},
],
nextItem: {
permalink: '/blog/2018/12/14/Happy-First-Birthday-Slash',
title: 'Happy 1st Birthday Slash! (translated)',
},
hasTruncateMarker: false,
unlisted: false,
});
expect(
getByTitle(blogPosts, 'Happy 1st Birthday Slash! (translated)').metadata,
).toEqual({
editUrl: `${BaseEditUrl}/blog/2018-12-14-Happy-First-Birthday-Slash.md`,
permalink: '/blog/2018/12/14/Happy-First-Birthday-Slash',
readingTime: 0.015,
source: path.posix.join(
'@site',
path.posix.join('i18n', 'en', 'docusaurus-plugin-content-blog'),
'2018-12-14-Happy-First-Birthday-Slash.md',
),
title: 'Happy 1st Birthday Slash! (translated)',
description: `Happy birthday! (translated)`,
authors: [
{
name: 'Yangshun Tay (translated)',
imageURL: undefined,
key: null,
page: null,
socials: {},
},
{
email: '[email protected]',
key: 'slorber',
name: 'Sébastien Lorber (translated)',
title: 'Docusaurus maintainer (translated)',
imageURL: undefined,
socials: undefined,
page: {permalink: '/blog/authors/slorber-custom-permalink-localized'},
},
],
date: new Date('2018-12-14'),
frontMatter: {
authors: [
{
name: 'Yangshun Tay (translated)',
},
'slorber',
],
tags: ['inlineTag', 'globalTag'],
title: 'Happy 1st Birthday Slash! (translated)',
},
tags: [
{
description: undefined,
inline: true,
label: 'inlineTag',
permalink: '/blog/tags/inline-tag',
},
{
description: 'Global Tag description (en)',
inline: false,
label: 'Global Tag label (en)',
permalink: '/blog/tags/global-tag-permalink (en)',
},
],
prevItem: {
permalink: '/blog/date-matter',
title: 'date-matter',
},
hasTruncateMarker: false,
unlisted: false,
});
expect({
...getByTitle(blogPosts, 'Complex Slug').metadata,
...{prevItem: undefined},
}).toEqual({
editUrl: `${BaseEditUrl}/blog/complex-slug.md`,
permalink: '/blog/hey/my super path/héllô',
readingTime: 0.015,
source: path.posix.join('@site', PluginPath, 'complex-slug.md'),
title: 'Complex Slug',
description: `complex url slug`,
authors: [],
prevItem: undefined,
nextItem: {
permalink: '/blog/simple/slug',
title: 'Simple Slug',
},
date: new Date('2020-08-16'),
frontMatter: {
date: '2020/08/16',
slug: '/hey/my super path/héllô',
title: 'Complex Slug',
tags: ['date', 'complex'],
custom_frontMatter: 'added by parseFrontMatter',
},
tags: [
{
description: undefined,
inline: true,
label: 'date',
permalink: '/blog/tags/date',
},
{
description: undefined,
inline: true,
label: 'complex',
permalink: '/blog/tags/complex',
},
],
hasTruncateMarker: false,
unlisted: false,
});
expect({
...getByTitle(blogPosts, 'Simple Slug').metadata,
...{prevItem: undefined},
}).toEqual({
editUrl: `${BaseEditUrl}/blog/simple-slug.md`,
permalink: '/blog/simple/slug',
readingTime: 0.015,
source: path.posix.join('@site', PluginPath, 'simple-slug.md'),
title: 'Simple Slug',
description: `simple url slug`,
authors: [
{
name: 'Sébastien Lorber',
title: 'Docusaurus maintainer',
url: 'https://sebastienlorber.com',
imageURL: undefined,
page: null,
key: null,
},
],
prevItem: undefined,
nextItem: {
permalink: '/blog/draft',
title: 'draft',
},
date: new Date('2020-08-15'),
frontMatter: {
author: 'Sébastien Lorber',
author_title: 'Docusaurus maintainer',
author_url: 'https://sebastienlorber.com',
date: new Date('2020-08-15'),
slug: '/simple/slug',
title: 'Simple Slug',
},
tags: [],
hasTruncateMarker: false,
unlisted: false,
});
expect({
...getByTitle(blogPosts, 'some heading').metadata,
prevItem: undefined,
}).toEqual({
editUrl: `${BaseEditUrl}/blog/heading-as-title.md`,
permalink: '/blog/heading-as-title',
readingTime: 0,
source: path.posix.join('@site', PluginPath, 'heading-as-title.md'),
title: 'some heading',
description: '',
authors: [],
date: new Date('2019-01-02'),
frontMatter: {
date: new Date('2019-01-02'),
},
prevItem: undefined,
tags: [],
nextItem: {
permalink: '/blog/date-matter',
title: 'date-matter',
},
hasTruncateMarker: false,
unlisted: false,
});
});
it('handles edit URL with editLocalizedBlogs: true', async () => {
const siteDir = path.join(__dirname, '__fixtures__', 'website');
const blogPosts = await getBlogPosts(siteDir, {editLocalizedFiles: true});
const localizedBlogPost = blogPosts.find(
(v) => v.metadata.title === 'Happy 1st Birthday Slash! (translated)',
)!;
expect(localizedBlogPost.metadata.editUrl).toBe(
`${BaseEditUrl}/i18n/en/docusaurus-plugin-content-blog/2018-12-14-Happy-First-Birthday-Slash.md`,
);
});
it('handles edit URL with editUrl function', async () => {
const siteDir = path.join(__dirname, '__fixtures__', 'website');
const hardcodedEditUrl = 'hardcoded-edit-url';
const editUrlFunction: EditUrlFunction = jest.fn(() => hardcodedEditUrl);
const blogPosts = await getBlogPosts(siteDir, {editUrl: editUrlFunction});
blogPosts.forEach((blogPost) => {
expect(blogPost.metadata.editUrl).toEqual(hardcodedEditUrl);
});
expect(editUrlFunction).toHaveBeenCalledTimes(10);
expect(editUrlFunction).toHaveBeenCalledWith({
blogDirPath: 'blog',
blogPath: 'date-matter.md',
permalink: '/blog/date-matter',
locale: 'en',
});
expect(editUrlFunction).toHaveBeenCalledWith({
blogDirPath: 'blog',
blogPath: 'draft.md',
permalink: '/blog/draft',
locale: 'en',
});
expect(editUrlFunction).toHaveBeenCalledWith({
blogDirPath: 'blog',
blogPath: 'mdx-blog-post.mdx',
permalink: '/blog/mdx-blog-post',
locale: 'en',
});
expect(editUrlFunction).toHaveBeenCalledWith({
blogDirPath: 'blog',
blogPath: 'mdx-require-blog-post.mdx',
permalink: '/blog/mdx-require-blog-post',
locale: 'en',
});
expect(editUrlFunction).toHaveBeenCalledWith({
blogDirPath: 'blog',
blogPath: 'complex-slug.md',
permalink: '/blog/hey/my super path/héllô',
locale: 'en',
});
expect(editUrlFunction).toHaveBeenCalledWith({
blogDirPath: 'blog',
blogPath: 'simple-slug.md',
permalink: '/blog/simple/slug',
locale: 'en',
});
expect(editUrlFunction).toHaveBeenCalledWith({
blogDirPath: 'i18n/en/docusaurus-plugin-content-blog',
blogPath: '2018-12-14-Happy-First-Birthday-Slash.md',
permalink: '/blog/2018/12/14/Happy-First-Birthday-Slash',
locale: 'en',
});
expect(editUrlFunction).toHaveBeenCalledWith({
blogDirPath: 'blog',
blogPath: 'heading-as-title.md',
locale: 'en',
permalink: '/blog/heading-as-title',
});
});
it('excludes draft blog post from production build', async () => {
const originalEnv = process.env;
jest.resetModules();
process.env = {...originalEnv, NODE_ENV: 'production'};
const siteDir = path.join(__dirname, '__fixtures__', 'website');
const blogPosts = await getBlogPosts(siteDir);
expect(blogPosts.find((v) => v.metadata.title === 'draft')).toBeUndefined();
process.env = originalEnv;
});
it('creates blog post without date', async () => {
const siteDir = path.join(
__dirname,
'__fixtures__',
'website-blog-without-date',
);
const blogPosts = await getBlogPosts(siteDir);
const noDateSource = path.posix.join('@site', PluginPath, 'no date.md');
const noDateSourceFile = path.posix.join(siteDir, PluginPath, 'no date.md');
// We know the file exists and we know we have git
const result = await getFileCommitDate(noDateSourceFile, {age: 'oldest'});
const noDateSourceTime = result.date;
expect({
...getByTitle(blogPosts, 'no date').metadata,
...{prevItem: undefined},
}).toEqual({
editUrl: `${BaseEditUrl}/blog/no date.md`,
permalink: '/blog/no date',
readingTime: 0.01,
source: noDateSource,
title: 'no date',
description: `no date`,
authors: [],
date: noDateSourceTime,
frontMatter: {},
tags: [],
prevItem: undefined,
nextItem: undefined,
hasTruncateMarker: false,
unlisted: false,
});
});
it('can sort blog posts in ascending order', async () => {
const siteDir = path.join(__dirname, '__fixtures__', 'website');
const normalOrder = await getBlogPosts(siteDir);
const reversedOrder = await getBlogPosts(siteDir, {
sortPosts: 'ascending',
});
expect(normalOrder.reverse().map((x) => x.metadata.date)).toEqual(
reversedOrder.map((x) => x.metadata.date),
);
});
it('works with blog tags', async () => {
const siteDir = path.join(
__dirname,
'__fixtures__',
'website-blog-with-tags',
);
const blogTags = await getBlogTags(siteDir, {
postsPerPage: 2,
});
expect(Object.keys(blogTags)).toHaveLength(3);
expect(blogTags).toMatchSnapshot();
});
it('works on blog tags without pagination', async () => {
const siteDir = path.join(
__dirname,
'__fixtures__',
'website-blog-with-tags',
);
const blogTags = await getBlogTags(siteDir, {
postsPerPage: 'ALL',
});
expect(blogTags).toMatchSnapshot();
});
it('process blog posts load content', async () => {
const siteDir = path.join(
__dirname,
'__fixtures__',
'website-blog-with-tags',
);
const plugin = await getPlugin(
siteDir,
{
postsPerPage: 1,
processBlogPosts: async ({blogPosts}) =>
blogPosts.filter((blog) => blog.metadata.tags[0]?.label === 'tag1'),
onInlineTags: 'ignore',
tags: false,
},
DefaultI18N,
);
const {blogPosts, blogTags, blogListPaginated} =
(await plugin.loadContent!())!;
expect(blogListPaginated).toHaveLength(3);
expect(Object.keys(blogTags)).toHaveLength(2);
expect(blogTags).toMatchSnapshot();
expect(blogPosts).toHaveLength(3);
expect(blogPosts).toMatchSnapshot();
});
});
describe('last update', () => {
const siteDir = path.join(
__dirname,
'__fixtures__',
'website-blog-with-last-update',
);
const lastUpdateFor = (date: string) => new Date(date).getTime();
it('author and time', async () => {
const plugin = await getPlugin(
siteDir,
{
showLastUpdateAuthor: true,
showLastUpdateTime: true,
},
DefaultI18N,
);
const {blogPosts} = (await plugin.loadContent!())!;
expect(blogPosts[0]?.metadata.lastUpdatedBy).toBe('seb');
expect(blogPosts[0]?.metadata.lastUpdatedAt).toBe(
LAST_UPDATE_FALLBACK.lastUpdatedAt,
);
expect(blogPosts[1]?.metadata.lastUpdatedBy).toBe(
LAST_UPDATE_FALLBACK.lastUpdatedBy,
);
expect(blogPosts[1]?.metadata.lastUpdatedAt).toBe(
LAST_UPDATE_FALLBACK.lastUpdatedAt,
);
expect(blogPosts[2]?.metadata.lastUpdatedBy).toBe('seb');
expect(blogPosts[2]?.metadata.lastUpdatedAt).toBe(
lastUpdateFor('2021-01-01'),
);
expect(blogPosts[3]?.metadata.lastUpdatedBy).toBe(
LAST_UPDATE_FALLBACK.lastUpdatedBy,
);
expect(blogPosts[3]?.metadata.lastUpdatedAt).toBe(
lastUpdateFor('2021-01-01'),
);
});
it('time only', async () => {
const plugin = await getPlugin(
siteDir,
{
showLastUpdateAuthor: false,
showLastUpdateTime: true,
},
DefaultI18N,
);
const {blogPosts} = (await plugin.loadContent!())!;
expect(blogPosts[0]?.metadata.title).toBe('Author');
expect(blogPosts[0]?.metadata.lastUpdatedBy).toBeUndefined();
expect(blogPosts[0]?.metadata.lastUpdatedAt).toBe(
LAST_UPDATE_FALLBACK.lastUpdatedAt,
);
expect(blogPosts[1]?.metadata.title).toBe('Nothing');
expect(blogPosts[1]?.metadata.lastUpdatedBy).toBeUndefined();
expect(blogPosts[1]?.metadata.lastUpdatedAt).toBe(
LAST_UPDATE_FALLBACK.lastUpdatedAt,
);
expect(blogPosts[2]?.metadata.title).toBe('Both');
expect(blogPosts[2]?.metadata.lastUpdatedBy).toBeUndefined();
expect(blogPosts[2]?.metadata.lastUpdatedAt).toBe(
lastUpdateFor('2021-01-01'),
);
expect(blogPosts[3]?.metadata.title).toBe('Last update date');
expect(blogPosts[3]?.metadata.lastUpdatedBy).toBeUndefined();
expect(blogPosts[3]?.metadata.lastUpdatedAt).toBe(
lastUpdateFor('2021-01-01'),
);
});
it('author only', async () => {
const plugin = await getPlugin(
siteDir,
{
showLastUpdateAuthor: true,
showLastUpdateTime: false,
},
DefaultI18N,
);
const {blogPosts} = (await plugin.loadContent!())!;
expect(blogPosts[0]?.metadata.lastUpdatedBy).toBe('seb');
expect(blogPosts[0]?.metadata.lastUpdatedAt).toBeUndefined();
expect(blogPosts[1]?.metadata.lastUpdatedBy).toBe(
LAST_UPDATE_FALLBACK.lastUpdatedBy,
);
expect(blogPosts[1]?.metadata.lastUpdatedAt).toBeUndefined();
expect(blogPosts[2]?.metadata.lastUpdatedBy).toBe('seb');
expect(blogPosts[2]?.metadata.lastUpdatedAt).toBeUndefined();
expect(blogPosts[3]?.metadata.lastUpdatedBy).toBe(
LAST_UPDATE_FALLBACK.lastUpdatedBy,
);
expect(blogPosts[3]?.metadata.lastUpdatedAt).toBeUndefined();
});
it('none', async () => {
const plugin = await getPlugin(
siteDir,
{
showLastUpdateAuthor: false,
showLastUpdateTime: false,
},
DefaultI18N,
);
const {blogPosts} = (await plugin.loadContent!())!;
expect(blogPosts[0]?.metadata.lastUpdatedBy).toBeUndefined();
expect(blogPosts[0]?.metadata.lastUpdatedAt).toBeUndefined();
expect(blogPosts[1]?.metadata.lastUpdatedBy).toBeUndefined();
expect(blogPosts[1]?.metadata.lastUpdatedAt).toBeUndefined();
expect(blogPosts[2]?.metadata.lastUpdatedBy).toBeUndefined();
expect(blogPosts[2]?.metadata.lastUpdatedAt).toBeUndefined();
expect(blogPosts[3]?.metadata.lastUpdatedBy).toBeUndefined();
expect(blogPosts[3]?.metadata.lastUpdatedAt).toBeUndefined();
});
});