|
| 1 | +import { describe, expect, it } from 'vitest' |
| 2 | +import routerOptions from '../../../app/router.options' |
| 3 | + |
| 4 | +type ScrollBehavior = NonNullable<typeof routerOptions.scrollBehavior> |
| 5 | +type RouteArg = Parameters<ScrollBehavior>[0] |
| 6 | + |
| 7 | +function createRoute(overrides: Partial<RouteArg> = {}) { |
| 8 | + return { |
| 9 | + path: '/', |
| 10 | + hash: '', |
| 11 | + query: {}, |
| 12 | + meta: {}, |
| 13 | + ...overrides, |
| 14 | + } as RouteArg |
| 15 | +} |
| 16 | + |
| 17 | +describe('router scrollBehavior', () => { |
| 18 | + it('restores saved position when available', () => { |
| 19 | + const savedPosition = { left: 12, top: 345 } |
| 20 | + |
| 21 | + expect(routerOptions.scrollBehavior(createRoute(), createRoute(), savedPosition)).toEqual( |
| 22 | + savedPosition, |
| 23 | + ) |
| 24 | + }) |
| 25 | + |
| 26 | + it('preserves scroll on query-only updates for pages that opt in', () => { |
| 27 | + const to = createRoute({ |
| 28 | + path: '/compare', |
| 29 | + query: { packages: 'vue,nuxt', facets: 'downloads,license' }, |
| 30 | + meta: { preserveScrollOnQuery: true }, |
| 31 | + }) |
| 32 | + const from = createRoute({ |
| 33 | + path: '/compare', |
| 34 | + query: { packages: 'vue', facets: 'downloads' }, |
| 35 | + meta: { preserveScrollOnQuery: true }, |
| 36 | + }) |
| 37 | + |
| 38 | + expect(routerOptions.scrollBehavior(to, from, null)).toBe(false) |
| 39 | + }) |
| 40 | + |
| 41 | + it('does not preserve scroll on query-only updates without opt-in', () => { |
| 42 | + const to = createRoute({ |
| 43 | + path: '/compare', |
| 44 | + query: { packages: 'vue,nuxt', facets: 'downloads,license' }, |
| 45 | + }) |
| 46 | + const from = createRoute({ |
| 47 | + path: '/compare', |
| 48 | + query: { packages: 'vue', facets: 'downloads' }, |
| 49 | + }) |
| 50 | + |
| 51 | + expect(routerOptions.scrollBehavior(to, from, null)).toEqual({ left: 0, top: 0 }) |
| 52 | + }) |
| 53 | + |
| 54 | + it('scrolls to hash anchors', () => { |
| 55 | + const to = createRoute({ |
| 56 | + hash: '#section-function', |
| 57 | + meta: { scrollMargin: 96 }, |
| 58 | + }) |
| 59 | + |
| 60 | + expect(routerOptions.scrollBehavior(to, createRoute(), null)).toEqual({ |
| 61 | + el: '#section-function', |
| 62 | + behavior: 'smooth', |
| 63 | + top: 96, |
| 64 | + }) |
| 65 | + }) |
| 66 | + |
| 67 | + it('scrolls to top for regular navigations', () => { |
| 68 | + const to = createRoute({ path: '/compare', meta: { preserveScrollOnQuery: true } }) |
| 69 | + const from = createRoute({ path: '/search' }) |
| 70 | + |
| 71 | + expect(routerOptions.scrollBehavior(to, from, null)).toEqual({ left: 0, top: 0 }) |
| 72 | + }) |
| 73 | +}) |
0 commit comments