Files
fluent-url/lib/core/serializer/url-serializer.test.ts

76 lines
2.0 KiB
TypeScript

import { describe, expect, it, vi } from 'vitest'
import { parseUrl } from './url-serializer'
const dummyQueryParser = (s: string) => ({ raw: s })
describe('parseUrl', () => {
it('parses a full absolute URL', () => {
const result = parseUrl({
str: 'https://example.com:8080/foo/bar?x=1#frag',
parseQuery: dummyQueryParser,
})
expect(result).toEqual({
protocol: 'https',
hostname: 'example.com',
paths: ['foo', 'bar'],
port: 8080,
fragment: 'frag',
queries: { raw: '?x=1' },
})
})
it('parses a relative path without protocol or hostname', () => {
const result = parseUrl({
str: '/some/path',
parseQuery: dummyQueryParser,
})
expect(result).toEqual({
paths: ['some', 'path'],
queries: Object.create(null),
})
})
it('parses relative slash-only path with query and fragment', () => {
const parser = vi.fn(dummyQueryParser)
const result = parseUrl({
str: '/?a=1#b',
parseQuery: parser,
})
expect(result.paths).toEqual([])
expect(result.queries).toEqual({ raw: '?a=1' })
expect(parser).toHaveBeenCalledOnce()
})
it('parses protocol-relative URL (//host/...)', () => {
const result = parseUrl({
str: '//foo.com/bar',
parseQuery: dummyQueryParser,
})
expect(result).toEqual({
hostname: 'foo.com',
paths: ['bar'],
queries: Object.create(null),
})
})
it('throws if the string is not a valid URL', () => {
expect(() =>
parseUrl({ str: 'not a url', parseQuery: dummyQueryParser }),
).toThrowError('Invalid URL')
})
it('omits protocol and hostname when not applicable', () => {
const r1 = parseUrl({ str: '/', parseQuery: dummyQueryParser })
expect(r1.protocol).toBeUndefined()
expect(r1.hostname).toBeUndefined()
const r2 = parseUrl({ str: '//host', parseQuery: dummyQueryParser })
expect(r2.protocol).toBeUndefined()
expect(r2.hostname).toBe('host')
})
})