itube-specs 0.0.707 → 0.0.712

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,57 @@
1
+ // @vitest-environment nuxt
2
+ import { describe, it, expect } from 'vitest';
3
+ import { useFilterScheme } from './use-filter-scheme';
4
+
5
+ const t = (key: string) => key;
6
+
7
+ describe('useFilterScheme', () => {
8
+ it('пустой массив для null', () => {
9
+ const { filterScheme } = useFilterScheme(t, null);
10
+ expect(filterScheme.value).toEqual([]);
11
+ });
12
+
13
+ it('трансформирует группы в схему', () => {
14
+ const groups = [{
15
+ title: 'Age', name: 'age', icon: 'age-icon',
16
+ categories: [
17
+ { title: 'teen', name: 'teen' },
18
+ { title: 'milf', name: 'milf' },
19
+ ],
20
+ }];
21
+ const { filterScheme } = useFilterScheme(t, groups);
22
+ expect(filterScheme.value).toHaveLength(1);
23
+ expect(filterScheme.value[0].label).toBe('Age');
24
+ expect(filterScheme.value[0].items).toEqual([
25
+ { title: 'Teen', value: 'teen' },
26
+ { title: 'Milf', value: 'milf' },
27
+ ]);
28
+ });
29
+
30
+ it('capitalize для multi-word', () => {
31
+ const groups = [{
32
+ title: 'Body', name: 'body', icon: '',
33
+ categories: [{ title: 'big tits', name: 'big-tits' }],
34
+ }];
35
+ const { filterScheme } = useFilterScheme(t, groups);
36
+ expect(filterScheme.value[0].items[0].title).toBe('Big Tits');
37
+ });
38
+
39
+ it('фильтрует пустые группы', () => {
40
+ const groups = [
41
+ { title: 'Empty', name: 'empty', icon: '', categories: [] },
42
+ { title: 'Body', name: 'body', icon: '', categories: [{ title: 'slim', name: 'slim' }] },
43
+ ];
44
+ const { filterScheme } = useFilterScheme(t, groups);
45
+ expect(filterScheme.value).toHaveLength(1);
46
+ expect(filterScheme.value[0].name).toBe('body');
47
+ });
48
+
49
+ it('placeholder из t()', () => {
50
+ const groups = [{
51
+ title: 'Age', name: 'age', icon: '',
52
+ categories: [{ title: 'teen', name: 'teen' }],
53
+ }];
54
+ const { filterScheme } = useFilterScheme(t, groups);
55
+ expect(filterScheme.value[0].placeholder).toBe('choose_category');
56
+ });
57
+ });
@@ -0,0 +1,30 @@
1
+ import { vi, describe, it, expect } from 'vitest';
2
+
3
+ vi.mock('vue-router', () => ({
4
+ useRoute: vi.fn(),
5
+ }));
6
+
7
+ import { useRoute } from 'vue-router';
8
+ import { useGetPureRouteName } from './use-get-pure-route-name';
9
+
10
+ describe('useGetPureRouteName', () => {
11
+ it('убирает суффикс ___en', () => {
12
+ vi.mocked(useRoute).mockReturnValue({ name: 'videos___en' } as any);
13
+ expect(useGetPureRouteName()).toBe('videos');
14
+ });
15
+
16
+ it('убирает суффикс ___zh-hans', () => {
17
+ vi.mocked(useRoute).mockReturnValue({ name: 'user-settings___zh-hans' } as any);
18
+ expect(useGetPureRouteName()).toBe('user-settings');
19
+ });
20
+
21
+ it('оставляет имя без суффикса', () => {
22
+ vi.mocked(useRoute).mockReturnValue({ name: 'videos' } as any);
23
+ expect(useGetPureRouteName()).toBe('videos');
24
+ });
25
+
26
+ it('вложенный роут с суффиксом', () => {
27
+ vi.mocked(useRoute).mockReturnValue({ name: 'user-playlists-id___en' } as any);
28
+ expect(useGetPureRouteName()).toBe('user-playlists-id');
29
+ });
30
+ });
@@ -0,0 +1,45 @@
1
+ import { vi, describe, it, expect } from 'vitest';
2
+
3
+ vi.mock('../runtime', () => ({
4
+ getMultipleQuery: () => ({}),
5
+ }));
6
+
7
+ import { useGetVideosFilterRequest } from './use-get-videos-filter-request';
8
+
9
+ describe('useGetVideosFilterRequest', () => {
10
+ it('всегда возвращает categories_filter_use_and', () => {
11
+ const route = { query: {} } as any;
12
+ const result = useGetVideosFilterRequest(route, [], []);
13
+ expect(result.categories_filter_use_and).toBe(true);
14
+ });
15
+
16
+ it('парсит строковые категории', () => {
17
+ const route = { query: { categories: 'age_teen,body_slim' } } as any;
18
+ const result = useGetVideosFilterRequest(route, [], []);
19
+ expect(result.categories).toEqual(['teen', 'slim']);
20
+ });
21
+
22
+ it('парсит массив категорий', () => {
23
+ const route = { query: { categories: ['age_teen', 'body_slim,body_athletic'] } } as any;
24
+ const result = useGetVideosFilterRequest(route, [], []);
25
+ expect(result.categories).toEqual(['teen', 'slim', 'athletic']);
26
+ });
27
+
28
+ it('убирает префикс группы из категории', () => {
29
+ const route = { query: { categories: 'ethnicity_asian' } } as any;
30
+ const result = useGetVideosFilterRequest(route, [], []);
31
+ expect(result.categories).toEqual(['asian']);
32
+ });
33
+
34
+ it('сохраняет _ в значении категории', () => {
35
+ const route = { query: { categories: 'body_big_tits' } } as any;
36
+ const result = useGetVideosFilterRequest(route, [], []);
37
+ expect(result.categories).toEqual(['big_tits']);
38
+ });
39
+
40
+ it('нет categories при пустом query', () => {
41
+ const route = { query: {} } as any;
42
+ const result = useGetVideosFilterRequest(route, [], []);
43
+ expect(result.categories).toBeUndefined();
44
+ });
45
+ });
@@ -0,0 +1,67 @@
1
+ // @vitest-environment nuxt
2
+ import { describe, it, expect } from 'vitest';
3
+ import { useFilterChipsItems } from './use-model-filter-chips';
4
+
5
+ const t = (key: string) => key;
6
+
7
+ describe('useFilterChipsItems', () => {
8
+ it('пустой массив без filter_ в query', () => {
9
+ const filters = ref([]);
10
+ const route = { query: {} };
11
+ const { chipsItems } = useFilterChipsItems(filters, route, t);
12
+ expect(chipsItems.value).toEqual([]);
13
+ });
14
+
15
+ it('игнорирует не-filter параметры', () => {
16
+ const filters = ref([]);
17
+ const route = { query: { page: '1', sort: 'popular' } };
18
+ const { chipsItems } = useFilterChipsItems(filters, route, t);
19
+ expect(chipsItems.value).toEqual([]);
20
+ });
21
+
22
+ it('создаёт чип из одного фильтра', () => {
23
+ const filters = ref([{
24
+ name: 'hair_color',
25
+ title: 'Hair color',
26
+ options: [
27
+ { name: 'blonde', title: 'Blonde' },
28
+ { name: 'brunette', title: 'Brunette' },
29
+ ],
30
+ }]);
31
+ const route = { query: { filter_hair_color: 'blonde' } };
32
+ const { chipsItems } = useFilterChipsItems(filters, route, t);
33
+ expect(chipsItems.value).toHaveLength(1);
34
+ expect(chipsItems.value[0].title).toBe('Hair color: Blonde');
35
+ expect(chipsItems.value[0].value).toEqual(['filter_hair_color']);
36
+ });
37
+
38
+ it('группирует from/to фильтры', () => {
39
+ const filters = ref([{
40
+ name: 'age',
41
+ title: 'Age',
42
+ options: [
43
+ { name: '18', title: '18' },
44
+ { name: '50', title: '50' },
45
+ ],
46
+ }]);
47
+ const route = { query: { filter_age_from: '18', filter_age_to: '30' } };
48
+ const { chipsItems } = useFilterChipsItems(filters, route, t);
49
+ expect(chipsItems.value).toHaveLength(1);
50
+ expect(chipsItems.value[0].title).toBe('Age: 18 - 30');
51
+ expect(chipsItems.value[0].value).toEqual(['filter_age_from', 'filter_age_to']);
52
+ });
53
+
54
+ it('числовое значение возвращается как есть', () => {
55
+ const filters = ref([{
56
+ name: 'weight',
57
+ title: 'Weight',
58
+ options: [
59
+ { name: '40', title: '40' },
60
+ { name: '120', title: '120' },
61
+ ],
62
+ }]);
63
+ const route = { query: { filter_weight: '65' } };
64
+ const { chipsItems } = useFilterChipsItems(filters, route, t);
65
+ expect(chipsItems.value[0].title).toBe('Weight: 65');
66
+ });
67
+ });
@@ -0,0 +1,74 @@
1
+ // @vitest-environment nuxt
2
+ import { describe, it, expect, beforeEach } from 'vitest';
3
+ import { mockNuxtImport } from '@nuxt/test-utils/runtime';
4
+ import { useSeoLinks } from './use-seo-links';
5
+
6
+ let mockRoute = { path: '/videos', query: {} as Record<string, any> };
7
+
8
+ mockNuxtImport('useRoute', () => () => mockRoute);
9
+
10
+ const mockI18n = {
11
+ locale: { value: 'en' },
12
+ locales: { value: ['en', 'fr', 'de', 'ja', 'zh'] },
13
+ };
14
+
15
+ const mockLocalePath = (path: string, locale: string) =>
16
+ locale === 'en' ? path : `/${locale}${path}`;
17
+
18
+ describe('useSeoLinks', () => {
19
+ beforeEach(() => {
20
+ mockRoute = { path: '/videos', query: {} };
21
+ mockI18n.locale.value = 'en';
22
+ });
23
+
24
+ it('canonical URL', () => {
25
+ const { canonicalUrl } = useSeoLinks('https://example.com', false, mockI18n, mockLocalePath);
26
+ expect(canonicalUrl.value).toBe('https://example.com/videos');
27
+ });
28
+
29
+ it('canonical с query params', () => {
30
+ mockRoute = { path: '/videos', query: { page: '2', sort: 'popular' } };
31
+ const { canonicalUrl } = useSeoLinks('https://example.com', false, mockI18n, mockLocalePath);
32
+ expect(canonicalUrl.value).toContain('page=2');
33
+ expect(canonicalUrl.value).toContain('sort=popular');
34
+ });
35
+
36
+ it('исключает sort при alonePage', () => {
37
+ mockRoute = { path: '/videos', query: { page: '2', sort: 'popular' } };
38
+ const { canonicalUrl } = useSeoLinks('https://example.com', true, mockI18n, mockLocalePath);
39
+ expect(canonicalUrl.value).toContain('page=2');
40
+ expect(canonicalUrl.value).not.toContain('sort');
41
+ });
42
+
43
+ it('alternate links для всех локалей', () => {
44
+ const { alternateLinks } = useSeoLinks('https://example.com', false, mockI18n, mockLocalePath);
45
+ const hreflangs = alternateLinks.value.map(l => l.hreflang);
46
+ expect(hreflangs).toContain('en');
47
+ expect(hreflangs).toContain('fr');
48
+ expect(hreflangs).toContain('de');
49
+ expect(hreflangs).toContain('ja-JP');
50
+ expect(hreflangs).toContain('zh-CN');
51
+ expect(hreflangs).toContain('x-default');
52
+ });
53
+
54
+ it('ja маппится в ja-JP', () => {
55
+ const { alternateLinks } = useSeoLinks('https://example.com', false, mockI18n, mockLocalePath);
56
+ const jaLink = alternateLinks.value.find(l => l.hreflang === 'ja-JP');
57
+ expect(jaLink).toBeDefined();
58
+ expect(jaLink!.href).toContain('/ja/videos');
59
+ });
60
+
61
+ it('x-default указывает на en', () => {
62
+ const { alternateLinks } = useSeoLinks('https://example.com', false, mockI18n, mockLocalePath);
63
+ const xDefault = alternateLinks.value.find(l => l.hreflang === 'x-default');
64
+ expect(xDefault!.href).toBe('https://example.com/videos');
65
+ });
66
+
67
+ it('игнорирует неразрешённые query params', () => {
68
+ mockRoute = { path: '/videos', query: { page: '1', foo: 'bar', categories: 'teen' } };
69
+ const { canonicalUrl } = useSeoLinks('https://example.com', false, mockI18n, mockLocalePath);
70
+ expect(canonicalUrl.value).toContain('page=1');
71
+ expect(canonicalUrl.value).toContain('categories=teen');
72
+ expect(canonicalUrl.value).not.toContain('foo');
73
+ });
74
+ });
@@ -0,0 +1,36 @@
1
+ // @vitest-environment nuxt
2
+ import { vi, describe, it, expect } from 'vitest';
3
+
4
+ vi.mock('vue-router', async (importOriginal) => {
5
+ const mod = await importOriginal<typeof import('vue-router')>();
6
+ return { ...mod, useRoute: vi.fn() };
7
+ });
8
+
9
+ import { useRoute } from 'vue-router';
10
+ import { useSlug } from './use-slug';
11
+
12
+ describe('useSlug', () => {
13
+ it('конвертирует kebab-case slug', () => {
14
+ vi.mocked(useRoute).mockReturnValue({ params: { slug: 'john-doe' } } as any);
15
+ const slug = useSlug();
16
+ expect(slug.value).toBe('john doe');
17
+ });
18
+
19
+ it('пустая строка если slug отсутствует', () => {
20
+ vi.mocked(useRoute).mockReturnValue({ params: {} } as any);
21
+ const slug = useSlug();
22
+ expect(slug.value).toBe('');
23
+ });
24
+
25
+ it('кастомное имя параметра', () => {
26
+ vi.mocked(useRoute).mockReturnValue({ params: { name: 'big-tits' } } as any);
27
+ const slug = useSlug('name');
28
+ expect(slug.value).toBe('big tits');
29
+ });
30
+
31
+ it('slug с подчёркиваниями', () => {
32
+ vi.mocked(useRoute).mockReturnValue({ params: { slug: 'some_thing' } } as any);
33
+ const slug = useSlug();
34
+ expect(slug.value).toBe('some-thing');
35
+ });
36
+ });
@@ -0,0 +1,64 @@
1
+ // @vitest-environment nuxt
2
+ import { describe, it, expect, beforeEach, afterEach, vi } from 'vitest';
3
+ import { useSnackbar } from './use-snackbar';
4
+
5
+ describe('useSnackbar', () => {
6
+ beforeEach(() => {
7
+ useNuxtApp().payload.state = {};
8
+ vi.useFakeTimers();
9
+ const { resetSnackbar } = useSnackbar();
10
+ resetSnackbar();
11
+ });
12
+
13
+ afterEach(() => {
14
+ vi.useRealTimers();
15
+ });
16
+
17
+ it('дефолтное состояние', () => {
18
+ const { snackbarTheme, snackbarText, snackbarIcon, snackbarTimer } = useSnackbar();
19
+ expect(snackbarTheme.value).toBe('success');
20
+ expect(snackbarText.value).toBe('');
21
+ expect(snackbarIcon.value).toBe('check');
22
+ expect(snackbarTimer.value).toBe(2000);
23
+ });
24
+
25
+ it('setErrorState устанавливает ошибку', () => {
26
+ const { setErrorState, snackbarTheme, snackbarIcon, snackbarTimer, snackbarText } = useSnackbar();
27
+ setErrorState({ message: 'Something failed' });
28
+ expect(snackbarTheme.value).toBe('error');
29
+ expect(snackbarIcon.value).toBe('close');
30
+ expect(snackbarTimer.value).toBe(4000);
31
+ expect(snackbarText.value).toBe('Something failed');
32
+ });
33
+
34
+ it('showErrorSnack показывает и авто-сбрасывает', () => {
35
+ const { showErrorSnack, snackbarText, snackbarTheme } = useSnackbar();
36
+ showErrorSnack('Error!');
37
+ expect(snackbarText.value).toBe('Error!');
38
+ expect(snackbarTheme.value).toBe('error');
39
+
40
+ vi.advanceTimersByTime(4000);
41
+ expect(snackbarText.value).toBe('');
42
+ expect(snackbarTheme.value).toBe('success');
43
+ });
44
+
45
+ it('повторный showErrorSnack сбрасывает предыдущий таймер', () => {
46
+ const { showErrorSnack, snackbarText } = useSnackbar();
47
+ showErrorSnack('First');
48
+ vi.advanceTimersByTime(2000);
49
+ showErrorSnack('Second');
50
+ expect(snackbarText.value).toBe('Second');
51
+
52
+ vi.advanceTimersByTime(4000);
53
+ expect(snackbarText.value).toBe('');
54
+ });
55
+
56
+ it('resetSnackbar сбрасывает всё', () => {
57
+ const { showErrorSnack, resetSnackbar, snackbarText, snackbarTheme, snackbarIcon } = useSnackbar();
58
+ showErrorSnack('Error');
59
+ resetSnackbar();
60
+ expect(snackbarText.value).toBe('');
61
+ expect(snackbarTheme.value).toBe('success');
62
+ expect(snackbarIcon.value).toBe('check');
63
+ });
64
+ });
package/package.json CHANGED
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "name": "itube-specs",
3
3
  "type": "module",
4
- "version": "0.0.707",
4
+ "version": "0.0.712",
5
5
  "main": "./nuxt.config.ts",
6
6
  "types": "./types/index.d.ts",
7
7
  "scripts": {
@@ -0,0 +1,38 @@
1
+ import { describe, it, expect } from 'vitest';
2
+ import { convertDateToTimestamp } from './convert-date-to-timestamp';
3
+
4
+ const c = convertDateToTimestamp();
5
+
6
+ describe('convertDateToTimestamp', () => {
7
+ describe('toUnix', () => {
8
+ it('валидная дата', () => {
9
+ expect(c.toUnix('2025-01-01')).toBe(Date.UTC(2025, 0, 1) / 1000);
10
+ });
11
+
12
+ it('начало эпохи', () => {
13
+ expect(c.toUnix('1970-01-01')).toBe(0);
14
+ });
15
+
16
+ it('невалидная дата → null', () => {
17
+ expect(c.toUnix('invalid')).toBe(null);
18
+ });
19
+ });
20
+
21
+ describe('fromUnix', () => {
22
+ it('timestamp → дата', () => {
23
+ expect(c.fromUnix(0)).toBe('1970-01-01');
24
+ });
25
+
26
+ it('конкретная дата', () => {
27
+ const ts = Date.UTC(2024, 2, 5) / 1000;
28
+ expect(c.fromUnix(ts)).toBe('2024-03-05');
29
+ });
30
+ });
31
+
32
+ describe('roundtrip', () => {
33
+ it('toUnix → fromUnix', () => {
34
+ const date = '2024-03-05';
35
+ expect(c.fromUnix(c.toUnix(date)!)).toBe(date);
36
+ });
37
+ });
38
+ });
@@ -0,0 +1,29 @@
1
+ import { describe, it, expect } from 'vitest';
2
+ import { convertSnakeKeysToCamel } from './convert-snake-keys-to-camel';
3
+
4
+ describe('convertSnakeKeysToCamel', () => {
5
+ it('простой объект', () => {
6
+ expect(convertSnakeKeysToCamel({ user_name: 'John', is_active: true }))
7
+ .toEqual({ userName: 'John', isActive: true });
8
+ });
9
+
10
+ it('вложенный объект', () => {
11
+ expect(convertSnakeKeysToCamel({ user_info: { first_name: 'John' } }))
12
+ .toEqual({ userInfo: { firstName: 'John' } });
13
+ });
14
+
15
+ it('массив объектов', () => {
16
+ expect(convertSnakeKeysToCamel([{ video_id: 1 }, { video_id: 2 }]))
17
+ .toEqual([{ videoId: 1 }, { videoId: 2 }]);
18
+ });
19
+
20
+ it('примитив возвращается как есть', () => {
21
+ expect(convertSnakeKeysToCamel('hello')).toBe('hello');
22
+ expect(convertSnakeKeysToCamel(42)).toBe(42);
23
+ expect(convertSnakeKeysToCamel(null)).toBe(null);
24
+ });
25
+
26
+ it('ключ без подчёркиваний', () => {
27
+ expect(convertSnakeKeysToCamel({ name: 'John' })).toEqual({ name: 'John' });
28
+ });
29
+ });
@@ -0,0 +1,78 @@
1
+ import { describe, it, expect } from 'vitest';
2
+ import { convertString } from './convert-string';
3
+
4
+ const s = convertString();
5
+
6
+ describe('convertString', () => {
7
+ describe('toSlug', () => {
8
+ it('пробелы → дефисы', () => {
9
+ expect(s.toSlug('Big Tits')).toBe('big-tits');
10
+ });
11
+
12
+ it('дефисы → подчёркивания', () => {
13
+ expect(s.toSlug('A-B')).toBe('a_b');
14
+ });
15
+
16
+ it('подчёркивания → тильда', () => {
17
+ expect(s.toSlug('a_b')).toBe('a~b');
18
+ });
19
+ });
20
+
21
+ describe('fromSlug', () => {
22
+ it('дефисы → пробелы', () => {
23
+ expect(s.fromSlug('big-tits')).toBe('big tits');
24
+ });
25
+
26
+ it('подчёркивания → дефисы', () => {
27
+ expect(s.fromSlug('a_b')).toBe('a-b');
28
+ });
29
+
30
+ it('тильда → подчёркивание', () => {
31
+ expect(s.fromSlug('a~b')).toBe('a_b');
32
+ });
33
+ });
34
+
35
+ describe('toSnakeCase', () => {
36
+ it('camelCase', () => {
37
+ expect(s.toSnakeCase('bigTits')).toBe('big_tits');
38
+ });
39
+
40
+ it('пробелы', () => {
41
+ expect(s.toSnakeCase('big tits')).toBe('big_tits');
42
+ });
43
+
44
+ it('дефисы', () => {
45
+ expect(s.toSnakeCase('big-tits')).toBe('big_tits');
46
+ });
47
+ });
48
+
49
+ describe('toKebabCase', () => {
50
+ it('camelCase', () => {
51
+ expect(s.toKebabCase('bigTits')).toBe('big-tits');
52
+ });
53
+
54
+ it('подчёркивания', () => {
55
+ expect(s.toKebabCase('big_tits')).toBe('big-tits');
56
+ });
57
+
58
+ it('пробелы', () => {
59
+ expect(s.toKebabCase('big tits')).toBe('big-tits');
60
+ });
61
+ });
62
+
63
+ describe('toCapitalize', () => {
64
+ it('одно слово', () => {
65
+ expect(s.toCapitalize('teen')).toBe('Teen');
66
+ });
67
+
68
+ it('несколько слов', () => {
69
+ expect(s.toCapitalize('big tits')).toBe('Big Tits');
70
+ });
71
+ });
72
+
73
+ describe('roundtrip', () => {
74
+ it('toSlug → fromSlug', () => {
75
+ expect(s.fromSlug(s.toSlug('Big Tits'))).toBe('big tits');
76
+ });
77
+ });
78
+ });
@@ -0,0 +1,33 @@
1
+ import { describe, it, expect } from 'vitest';
2
+ import { groupObjectsByFirstLetter } from './group-objects-by-first-letter';
3
+
4
+ describe('groupObjectsByFirstLetter', () => {
5
+ const items = [
6
+ { name: 'Alice' },
7
+ { name: 'Anna' },
8
+ { name: 'Bob' },
9
+ { name: '123test' },
10
+ ];
11
+
12
+ it('группирует по первой букве', () => {
13
+ const result = groupObjectsByFirstLetter(items, 'name');
14
+ expect(result['A']).toHaveLength(2);
15
+ expect(result['B']).toHaveLength(1);
16
+ });
17
+
18
+ it('цифры попадают в POST', () => {
19
+ const result = groupObjectsByFirstLetter(items, 'name');
20
+ expect(result['POST']).toHaveLength(1);
21
+ expect(result['POST'][0]).toEqual({ name: '123test' });
22
+ });
23
+
24
+ it('кастомный nonLetterKey', () => {
25
+ const result = groupObjectsByFirstLetter(items, 'name', 'OTHER');
26
+ expect(result['OTHER']).toHaveLength(1);
27
+ });
28
+
29
+ it('пустой массив', () => {
30
+ const result = groupObjectsByFirstLetter([], 'name');
31
+ expect(result).toEqual({});
32
+ });
33
+ });
@@ -0,0 +1,18 @@
1
+ import { describe, it, expect } from 'vitest';
2
+ import { formatDate } from './format-date';
3
+
4
+ describe('formatDate', () => {
5
+ it('обычная дата', () => {
6
+ // 2025-01-15 00:00:00 UTC
7
+ expect(formatDate(1736899200)).toBe('15.01.2025');
8
+ });
9
+
10
+ it('начало эпохи', () => {
11
+ expect(formatDate(0)).toBe('01.01.1970');
12
+ });
13
+
14
+ it('с padding нулей', () => {
15
+ // 2024-03-05 UTC
16
+ expect(formatDate(1709596800)).toBe('05.03.2024');
17
+ });
18
+ });
@@ -0,0 +1,24 @@
1
+ import { describe, it, expect } from 'vitest';
2
+ import { formatNumber } from './format-number';
3
+
4
+ describe('formatNumber', () => {
5
+ it('тысячи', () => {
6
+ expect(formatNumber(10400)).toBe('10.4K');
7
+ });
8
+
9
+ it('миллионы', () => {
10
+ expect(formatNumber(1500000)).toBe('1.5M');
11
+ });
12
+
13
+ it('маленькое число без сокращения', () => {
14
+ expect(formatNumber(999)).toBe('999');
15
+ });
16
+
17
+ it('ноль', () => {
18
+ expect(formatNumber(0)).toBe('0');
19
+ });
20
+
21
+ it('ровно тысяча', () => {
22
+ expect(formatNumber(1000)).toBe('1K');
23
+ });
24
+ });
@@ -0,0 +1,49 @@
1
+ import { describe, it, expect, vi, beforeEach, afterEach } from 'vitest';
2
+ import { formatTimeAgo } from './format-time-ago';
3
+
4
+ const t = (key: string) => key;
5
+
6
+ describe('formatTimeAgo', () => {
7
+ beforeEach(() => {
8
+ vi.useFakeTimers();
9
+ vi.setSystemTime(new Date('2025-06-15T12:00:00Z'));
10
+ });
11
+
12
+ afterEach(() => {
13
+ vi.useRealTimers();
14
+ });
15
+
16
+ const now = () => Math.floor(Date.now() / 1000);
17
+
18
+ it('сегодня', () => {
19
+ expect(formatTimeAgo(now(), t)).toBe('today');
20
+ });
21
+
22
+ it('1 день назад', () => {
23
+ expect(formatTimeAgo(now() - 86400, t)).toBe('day_ago');
24
+ });
25
+
26
+ it('5 дней назад', () => {
27
+ expect(formatTimeAgo(now() - 5 * 86400, t)).toBe('5 days_ago');
28
+ });
29
+
30
+ it('29 дней назад', () => {
31
+ expect(formatTimeAgo(now() - 29 * 86400, t)).toBe('29 days_ago');
32
+ });
33
+
34
+ it('1 месяц', () => {
35
+ expect(formatTimeAgo(now() - 31 * 86400, t)).toBe('1 month ago');
36
+ });
37
+
38
+ it('3 месяца — plural', () => {
39
+ expect(formatTimeAgo(now() - 90 * 86400, t)).toBe('3 months ago');
40
+ });
41
+
42
+ it('1 год', () => {
43
+ expect(formatTimeAgo(now() - 366 * 86400, t)).toBe('1 year ago');
44
+ });
45
+
46
+ it('2 года — plural', () => {
47
+ expect(formatTimeAgo(now() - 730 * 86400, t)).toBe('2 years ago');
48
+ });
49
+ });
@@ -0,0 +1,24 @@
1
+ import { describe, it, expect } from 'vitest';
2
+ import { formatTime } from './format-time';
3
+
4
+ describe('formatTime', () => {
5
+ it('только секунды', () => {
6
+ expect(formatTime(5)).toBe('00:05');
7
+ });
8
+
9
+ it('минуты и секунды', () => {
10
+ expect(formatTime(65)).toBe('01:05');
11
+ });
12
+
13
+ it('часы, минуты, секунды', () => {
14
+ expect(formatTime(3661)).toBe('01:01:01');
15
+ });
16
+
17
+ it('ноль', () => {
18
+ expect(formatTime(0)).toBe('00:00');
19
+ });
20
+
21
+ it('ровно час', () => {
22
+ expect(formatTime(3600)).toBe('01:00:00');
23
+ });
24
+ });
@@ -0,0 +1,24 @@
1
+ import { describe, it, expect } from 'vitest';
2
+ import { getDuration } from './get-duration';
3
+
4
+ describe('getDuration', () => {
5
+ it('только секунды', () => {
6
+ expect(getDuration(45)).toBe('00:45');
7
+ });
8
+
9
+ it('минуты и секунды', () => {
10
+ expect(getDuration(125)).toBe('02:05');
11
+ });
12
+
13
+ it('с часами', () => {
14
+ expect(getDuration(3661)).toBe('01:01:01');
15
+ });
16
+
17
+ it('ноль', () => {
18
+ expect(getDuration(0)).toBe('00:00');
19
+ });
20
+
21
+ it('ровно час', () => {
22
+ expect(getDuration(3600)).toBe('01:00:00');
23
+ });
24
+ });
@@ -0,0 +1,30 @@
1
+ import { describe, it, expect } from 'vitest';
2
+ import { getMonth } from './get-month';
3
+
4
+ const t = (key: string) => key;
5
+
6
+ describe('getMonth', () => {
7
+ it('январь = 0', () => {
8
+ expect(getMonth(t, 0)).toBe('january');
9
+ });
10
+
11
+ it('декабрь = 11', () => {
12
+ expect(getMonth(t, 11)).toBe('december');
13
+ });
14
+
15
+ it('июнь = 5', () => {
16
+ expect(getMonth(t, 5)).toBe('june');
17
+ });
18
+
19
+ it('undefined → декабрь (дефолт)', () => {
20
+ expect(getMonth(t)).toBe('december');
21
+ });
22
+
23
+ it('отрицательное число → декабрь', () => {
24
+ expect(getMonth(t, -1)).toBe('december');
25
+ });
26
+
27
+ it('число >= 12 → декабрь', () => {
28
+ expect(getMonth(t, 12)).toBe('december');
29
+ });
30
+ });
@@ -0,0 +1,59 @@
1
+ import { describe, it, expect } from 'vitest';
2
+ import { normalizeUrl } from './normalize-url';
3
+
4
+ describe('normalizeUrl', () => {
5
+ it('удаляет page=1', () => {
6
+ const result = normalizeUrl({ path: '/videos', query: { page: '1' } });
7
+ expect(result.query.page).toBeUndefined();
8
+ });
9
+
10
+ it('сохраняет page=2', () => {
11
+ const result = normalizeUrl({ path: '/videos', query: { page: '2' } });
12
+ expect(result.query.page).toBe('2');
13
+ });
14
+
15
+ it('удаляет sort=trending', () => {
16
+ const result = normalizeUrl({ path: '/videos', query: { sort: 'trending' } });
17
+ expect(result.query.sort).toBeUndefined();
18
+ });
19
+
20
+ it('сохраняет sort=popular', () => {
21
+ const result = normalizeUrl({ path: '/videos', query: { sort: 'popular' } });
22
+ expect(result.query.sort).toBe('popular');
23
+ });
24
+
25
+ it('удаляет пустые значения', () => {
26
+ const result = normalizeUrl({ path: '/', query: { a: '', b: null as any, c: 'ok' } });
27
+ expect(result.query).toEqual({ c: 'ok' });
28
+ });
29
+
30
+ it('lowercase путь', () => {
31
+ const result = normalizeUrl({ path: '/Videos/BIG', query: {} });
32
+ expect(result.path).toBe('/videos/big');
33
+ });
34
+
35
+ it('lowercase query', () => {
36
+ const result = normalizeUrl({ path: '/', query: { Sort: 'Popular' } });
37
+ expect(result.query).toEqual({ sort: 'popular' });
38
+ });
39
+
40
+ it('%20 и пробелы → дефисы', () => {
41
+ const result = normalizeUrl({ path: '/big%20tits videos', query: {} });
42
+ expect(result.path).toBe('/big-tits-videos');
43
+ });
44
+
45
+ it('убирает двойные дефисы', () => {
46
+ const result = normalizeUrl({ path: '/big--tits', query: {} });
47
+ expect(result.path).toBe('/big-tits');
48
+ });
49
+
50
+ it('убирает trailing slash', () => {
51
+ const result = normalizeUrl({ path: '/videos/', query: {} });
52
+ expect(result.path).toBe('/videos');
53
+ });
54
+
55
+ it('не убирает /', () => {
56
+ const result = normalizeUrl({ path: '/', query: {} });
57
+ expect(result.path).toBe('/');
58
+ });
59
+ });
@@ -0,0 +1,36 @@
1
+ import { describe, it, expect } from 'vitest';
2
+ import { parseApiError } from './parse-api-error';
3
+
4
+ describe('parseApiError', () => {
5
+ it('error.message', () => {
6
+ expect(parseApiError({ message: 'Not found' })).toBe('Not found');
7
+ });
8
+
9
+ it('response._data как объект', () => {
10
+ const error = { response: { _data: { error: 'Bad request' } } };
11
+ expect(parseApiError(error)).toBe('Bad request');
12
+ });
13
+
14
+ it('response._data как JSON строка', () => {
15
+ const error = { response: { _data: '{"error":"Forbidden"}' } };
16
+ expect(parseApiError(error)).toBe('Forbidden');
17
+ });
18
+
19
+ it('вложенный data.error', () => {
20
+ const error = { response: { _data: { data: { error: 'Validation failed' } } } };
21
+ expect(parseApiError(error)).toBe('Validation failed');
22
+ });
23
+
24
+ it('массив ошибок — первый элемент', () => {
25
+ const error = { response: { _data: { error: ['Field required', 'Too short'] } } };
26
+ expect(parseApiError(error)).toBe('Field required');
27
+ });
28
+
29
+ it('fallback при null', () => {
30
+ expect(parseApiError(null)).toBe('Unknown error occurred.');
31
+ });
32
+
33
+ it('fallback при пустом объекте', () => {
34
+ expect(parseApiError({})).toBe('Unknown error occurred.');
35
+ });
36
+ });
@@ -0,0 +1,32 @@
1
+ import { describe, it, expect } from 'vitest';
2
+ import { validateEmail } from './validate-email';
3
+
4
+ describe('validateEmail', () => {
5
+ it('валидный email', () => {
6
+ expect(validateEmail('user@example.com')).toBe(true);
7
+ });
8
+
9
+ it('с точкой в имени', () => {
10
+ expect(validateEmail('first.last@example.com')).toBe(true);
11
+ });
12
+
13
+ it('с поддоменом', () => {
14
+ expect(validateEmail('user@mail.example.com')).toBe(true);
15
+ });
16
+
17
+ it('без @', () => {
18
+ expect(validateEmail('userexample.com')).toBe(false);
19
+ });
20
+
21
+ it('без домена', () => {
22
+ expect(validateEmail('user@')).toBe(false);
23
+ });
24
+
25
+ it('пустая строка', () => {
26
+ expect(validateEmail('')).toBe(false);
27
+ });
28
+
29
+ it('пробелы', () => {
30
+ expect(validateEmail('user @example.com')).toBe(false);
31
+ });
32
+ });
@@ -0,0 +1,20 @@
1
+ import { describe, it, expect } from 'vitest';
2
+ import { validatePassword } from './validate-password';
3
+
4
+ describe('validatePassword', () => {
5
+ it('длина > 4 — валиден', () => {
6
+ expect(validatePassword('12345')).toBe(true);
7
+ });
8
+
9
+ it('длина 4 — невалиден', () => {
10
+ expect(validatePassword('1234')).toBe(false);
11
+ });
12
+
13
+ it('длина 1 — невалиден', () => {
14
+ expect(validatePassword('a')).toBe(false);
15
+ });
16
+
17
+ it('длинный пароль', () => {
18
+ expect(validatePassword('super_secure_password_123')).toBe(true);
19
+ });
20
+ });
@@ -0,0 +1,32 @@
1
+ import { describe, it, expect } from 'vitest';
2
+ import { validatePhone } from './validate-phone';
3
+
4
+ describe('validatePhone', () => {
5
+ it('международный формат', () => {
6
+ expect(validatePhone('+79001234567')).toBe(true);
7
+ });
8
+
9
+ it('с дефисами', () => {
10
+ expect(validatePhone('8-900-123-45-67')).toBe(true);
11
+ });
12
+
13
+ it('с пробелами', () => {
14
+ expect(validatePhone('+7 900 123 4567')).toBe(true);
15
+ });
16
+
17
+ it('со скобками', () => {
18
+ expect(validatePhone('+7(900)1234567')).toBe(true);
19
+ });
20
+
21
+ it('слишком короткий', () => {
22
+ expect(validatePhone('12345')).toBe(false);
23
+ });
24
+
25
+ it('пустая строка', () => {
26
+ expect(validatePhone('')).toBe(false);
27
+ });
28
+
29
+ it('буквы', () => {
30
+ expect(validatePhone('phone123')).toBe(false);
31
+ });
32
+ });
@@ -0,0 +1,36 @@
1
+ import { describe, it, expect } from 'vitest';
2
+ import { validateUsername } from './validate-username';
3
+
4
+ describe('validateUsername', () => {
5
+ it('латиница', () => {
6
+ expect(validateUsername('john')).toBe(true);
7
+ });
8
+
9
+ it('с цифрами', () => {
10
+ expect(validateUsername('user123')).toBe(true);
11
+ });
12
+
13
+ it('с подчёркиванием и дефисом', () => {
14
+ expect(validateUsername('my_user-name')).toBe(true);
15
+ });
16
+
17
+ it('1 символ — невалиден', () => {
18
+ expect(validateUsername('a')).toBe(false);
19
+ });
20
+
21
+ it('21 символ — невалиден', () => {
22
+ expect(validateUsername('a'.repeat(21))).toBe(false);
23
+ });
24
+
25
+ it('20 символов — валиден', () => {
26
+ expect(validateUsername('a'.repeat(20))).toBe(true);
27
+ });
28
+
29
+ it('пустая строка', () => {
30
+ expect(validateUsername('')).toBe(false);
31
+ });
32
+
33
+ it('спецсимволы', () => {
34
+ expect(validateUsername('user@name')).toBe(false);
35
+ });
36
+ });