|
| 1 | +import {path} from '@packula/router-path' |
| 2 | + |
| 3 | +import {any} from '../../src/repeating' |
| 4 | + |
| 5 | +describe('any()', () => { |
| 6 | + it('should allow building from an array', () => { |
| 7 | + const subject = path`/a${any('p1')}/b` |
| 8 | + |
| 9 | + expect(subject.build({p1: ['wx', 'yz']})).toBe('/a/wx/yz/b') |
| 10 | + expect(subject.build({p1: []})).toBe('/a/b') |
| 11 | + }) |
| 12 | + |
| 13 | + it('should allow building with alternate expressions, separators, and prefixes', () => { |
| 14 | + expect(path`/a${any('p1', /x/, '<sep>')}/b`.build({p1: ['wx', 'yz']})).toBe('/a<sep>wx<sep>yz/b') |
| 15 | + expect(path`/a${any('p1', /x/, '<sep>', '<pre>')}/b`.build({p1: ['wx', 'yz']})).toBe('/a<pre>wx<sep>yz/b') |
| 16 | + }) |
| 17 | + |
| 18 | + it('should match zero to many path segments', () => { |
| 19 | + const subject = path`/a${any('p1')}/b` |
| 20 | + |
| 21 | + expect(subject.match('/a/b')).toStrictEqual({p1: []}) |
| 22 | + expect(subject.match('/a/xy/b')).toStrictEqual({p1: ['xy']}) |
| 23 | + expect(subject.match('/a/wx/yz/b')).toStrictEqual({p1: ['wx', 'yz']}) |
| 24 | + }) |
| 25 | + |
| 26 | + it('should allow matching with alternate expressions, separators, and prefixes', () => { |
| 27 | + const subjectA = path`/a${any('p1', /xy|yz|[ππ]/u, '<sep>')}/b` |
| 28 | + |
| 29 | + expect(subjectA.match('/a/b')).toStrictEqual({p1: []}) |
| 30 | + expect(subjectA.match('/a<sep>xy/b')).toStrictEqual({p1: ['xy']}) |
| 31 | + expect(subjectA.match('/a<sep>xy<sep>yz<sep>π<sep>π/b')).toStrictEqual({p1: ['xy', 'yz', 'π', 'π']}) |
| 32 | + |
| 33 | + const subjectB = path`/a${any('p1', /xy|yz|[ππ]/u, '<sep>', '<pre>')}/b` |
| 34 | + |
| 35 | + expect(subjectB.match('/a/b')).toStrictEqual({p1: []}) |
| 36 | + expect(subjectB.match('/a<pre>xy/b')).toStrictEqual({p1: ['xy']}) |
| 37 | + expect(subjectB.match('/a<pre>xy<sep>yz<sep>π<sep>π/b')).toStrictEqual({p1: ['xy', 'yz', 'π', 'π']}) |
| 38 | + }) |
| 39 | + |
| 40 | + it('should not match empty path segments', () => { |
| 41 | + const subject = path`/a${any('p1')}/b` |
| 42 | + |
| 43 | + expect(subject.match('/a//b')).toBeUndefined() |
| 44 | + expect(subject.match('/a///b')).toBeUndefined() |
| 45 | + }) |
| 46 | + |
| 47 | + it('should complain about keys being possibly undefined', () => { |
| 48 | + const result = path`/a${any('p1')}/b`.match('/a/xy/b') |
| 49 | + |
| 50 | + expect(result).toBeDefined() |
| 51 | + if (result == null) return // TypeScript guard |
| 52 | + |
| 53 | + // @ts-expect-error |
| 54 | + expect(result.p1[0].toUpperCase()).toBe('XY') |
| 55 | + }) |
| 56 | +}) |
0 commit comments