diff --git a/.changeset/young-teeth-draw.md b/.changeset/young-teeth-draw.md new file mode 100644 index 000000000000..b68aeac582cf --- /dev/null +++ b/.changeset/young-teeth-draw.md @@ -0,0 +1,5 @@ +--- +'astro': patch +--- + +Fixes `experimental_AstroContainer` output including dev toolbar `data-astro-source-file` and `data-astro-source-loc` attributes when rendering components under Vitest diff --git a/packages/astro/src/core/compile/compile.ts b/packages/astro/src/core/compile/compile.ts index 39aba5eb0315..ff1566c6035a 100644 --- a/packages/astro/src/core/compile/compile.ts +++ b/packages/astro/src/core/compile/compile.ts @@ -63,8 +63,12 @@ export async function compile({ scopedStyleStrategy: astroConfig.scopedStyleStrategy, resultScopedSlot: true, transitionsAnimationURL: 'astro/components/viewtransitions.css', + // Source annotations only serve the dev toolbar. Vitest also runs Vite in `serve`, + // so skip them in `test` mode to keep rendered markup (e.g. from the Container API) + // free of machine-specific paths. See https://github.com/withastro/astro/issues/18162 annotateSourceFile: viteConfig.command === 'serve' && + viteConfig.mode !== 'test' && astroConfig.devToolbar && astroConfig.devToolbar.enabled && toolbarEnabled, diff --git a/packages/astro/test/units/compile/annotate-source-file.test.ts b/packages/astro/test/units/compile/annotate-source-file.test.ts new file mode 100644 index 000000000000..87fe29be860c --- /dev/null +++ b/packages/astro/test/units/compile/annotate-source-file.test.ts @@ -0,0 +1,36 @@ +import * as assert from 'node:assert/strict'; +import { describe, it } from 'node:test'; +import { pathToFileURL } from 'node:url'; +import { resolveConfig } from 'vite'; +import { compile } from '../../../dist/core/compile/index.js'; +import type { AstroConfig } from '../../../dist/types/public/config.js'; + +async function compileInMode(mode: string) { + const result = await compile({ + astroConfig: { + root: pathToFileURL('/'), + experimental: {}, + devToolbar: { enabled: true }, + } as AstroConfig, + viteConfig: await resolveConfig({ configFile: false, mode }, 'serve'), + toolbarEnabled: true, + filename: '/src/components/Hello.astro', + source: ``, + }); + return result.code; +} + +describe('astro/src/core/compile', () => { + describe('annotateSourceFile', () => { + it('adds source annotations in dev', async () => { + const code = await compileInMode('development'); + assert.match(code, /data-astro-source-file=/); + }); + + it('does not add source annotations in Vitest (test mode)', async () => { + const code = await compileInMode('test'); + assert.doesNotMatch(code, /data-astro-source-file=/); + assert.doesNotMatch(code, /data-astro-source-loc=/); + }); + }); +});