Skip to content

Commit

Permalink
feat: add test to check if links in feed are resolved correctly (+2 s…
Browse files Browse the repository at this point in the history
…quashed commits)

Squashed commits:
[2db488373] chore: add a new file to test href resolving
[6c18cea] docs: added to test if href resolved correctly in feed
  • Loading branch information
政宇 廖 committed Jul 21, 2023
1 parent b607956 commit a339fc9
Show file tree
Hide file tree
Showing 7 changed files with 501 additions and 30 deletions.

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

Large diffs are not rendered by default.

130 changes: 127 additions & 3 deletions packages/docusaurus-plugin-content-blog/src/__tests__/feed.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -8,12 +8,18 @@
import {jest} from '@jest/globals';
import path from 'path';
import fs from 'fs-extra';
import {load as cheerioLoad} from 'cheerio';
import {readOutputHTMLFile} from '@docusaurus/utils';
import {blogPostContainerID} from '@docusaurus/utils-common';
import {DEFAULT_OPTIONS} from '../options';
import {generateBlogPosts} from '../blogUtils';
import {createBlogFeedFiles} from '../feed';
import type {LoadContext, I18n} from '@docusaurus/types';
import {
createBlogFeedFiles,
defaultCreateFeedItems as feedDefaultCreateFeedItems,
} from '../feed';
import type {LoadContext, I18n, DocusaurusConfig} from '@docusaurus/types';
import type {BlogContentPaths} from '../types';
import type {PluginOptions} from '@docusaurus/plugin-content-blog';
import type {BlogPost, PluginOptions} from '@docusaurus/plugin-content-blog';

const DefaultI18N: I18n = {
currentLocale: 'en',
Expand Down Expand Up @@ -62,6 +68,32 @@ async function testGenerateFeeds(
});
}

function isFullAbsolutePath(str: string) {
const domain = 'https://domain.com';
const {origin} = new URL(str, domain);
return origin !== domain;
}

async function generateLinksOfBlogPosts(outDir: string, blogPosts: BlogPost[]) {
const linksOfBlogPosts: {[postId: string]: string[]} = {};
const pathOfFile = path.join(outDir, 'blog');
const promises = blogPosts.map(async (post) => {
try {
const content = await readOutputHTMLFile(post.id, pathOfFile, true);
const $ = cheerioLoad(content);
const anchorElements = $(`div#${blogPostContainerID} a`);
if (anchorElements.length > 0) {
const href = anchorElements.map((_, elm) => elm.attribs.href).toArray();
linksOfBlogPosts[post.id] = href;
}
} catch {
// post is a draft
}
});
await Promise.all(promises);
return linksOfBlogPosts;
}

describe.each(['atom', 'rss', 'json'])('%s', (feedType) => {
const fsMock = jest.spyOn(fs, 'outputFile').mockImplementation(() => {});

Expand Down Expand Up @@ -196,3 +228,95 @@ describe.each(['atom', 'rss', 'json'])('%s', (feedType) => {
fsMock.mockClear();
});
});

describe('Test defaultCreateFeedItems', () => {
const fsMock = jest.spyOn(fs, 'outputFile').mockImplementation(() => {});
it('links in feeds are resolved correctly', async () => {
const siteDir = path.join(__dirname, '__fixtures__', 'website');
const outDir = path.join(siteDir, 'build-snap');
const siteConfig = {
title: 'Hello',
baseUrl: '/myBaseUrl/',
url: 'https://docusaurus.io',
favicon: 'image/favicon.ico',
} as DocusaurusConfig;

const context = {
siteDir,
siteConfig,
i18n: DefaultI18N,
outDir,
} as LoadContext;

const options = {
path: 'blog',
routeBasePath: 'blog',
tagsBasePath: 'tags',
authorsMapPath: 'authors.yml',
include: DEFAULT_OPTIONS.include,
exclude: DEFAULT_OPTIONS.exclude,
feedOptions: {
type: ['atom', 'rss', 'json'],
copyright: 'Copyright',
},
readingTime: ({content, defaultReadingTime}) =>
defaultReadingTime({content}),
truncateMarker: /<!--\s*truncate\s*-->/,
} as PluginOptions;

const blogPosts = await generateBlogPosts(
getBlogContentPaths(siteDir),
context,
options,
);

await createBlogFeedFiles({
blogPosts,
options,
siteConfig: context.siteConfig,
outDir: context.outDir,
locale: 'en',
});

const originalLinksInBlogs: {[id: string]: Array<string>} =
await generateLinksOfBlogPosts(outDir, blogPosts);

const blogPostsWithLinks = blogPosts.filter(
(post) => originalLinksInBlogs[post.id],
);

const feedsWithLinks = await feedDefaultCreateFeedItems({
blogPosts: blogPostsWithLinks,
siteConfig,
outDir,
});

feedsWithLinks.forEach((feed) => {
const $ = cheerioLoad(feed.content ?? '');
const linksInFeed = $('a')
.map((_, elm) => elm.attribs.href)
.toArray();
const idOfBlogPost = feed.id!.replace(
new URL(`${siteConfig.baseUrl}blog`, siteConfig.url).href,
'',
);
const originalLinksInBlog = originalLinksInBlogs[idOfBlogPost];
const {permalink = ''} =
blogPostsWithLinks.find((post) => post.id === idOfBlogPost)?.metadata ||
{};

originalLinksInBlog!.forEach((originalLinkInBlog, idx) => {
const linkToTest = isFullAbsolutePath(originalLinkInBlog)
? originalLinkInBlog
: new URL(originalLinkInBlog, new URL(permalink, siteConfig.url))
.href;

expect(linkToTest).toEqual(linksInFeed[idx]);
});
});
expect(
fsMock.mock.calls.map((call) => call[1] as string),
).toMatchSnapshot();
fsMock.mockClear();
});
});
2 changes: 1 addition & 1 deletion packages/docusaurus-plugin-content-blog/src/feed.ts
Original file line number Diff line number Diff line change
Expand Up @@ -70,7 +70,7 @@ async function generateBlogFeed({
return feed;
}

async function defaultCreateFeedItems({
export async function defaultCreateFeedItems({
blogPosts,
siteConfig,
outDir,
Expand Down
9 changes: 9 additions & 0 deletions website/_dogfooding/_blog tests/2023-07-19-a.mdx
Original file line number Diff line number Diff line change
@@ -0,0 +1,9 @@
---
title: 'Test if href in feed resolved correctly'
---

[absolute full url](https://github.com/facebook/docusaurus)

[absolute url with implicit domain name](/tests/blog/2023/07/19/b)

[relative url](2023-07-19-b.mdx)
1 change: 1 addition & 0 deletions website/_dogfooding/_blog tests/2023-07-19-b.mdx
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
# Test Relative Path

0 comments on commit a339fc9

Please sign in to comment.