|
| 1 | +import { dirname, join } from 'node:path' |
| 2 | +import { fileURLToPath } from 'node:url' |
| 3 | + |
| 4 | +/** |
| 5 | + * Vite plugin to configure @testing-library/svelte. |
| 6 | + * |
| 7 | + * Ensures Svelte is imported correctly in tests |
| 8 | + * and that the DOM is cleaned up after each test. |
| 9 | + * |
| 10 | + * @param {{resolveBrowser?: boolean, autoCleanup?: boolean}} options |
| 11 | + * @returns {import('vite').Plugin} |
| 12 | + */ |
| 13 | +export const svelteTesting = ({ |
| 14 | + resolveBrowser = true, |
| 15 | + autoCleanup = true, |
| 16 | +} = {}) => ({ |
| 17 | + name: 'vite-plugin-svelte-testing-library', |
| 18 | + config: (config) => { |
| 19 | + if (!process.env.VITEST) { |
| 20 | + return |
| 21 | + } |
| 22 | + |
| 23 | + if (resolveBrowser) { |
| 24 | + addBrowserCondition(config) |
| 25 | + } |
| 26 | + |
| 27 | + if (autoCleanup) { |
| 28 | + addAutoCleanup(config) |
| 29 | + } |
| 30 | + }, |
| 31 | +}) |
| 32 | + |
| 33 | +/** |
| 34 | + * Add `browser` to `resolve.conditions` before `node`. |
| 35 | + * |
| 36 | + * This ensures that Svelte's browser code is used in tests, |
| 37 | + * rather than its SSR code. |
| 38 | + * |
| 39 | + * @param {import('vitest/config').UserConfig} config |
| 40 | + */ |
| 41 | +const addBrowserCondition = (config) => { |
| 42 | + const resolve = config.resolve ?? {} |
| 43 | + const conditions = resolve.conditions ?? [] |
| 44 | + const nodeConditionIndex = conditions.indexOf('node') |
| 45 | + const browserConditionIndex = conditions.indexOf('browser') |
| 46 | + |
| 47 | + if ( |
| 48 | + nodeConditionIndex >= 0 && |
| 49 | + (nodeConditionIndex < browserConditionIndex || browserConditionIndex < 0) |
| 50 | + ) { |
| 51 | + conditions.splice(nodeConditionIndex, 0, 'browser') |
| 52 | + } |
| 53 | + |
| 54 | + resolve.conditions = conditions |
| 55 | + config.resolve = resolve |
| 56 | +} |
| 57 | + |
| 58 | +/** |
| 59 | + * Add auto-cleanup file to Vitest's setup files. |
| 60 | + * |
| 61 | + * @param {import('vitest/config').UserConfig} config |
| 62 | + */ |
| 63 | +const addAutoCleanup = (config) => { |
| 64 | + const test = config.test ?? {} |
| 65 | + let setupFiles = test.setupFiles ?? [] |
| 66 | + |
| 67 | + if (typeof setupFiles === 'string') { |
| 68 | + setupFiles = [setupFiles] |
| 69 | + } |
| 70 | + |
| 71 | + setupFiles.push(join(dirname(fileURLToPath(import.meta.url)), './vitest.js')) |
| 72 | + |
| 73 | + test.setupFiles = setupFiles |
| 74 | + config.test = test |
| 75 | +} |
0 commit comments