From 3df97a57372891d1e77226c4fbbad22aaccde22a Mon Sep 17 00:00:00 2001 From: Daragh King Date: Mon, 8 Aug 2022 10:36:33 +0100 Subject: [PATCH] fix(url-utils): joinRoutes now accounts for routes that normalize to an empty string joinRoutes now accounts for routes that normalize to an empty string COMUI-1131 --- src/specs/urlUtils.spec.ts | 28 ++++++++++++++++++++++++++++ src/urlUtils.ts | 12 +++++++++++- 2 files changed, 39 insertions(+), 1 deletion(-) create mode 100644 src/specs/urlUtils.spec.ts diff --git a/src/specs/urlUtils.spec.ts b/src/specs/urlUtils.spec.ts new file mode 100644 index 0000000..6b38191 --- /dev/null +++ b/src/specs/urlUtils.spec.ts @@ -0,0 +1,28 @@ +import { + joinRoutes, + normalizeRoute, + stripLeadingSlash, + stripLeadingSlashAndHashTag, + stripTrailingSlash +} from '../urlUtils'; + +describe('urlUtils', () => { + describe('joinRoutes', () => { + [ + { input: ['', '', ''], expectedOutput: '' }, + { input: ['test', 'test', 'test'], expectedOutput: 'test/test/test' }, + { + input: ['/test/', '/test/', '/test/'], + expectedOutput: 'test/test/test' + }, + { input: ['test', '', 'test'], expectedOutput: 'test/test' }, + { input: ['/test/', '', '/test/'], expectedOutput: 'test/test' }, + { input: ['test', '/', 'test'], expectedOutput: 'test/test' }, + { input: ['/test/', '/', '/test/'], expectedOutput: 'test/test' } + ].forEach(({ input, expectedOutput }, index) => { + it(`should work as expected (${index + 1})`, () => { + expect(joinRoutes(...input)).toBe(expectedOutput); + }); + }); + }); +}); diff --git a/src/urlUtils.ts b/src/urlUtils.ts index 788b051..6198082 100644 --- a/src/urlUtils.ts +++ b/src/urlUtils.ts @@ -36,5 +36,15 @@ export function stripLeadingSlashAndHashTag(str: string): string { * */ export function joinRoutes(...routes: string[]): string { - return routes.map(route => normalizeRoute(route)).join('/'); + return routes + .reduce((acc, route) => { + const normalizedRoute = normalizeRoute(route); + + if (normalizedRoute) { + return acc.concat([normalizedRoute]); + } + + return acc; + }, [] as string[]) + .join('/'); }