|
| 1 | +import type { DevEnvironment } from 'vite' |
| 2 | +import { describe, expect, it } from 'vitest' |
| 3 | +import { hashString, normalizeViteImportAnalysisUrl } from './utils' |
| 4 | + |
| 5 | +function createEnvironment(options?: { |
| 6 | + consumer?: 'client' | 'server' |
| 7 | + timestamp?: number |
| 8 | +}) { |
| 9 | + return { |
| 10 | + config: { |
| 11 | + root: '/root', |
| 12 | + consumer: options?.consumer ?? 'server', |
| 13 | + }, |
| 14 | + moduleGraph: { |
| 15 | + getModuleById: () => |
| 16 | + options?.timestamp |
| 17 | + ? { lastHMRTimestamp: options.timestamp } |
| 18 | + : undefined, |
| 19 | + }, |
| 20 | + } as unknown as DevEnvironment |
| 21 | +} |
| 22 | + |
| 23 | +describe(hashString, () => { |
| 24 | + it('returns a stable short sha256 hash', () => { |
| 25 | + expect(hashString('test')).toBe('9f86d081884c') |
| 26 | + expect(hashString('test')).toBe(hashString('test')) |
| 27 | + expect(hashString('other')).not.toBe(hashString('test')) |
| 28 | + }) |
| 29 | +}) |
| 30 | + |
| 31 | +describe(normalizeViteImportAnalysisUrl, () => { |
| 32 | + it('normalizes root files and virtual ids', () => { |
| 33 | + const environment = createEnvironment() |
| 34 | + expect( |
| 35 | + normalizeViteImportAnalysisUrl(environment, '/root/src/action.ts'), |
| 36 | + ).toBe('/src/action.ts') |
| 37 | + expect(normalizeViteImportAnalysisUrl(environment, 'virtual:action')).toBe( |
| 38 | + '/@id/virtual:action', |
| 39 | + ) |
| 40 | + }) |
| 41 | + |
| 42 | + it('injects HMR timestamps for client consumers or when requested', () => { |
| 43 | + const id = '/root/src/action.ts' |
| 44 | + expect( |
| 45 | + normalizeViteImportAnalysisUrl( |
| 46 | + createEnvironment({ consumer: 'client', timestamp: 123 }), |
| 47 | + id, |
| 48 | + ), |
| 49 | + ).toBe('/src/action.ts?t=123') |
| 50 | + expect( |
| 51 | + normalizeViteImportAnalysisUrl( |
| 52 | + createEnvironment({ timestamp: 456 }), |
| 53 | + id, |
| 54 | + { injectHMRTimestamp: true }, |
| 55 | + ), |
| 56 | + ).toBe('/src/action.ts?t=456') |
| 57 | + expect( |
| 58 | + normalizeViteImportAnalysisUrl(createEnvironment({ timestamp: 789 }), id), |
| 59 | + ).toBe('/src/action.ts') |
| 60 | + }) |
| 61 | +}) |
0 commit comments