diff --git a/lib/core/__tests__/utils.test.js b/lib/core/__tests__/utils.test.js index 5c1e9ec53d4d..dd5091948e7f 100644 --- a/lib/core/__tests__/utils.test.js +++ b/lib/core/__tests__/utils.test.js @@ -39,20 +39,29 @@ describe('utils', () => { }); test('getPath', () => { - expect(utils.getPath('/docs/en/versioning.html', true)).toBe( - '/docs/en/versioning' - ); - expect(utils.getPath('/en/users.html', true)).toBe('/en/users'); - expect(utils.getPath('/docs/en/asd/index.html', true)).toBe('/docs/en/asd'); - expect(utils.getPath('/en/help/index.html', true)).toBe('/en/help'); - expect(utils.getPath('/en/help.a.b.c.d.e.html', true)).toBe( - '/en/help.a.b.c.d.e' - ); - expect(utils.getPath('/en/help.js', true)).toBe('/en/help'); + // does not change/transform path + expect(utils.getPath('/en/users.html', false)).toBe('/en/users.html'); expect(utils.getPath('/docs/en/versioning.html', false)).toBe( '/docs/en/versioning.html' ); - expect(utils.getPath('/en/users.html', false)).toBe('/en/users.html'); + expect(utils.getPath(undefined, false)).toBeUndefined(); + expect(utils.getPath(null, false)).toBeNull(); + + // transform to pretty/clean path + const cleanPath = pathStr => utils.getPath(pathStr, true); + expect(cleanPath('/en/users')).toBe('/en/users'); + expect(cleanPath('/docs/versioning.html')).toBe('/docs/versioning'); + expect(cleanPath('/en/users.html')).toBe('/en/users'); + expect(cleanPath('/docs/en/asd/index.html')).toBe('/docs/en/asd/'); + expect(cleanPath('/en/help/index.html')).toBe('/en/help/'); + expect(cleanPath('/index.html')).toBe('/'); + expect(cleanPath('/react/index.html')).toBe('/react/'); + expect(cleanPath('/en/help.a.b.c.d.e.html')).toBe('/en/help.a.b.c.d.e'); + expect(cleanPath('/en/help.js')).toBe('/en/help.js'); + expect(cleanPath('/test.md')).toBe('/test.md'); + expect(cleanPath('/blog/7.0.0')).toBe('/blog/7.0.0'); + expect(cleanPath('/test/5.html.2')).toBe('/test/5.html.2'); + expect(cleanPath('/docs/en/5.2')).toBe('/docs/en/5.2'); }); test('removeExtension', () => { diff --git a/lib/core/utils.js b/lib/core/utils.js index 5e4b66e9fed6..a01f9921504a 100644 --- a/lib/core/utils.js +++ b/lib/core/utils.js @@ -15,17 +15,17 @@ function extractBlogPostBeforeTruncate(content) { return content.split(TRUNCATE_MARKER)[0]; } -function removeExtension(path) { - return path.replace(/\.[^/.]+$/, ''); +function removeExtension(pathStr) { + return pathStr.replace(/\.[^/.]+$/, ''); } -function getPath(path, cleanUrl = false) { - if (cleanUrl) { - return path.endsWith('/index.html') - ? path.replace(/\/index.html$/, '') - : removeExtension(path); +function getPath(pathStr, cleanUrl = false) { + if (!pathStr || !cleanUrl || !pathStr.endsWith('.html')) { + return pathStr; } - return path; + return pathStr.endsWith('/index.html') + ? pathStr.replace(/index\.html$/, '') + : removeExtension(pathStr); } module.exports = {