|
| 1 | +import { describe, expect, it } from 'vitest' |
| 2 | +import Unimport from '../src/unplugin' |
| 3 | + |
| 4 | +const id = '/src/a.ts' |
| 5 | +const code = [ |
| 6 | + 'export function classify(n) {', |
| 7 | + ' const h = helper();', |
| 8 | + ' if (n > 10) return h.big;', |
| 9 | + ' if (n > 0) return h.small;', |
| 10 | + ' return h.zero;', |
| 11 | + '}', |
| 12 | + '', |
| 13 | +].join('\n') |
| 14 | + |
| 15 | +function createPlugin() { |
| 16 | + return Unimport.raw( |
| 17 | + { |
| 18 | + imports: [{ name: 'helper', from: 'my-lib' }], |
| 19 | + }, |
| 20 | + { framework: 'vite', versions: {} }, |
| 21 | + ) |
| 22 | +} |
| 23 | + |
| 24 | +async function transform(input: string, fileId = id) { |
| 25 | + const hook = createPlugin().transform |
| 26 | + const handler = typeof hook === 'function' ? hook : hook!.handler |
| 27 | + return handler.call( |
| 28 | + {} as never, |
| 29 | + input, |
| 30 | + fileId, |
| 31 | + ) as Promise<{ code: string, map: { mappings: string, sources: string[] } } | undefined> |
| 32 | +} |
| 33 | + |
| 34 | +/** |
| 35 | + * Sourcemap `mappings` are grouped by generated line (`;`), then by segment |
| 36 | + * (`,`). A line-only map has one segment per line, all at column 0. |
| 37 | + */ |
| 38 | +function segmentsPerLine(mappings: string) { |
| 39 | + return mappings.split(';').map(line => (line === '' ? 0 : line.split(',').length)) |
| 40 | +} |
| 41 | + |
| 42 | +describe('unplugin', () => { |
| 43 | + it('injects auto-imports and emits a column-accurate sourcemap', async () => { |
| 44 | + const result = await transform(code) |
| 45 | + |
| 46 | + expect(result?.code).toContain(`import { helper } from 'my-lib';`) |
| 47 | + expect(result?.map.sources).toEqual([id]) |
| 48 | + // Bare generateMap() emits one mapping per line. V8 coverage then drops |
| 49 | + // the file and reports 100% (0/0). See https://github.com/unjs/unimport/issues/562 |
| 50 | + expect(Math.max(...segmentsPerLine(result!.map.mappings))).toBeGreaterThan(1) |
| 51 | + }) |
| 52 | + |
| 53 | + it('skips files that do not use auto-imports', async () => { |
| 54 | + expect(await transform('export const one = 1;\n')).toBeUndefined() |
| 55 | + }) |
| 56 | +}) |
0 commit comments