Skip to content

Commit

Permalink
Create unit tests for stripOrigin()
Browse files Browse the repository at this point in the history
Signed-off-by: Phillip Rak <[email protected]>
  • Loading branch information
rak-phillip committed Nov 15, 2024
1 parent 1693709 commit 3fb53be
Show file tree
Hide file tree
Showing 2 changed files with 63 additions and 2 deletions.
61 changes: 61 additions & 0 deletions shell/utils/__tests__/url.test.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,61 @@
import { stripOrigin } from '../url';

describe('stripOrigin', () => {
// eslint-disable-next-line jest/no-hooks
beforeAll(() => {
process.env.BASE_URL = 'https://example.com';
});

// eslint-disable-next-line jest/no-hooks
afterAll(() => {
delete process.env.BASE_URL;
});

it('should strip origin from a valid absolute URL', () => {
const url = 'https://example.com/path/to/resource?query=value';

expect(stripOrigin(url)).toBe('/path/to/resource?query=value');
});

it('should strip origin from a valid relative URL', () => {
const url = '/path/to/resource?query=value';

expect(stripOrigin(url)).toBe('/path/to/resource?query=value');
});

it('should return the original URL if it is invalid', () => {
const url = 'invalid-url';

expect(stripOrigin(url, '')).toBe('invalid-url');
});

it('should handle URLs without search queries', () => {
const url = 'https://example.com/path/to/resource';

expect(stripOrigin(url)).toBe('/path/to/resource');
});

it('should handle URLs with only search queries', () => {
const url = 'https://example.com?query=value';

expect(stripOrigin(url)).toBe('/?query=value');
});

it('should handle URLs with only path', () => {
const url = 'https://example.com/path/to/resource';

expect(stripOrigin(url)).toBe('/path/to/resource');
});

it('should handle URLs with only search query in relative URL', () => {
const url = '?query=value';

expect(stripOrigin(url)).toBe('/?query=value');
});

it('should handle URLs with only path in relative URL', () => {
const url = '/path/to/resource';

expect(stripOrigin(url)).toBe('/path/to/resource');
});
});
4 changes: 2 additions & 2 deletions shell/utils/url.ts
Original file line number Diff line number Diff line change
Expand Up @@ -196,11 +196,11 @@ function canParse(url: string, base?: string): boolean {
* @param url The URL to be processed.
* @returns The path and search query part of the URL, or the original URL if parsing fails.
*/
export function stripOrigin(url: string) {
export function stripOrigin(url: string, base = process.env.BASE_URL) {
let parsedUrl: URL;

try {
parsedUrl = canParse(url) ? new URL(url) : new URL(url, process.env.BASE_URL);
parsedUrl = canParse(url) ? new URL(url) : new URL(url, base);
} catch (e) {
return url;
}
Expand Down

0 comments on commit 3fb53be

Please sign in to comment.