diff --git a/src/core/nuxt.ts b/src/core/nuxt.ts index b6ef9c637..ba8a063a4 100644 --- a/src/core/nuxt.ts +++ b/src/core/nuxt.ts @@ -43,7 +43,7 @@ export async function loadFixture () { if (!ctx.options.dev) { const randomId = Math.random().toString(36).slice(2, 8) - const buildDir = ctx.options.buildDir || resolve(ctx.options.rootDir, '.nuxt', randomId) + const buildDir = ctx.options.buildDir || resolve(ctx.options.rootDir, '.nuxt', 'test', randomId) ctx.options.nuxtConfig = defu(ctx.options.nuxtConfig, { buildDir, nitro: { @@ -61,7 +61,13 @@ export async function loadFixture () { configFile: ctx.options.configFile }) - await fsp.mkdir(ctx.nuxt.options.buildDir, { recursive: true }) + const buildDir = ctx.nuxt.options.buildDir + // avoid creating / deleting build dirs that already exist - avoids misconfiguration deletes + if (!existsSync(buildDir)) { + await fsp.mkdir(buildDir, { recursive: true }) + ctx.teardown = ctx.teardown || [] + ctx.teardown.push(() => fsp.rm(buildDir, { recursive: true, force: true })) + } } export async function buildFixture () { diff --git a/src/core/setup/index.ts b/src/core/setup/index.ts index 6fc205cc6..f03a94868 100644 --- a/src/core/setup/index.ts +++ b/src/core/setup/index.ts @@ -34,6 +34,8 @@ export function createTest (options: Partial): TestHooks { if (ctx.browser) { await ctx.browser.close() } + // clear side effects + await Promise.all((ctx.teardown || []).map(fn => fn())) } const setup = async () => { diff --git a/src/core/types.ts b/src/core/types.ts index e8847091b..5e7f22e7f 100644 --- a/src/core/types.ts +++ b/src/core/types.ts @@ -33,6 +33,11 @@ export interface TestContext { url?: string serverProcess?: ExecaChildProcess mockFn?: Function + /** + * Functions to run on the vitest `afterAll` hook. + * Useful for removing anything created during the test. + */ + teardown?: (() => void)[] } export interface TestHooks {