|
1 | 1 | import { assert, expect, test, describe } from 'vitest'; |
2 | | -import { exec, parse_route_id, resolve_route } from './routing.js'; |
| 2 | +import { exec, parse_route_id, resolve_route, find_route } from './routing.js'; |
3 | 3 |
|
4 | 4 | describe('parse_route_id', () => { |
5 | 5 | const tests = { |
@@ -359,3 +359,56 @@ describe('resolve_route', () => { |
359 | 359 | ); |
360 | 360 | }); |
361 | 361 | }); |
| 362 | + |
| 363 | +describe('find_route', () => { |
| 364 | + /** @param {string} id */ |
| 365 | + function create_route(id) { |
| 366 | + const { pattern, params } = parse_route_id(id); |
| 367 | + return { id, pattern, params }; |
| 368 | + } |
| 369 | + |
| 370 | + test('finds matching route', () => { |
| 371 | + const routes = [create_route('/blog'), create_route('/blog/[slug]'), create_route('/about')]; |
| 372 | + |
| 373 | + const result = find_route('/blog/hello-world', routes, {}); |
| 374 | + assert.equal(result?.route.id, '/blog/[slug]'); |
| 375 | + assert.deepEqual(result?.params, { slug: 'hello-world' }); |
| 376 | + }); |
| 377 | + |
| 378 | + test('returns first matching route', () => { |
| 379 | + const routes = [create_route('/blog/[slug]'), create_route('/blog/[...rest]')]; |
| 380 | + |
| 381 | + const result = find_route('/blog/hello', routes, {}); |
| 382 | + assert.equal(result?.route.id, '/blog/[slug]'); |
| 383 | + }); |
| 384 | + |
| 385 | + test('returns null for no match', () => { |
| 386 | + const routes = [create_route('/blog'), create_route('/about')]; |
| 387 | + |
| 388 | + const result = find_route('/contact', routes, {}); |
| 389 | + assert.equal(result, null); |
| 390 | + }); |
| 391 | + |
| 392 | + test('respects matchers', () => { |
| 393 | + const routes = [create_route('/blog/[slug=word]'), create_route('/blog/[slug]')]; |
| 394 | + /** @type {Record<string, import('@sveltejs/kit').ParamMatcher>} */ |
| 395 | + const matchers = { |
| 396 | + word: (param) => /^\w+$/.test(param) |
| 397 | + }; |
| 398 | + |
| 399 | + // "hello" matches the word matcher |
| 400 | + const result1 = find_route('/blog/hello', routes, matchers); |
| 401 | + assert.equal(result1?.route.id, '/blog/[slug=word]'); |
| 402 | + |
| 403 | + // "hello-world" doesn't match word matcher, falls through to [slug] |
| 404 | + const result2 = find_route('/blog/hello-world', routes, matchers); |
| 405 | + assert.equal(result2?.route.id, '/blog/[slug]'); |
| 406 | + }); |
| 407 | + |
| 408 | + test('decodes params', () => { |
| 409 | + const routes = [create_route('/blog/[slug]')]; |
| 410 | + |
| 411 | + const result = find_route('/blog/hello%20world', routes, {}); |
| 412 | + assert.equal(result?.params.slug, 'hello world'); |
| 413 | + }); |
| 414 | +}); |
0 commit comments