Debian Codegraph @

tests/unit/matchPath.test.ts

raw
1 import { describe, expect, it } from 'vitest';
2 import { matchPath } from '../../src/index.js';
3 import { pathToRegexp } from 'path-to-regexp';
4
5 describe('matchPath', () => {
6 it('should return false if not matching', () => {
7 const urlMatch = matchPath('/users/:user');
8 const match = urlMatch('/posts/');
9 expect(match).toBe(false);
10 });
11
12 it('should return an object if matching', () => {
13 const urlMatch = matchPath('/users/:user');
14 const match = urlMatch('/users/bob');
15 expect(match).toEqual({
16 path: '/users/bob',
17 index: 0,
18 params: { user: 'bob' }
19 });
20 });
21
22 it('should work with primitive strings', () => {
23 const urlMatch = matchPath<{ user: string }>('/users/:user');
24 const match = urlMatch('/users/bob');
25 const params = !match ? false : match.params;
26 expect(params).toEqual({ user: 'bob' });
27 });
28
29 it('should work with an array of paths', () => {
30 const urlMatch = matchPath<{ user: string }>(['/users/', '/users/:user']);
31
32 const { params: withParams } = urlMatch('/users/bob') || {};
33 expect(withParams).toEqual({ user: 'bob' });
34
35 const { params: withoutParams } = urlMatch('/users/') || {};
36 expect(withoutParams).toEqual({});
37 });
38
39 /**
40 * When passing a regex to `match`, the params in the response are sorted by appearance.
41 * Only helpful for falsy/truthy detection
42 */
43 it('should work with regex', () => {
44 const re = pathToRegexp('/users/:user');
45 const urlMatch = matchPath(re);
46 const { params } = urlMatch('/users/bob') || {};
47 expect(params).toEqual({ '0': 'bob' });
48 });
49
50 it('should throw with malformed paths', () => {
51 // prettier-ignore
52 expect(() => matchPath('/\?user=:user')).toThrowError('[swup] Error parsing path');
53 });
54
55 it('should treat an empty array like an empty string', () => {
56 const urlMatch = matchPath([]);
57
58 expect(urlMatch('')).toEqual({ index: 0, path: '', params: {} });
59
60 expect(urlMatch('/foo/bar')).toBe(false);
61 });
62 });