test: don't use __dirname and __filename in tests and configs (#8314)

This commit is contained in:
Vladimir 2025-07-15 15:02:19 +02:00 committed by GitHub
parent f453237194
commit 497cb94498
No known key found for this signature in database
GPG Key ID: B5690EEEBB952194
29 changed files with 67 additions and 75 deletions

View File

@ -24,8 +24,8 @@ export default vite.defineConfig({
} as any
: {},
input: {
orchestrator: resolve(__dirname, './orchestrator.html'),
tester: resolve(__dirname, './tester/tester.html'),
orchestrator: resolve(import.meta.dirname, './orchestrator.html'),
tester: resolve(import.meta.dirname, './tester/tester.html'),
},
external: [
/^vitest\//,

View File

@ -1,15 +1,11 @@
import { resolve } from 'node:path'
import { fileURLToPath } from 'node:url'
import { defineConfig } from 'vite'
const __filename = fileURLToPath(import.meta.url)
const __dirname = resolve(__filename, '..')
export default defineConfig({
test: {
globals: true,
globalSetup: [
resolve(__dirname, './globalSetup/error.js'),
resolve(import.meta.dirname, './globalSetup/error.js'),
],
},
})

View File

@ -11,7 +11,7 @@ export default defineConfig({
server: {
fs: {
allow: [
resolve(__dirname, 'src'),
resolve(import.meta.dirname, 'src'),
],
},
},

View File

@ -5,7 +5,7 @@ import { glob } from 'tinyglobby'
import { expect, it } from 'vitest'
import { runInlineTests, runVitest, ts } from '../../test-utils'
const root = resolve(__dirname, '../fixtures/fails')
const root = resolve(import.meta.dirname, '../fixtures/fails')
const files = await glob(['**/*.test.ts'], { cwd: root, dot: true, expandDirectories: false })
it.each(files)('should fail %s', async (file) => {

View File

@ -4,7 +4,7 @@ import { expect, it } from 'vitest'
import { runVitest } from '../../test-utils'
it('should fail', async () => {
const root = resolve(__dirname, '../fixtures/global-setup-fail')
const root = resolve(import.meta.dirname, '../fixtures/global-setup-fail')
const { stderr } = await runVitest({ root })
expect(stderr).toBeTruthy()

View File

@ -7,7 +7,7 @@ import { runVitest } from '../../test-utils'
process.setMaxListeners(20)
describe('stacktraces should respect sourcemaps', async () => {
const root = resolve(__dirname, '../fixtures/stacktraces')
const root = resolve(import.meta.dirname, '../fixtures/stacktraces')
const files = await glob(['*.test.*'], { cwd: root, expandDirectories: false })
for (const file of files) {
@ -24,7 +24,7 @@ describe('stacktraces should respect sourcemaps', async () => {
})
describe('stacktraces should pick error frame if present', async () => {
const root = resolve(__dirname, '../fixtures/stacktraces')
const root = resolve(import.meta.dirname, '../fixtures/stacktraces')
const files = ['frame.spec.imba']
for (const file of files) {
@ -41,7 +41,7 @@ describe('stacktraces should pick error frame if present', async () => {
})
describe('stacktrace should print error frame source file correctly', async () => {
const root = resolve(__dirname, '../fixtures/stacktraces')
const root = resolve(import.meta.dirname, '../fixtures/stacktraces')
const testFile = resolve(root, './error-in-deps.test.js')
it('error-in-deps', async () => {
@ -53,7 +53,7 @@ describe('stacktrace should print error frame source file correctly', async () =
})
describe('stacktrace filtering', async () => {
const root = resolve(__dirname, '../fixtures/stacktraces')
const root = resolve(import.meta.dirname, '../fixtures/stacktraces')
const testFile = resolve(root, './error-with-stack.test.js')
it('filters stacktraces', async () => {
@ -67,7 +67,7 @@ describe('stacktrace filtering', async () => {
})
describe('stacktrace in dependency package', () => {
const root = resolve(__dirname, '../fixtures/stacktraces')
const root = resolve(import.meta.dirname, '../fixtures/stacktraces')
const testFile = resolve(root, './error-in-package.test.js')
it('external', async () => {
@ -91,7 +91,7 @@ describe('stacktrace in dependency package', () => {
})
it('stacktrace in vmThreads', async () => {
const root = resolve(__dirname, '../fixtures/stacktraces')
const root = resolve(import.meta.dirname, '../fixtures/stacktraces')
const testFile = resolve(root, './error-with-stack.test.js')
const { stderr } = await runVitest({
root,

View File

@ -1,9 +1,5 @@
import { defineConfig } from 'vitest/config'
import { resolve } from 'node:path'
import { fileURLToPath } from 'node:url'
const __filename = fileURLToPath(import.meta.url)
const __dirname = resolve(__filename, '..')
export default defineConfig({
test: {
@ -11,13 +7,13 @@ export default defineConfig({
{
test: {
name: 'Project #1',
root: resolve(__dirname, './project'),
root: resolve(import.meta.dirname, './project'),
},
},
{
test: {
name: 'Project #2',
root: resolve(__dirname, './project'),
root: resolve(import.meta.dirname, './project'),
},
},
]

View File

@ -3,7 +3,7 @@ import { resolve } from 'pathe'
import { describe, expect, test } from 'vitest'
import { runVitest } from '../../test-utils'
const root = resolve(__dirname, '../fixtures/cache')
const root = resolve(import.meta.dirname, '../fixtures/cache')
test('default', async () => {
const { ctx, stdout, stderr } = await runVitest({

View File

@ -274,7 +274,7 @@ describe('FakeTimers', () => {
it('warns when trying to advance timers while real timers are used', () => {
const timers = new FakeTimers({
config: {
rootDir: __dirname,
rootDir: import.meta.dirname,
},
global,
})
@ -418,7 +418,7 @@ describe('FakeTimers', () => {
it('warns when trying to advance timers while real timers are used', async () => {
const timers = new FakeTimers({
config: {
rootDir: __dirname,
rootDir: import.meta.dirname,
},
global,
})

View File

@ -8,14 +8,14 @@ const content = 'Hello, World!'
const filename = 'fixtures/hi.txt'
describe('fs', () => {
it('__dirname', async () => {
const raw = await fs.readFile(resolve(__dirname, filename), 'utf-8')
it('import.meta.dirname', async () => {
const raw = await fs.readFile(resolve(import.meta.dirname, filename), 'utf-8')
expect(raw.trim()).toEqual(content)
})
it('__filename', async () => {
const raw = await fs.readFile(resolve(__filename, '..', filename), 'utf-8')
it('import.meta.filename', async () => {
const raw = await fs.readFile(resolve(import.meta.filename, '..', filename), 'utf-8')
expect(raw.trim()).toEqual(content)
})

View File

@ -94,7 +94,7 @@ test('can import @vite/client', async () => {
})
describe('importing special files from node_modules', async () => {
const dir = resolve(__dirname, '../src/node_modules')
const dir = resolve(import.meta.dirname, '../src/node_modules')
const wasm = resolve(dir, 'file.wasm')
const css = resolve(dir, 'file.css')
const mp3 = resolve(dir, 'file.mp3')

View File

@ -5,7 +5,7 @@ import { expect, test, vi } from 'vitest'
// @ts-expect-error wasm is not typed
import { add } from '../src/wasm/add.wasm'
const wasmFileBuffer = readFileSync(resolve(__dirname, '../src/wasm/add.wasm'))
const wasmFileBuffer = readFileSync(resolve(import.meta.dirname, '../src/wasm/add.wasm'))
test('supports native wasm imports', () => {
expect(add(1, 2)).toBe(3)

View File

@ -44,9 +44,9 @@ export default defineConfig({
},
resolve: {
alias: [
{ find: '#', replacement: resolve(__dirname, 'src') },
{ find: /^custom-lib$/, replacement: resolve(__dirname, 'projects', 'custom-lib') },
{ find: /^inline-lib$/, replacement: resolve(__dirname, 'projects', 'inline-lib') },
{ find: '#', replacement: resolve(import.meta.dirname, 'src') },
{ find: /^custom-lib$/, replacement: resolve(import.meta.dirname, 'projects', 'custom-lib') },
{ find: /^inline-lib$/, replacement: resolve(import.meta.dirname, 'projects', 'inline-lib') },
],
},
server: {
@ -132,7 +132,7 @@ export default defineConfig({
find: 'test-alias',
replacement: '',
// vitest doesn't crash because function is defined
customResolver: () => resolve(__dirname, 'src', 'aliased-mod.ts'),
customResolver: () => resolve(import.meta.dirname, 'src', 'aliased-mod.ts'),
},
],
onConsoleLog(log) {

View File

@ -5,7 +5,7 @@ let teardownHappened = false
export async function setup() {
const server = await createServer({
root: resolve(__dirname, '..'),
root: resolve(import.meta.dirname, '..'),
server: {
port: 9988,
},

View File

@ -1,7 +1,7 @@
import { resolve } from 'pathe'
import { defineConfig } from 'vitest/config'
const customReporter = resolve(__dirname, './src/custom-reporter.ts')
const customReporter = resolve(import.meta.dirname, './src/custom-reporter.ts')
export default defineConfig({
test: {

View File

@ -1,12 +1,12 @@
import { resolve } from 'pathe'
import { defineConfig } from 'vitest/config'
const customReporter = resolve(__dirname, '../src/custom-reporter.ts')
const customReporter = resolve(import.meta.dirname, '../src/custom-reporter.ts')
export default defineConfig({
root: __dirname,
root: import.meta.dirname,
test: {
root: __dirname,
root: import.meta.dirname,
include: ['../tests/reporters.spec.ts'],
reporters: [customReporter],
},

View File

@ -4,9 +4,9 @@ import { describe, expect, test } from 'vitest'
import { runVitest, runVitestCli } from '../../test-utils'
import TestReporter from '../src/custom-reporter'
const customTsReporterPath = resolve(__dirname, '../src/custom-reporter.ts')
const customJSReporterPath = resolve(__dirname, '../src/custom-reporter.js')
const root = resolve(__dirname, '..')
const customTsReporterPath = resolve(import.meta.dirname, '../src/custom-reporter.ts')
const customJSReporterPath = resolve(import.meta.dirname, '../src/custom-reporter.js')
const root = resolve(import.meta.dirname, '..')
async function runWithRetry(...runOptions: string[]) {
const count = 3

View File

@ -9,7 +9,7 @@ describe(GithubActionsReporter, () => {
let { stdout, stderr } = await runVitest(
{ reporters: new GithubActionsReporter(), root: './fixtures', include: ['**/some-failing.test.ts'] },
)
stdout = stdout.replace(resolve(__dirname, '..').replace(/:/g, '%3A'), '__TEST_DIR__')
stdout = stdout.replace(resolve(import.meta.dirname, '..').replace(/:/g, '%3A'), '__TEST_DIR__')
expect(stdout).toMatchInlineSnapshot(`
"
::error file=__TEST_DIR__/fixtures/some-failing.test.ts,title=some-failing.test.ts > 3 + 3 = 7,line=8,column=17::AssertionError: expected 6 to be 7 // Object.is equality%0A%0A- Expected%0A+ Received%0A%0A- 7%0A+ 6%0A%0A some-failing.test.ts:8:17%0A%0A
@ -24,7 +24,7 @@ describe(GithubActionsReporter, () => {
reporters: new GithubActionsReporter({
onWritePath(path) {
const normalized = path
.replace(resolve(__dirname, '..'), '')
.replace(resolve(import.meta.dirname, '..'), '')
.replaceAll(sep, '/')
return `/some-custom-path${normalized}`

View File

@ -3,7 +3,7 @@ import { describe, expect, it } from 'vitest'
import { runVitest } from '../../test-utils'
describe('import durations', () => {
const root = resolve(__dirname, '..', 'fixtures')
const root = resolve(import.meta.dirname, '..', 'fixtures')
it('should populate importDurations on File with import durations during execution', async () => {
const { exitCode, ctx } = await runVitest({

View File

@ -4,8 +4,8 @@ import { describe, expect, it } from 'vitest'
import { runVitest } from '../../test-utils'
describe('json reporter', async () => {
const root = resolve(__dirname, '..', 'fixtures')
const projectRoot = resolve(__dirname, '..', '..', '..')
const root = resolve(import.meta.dirname, '..', 'fixtures')
const projectRoot = resolve(import.meta.dirname, '..', '..', '..')
it('generates correct report', async () => {
const { stdout } = await runVitest({

View File

@ -5,7 +5,7 @@ import { expect, test } from 'vitest'
import { getDuration } from '../../../packages/vitest/src/node/reporters/junit'
import { runVitest, runVitestCli } from '../../test-utils'
const root = resolve(__dirname, '../fixtures')
const root = resolve(import.meta.dirname, '../fixtures')
test('calc the duration used by junit', () => {
const result: RunnerTaskResult = { state: 'pass', duration: 0 }

View File

@ -9,7 +9,7 @@ import { DefaultReporter } from '../../../packages/vitest/src/node/reporters/def
import { createReporters } from '../../../packages/vitest/src/node/reporters/utils'
import TestReporter from '../src/custom-reporter'
const customReporterPath = resolve(__dirname, '../src/custom-reporter.js')
const customReporterPath = resolve(import.meta.dirname, '../src/custom-reporter.js')
const fetchModule = {
executeId: (id: string) => import(id),
} as ViteNodeRunner

View File

@ -46,7 +46,7 @@ describe('should fail', async () => {
it('typechecks with custom tsconfig', async () => {
const { stderr } = await runVitest({
root,
dir: resolve(__dirname, '..', './failing'),
dir: resolve(import.meta.dirname, '..', './failing'),
config: resolve('./test/vitest.custom.config.ts'),
typecheck: { enabled: true },
})
@ -78,20 +78,20 @@ describe('should fail', async () => {
it('typechecks empty "include" but with tests', async () => {
const { stderr } = await runVitest({
root,
dir: resolve(__dirname, '..', './failing'),
config: resolve(__dirname, './vitest.empty.config.ts'),
dir: resolve(import.meta.dirname, '..', './failing'),
config: resolve(import.meta.dirname, './vitest.empty.config.ts'),
typecheck: { enabled: true },
},
)
expect(stderr.replace(resolve(__dirname, '..'), '<root>')).toMatchSnapshot()
expect(stderr.replace(resolve(import.meta.dirname, '..'), '<root>')).toMatchSnapshot()
})
})
describe('ignoreSourceErrors', () => {
it('disabled', async () => {
const vitest = await runVitest({
root: resolve(__dirname, '../fixtures/source-error'),
root: resolve(import.meta.dirname, '../fixtures/source-error'),
})
expect(vitest.stderr).toContain('Unhandled Errors')
expect(vitest.stderr).toContain('Unhandled Source Error')
@ -101,7 +101,7 @@ describe('ignoreSourceErrors', () => {
it('enabled', async () => {
const vitest = await runVitest(
{
root: resolve(__dirname, '../fixtures/source-error'),
root: resolve(import.meta.dirname, '../fixtures/source-error'),
typecheck: {
ignoreSourceErrors: true,
enabled: true,
@ -117,7 +117,7 @@ describe('ignoreSourceErrors', () => {
describe('when the title is dynamic', () => {
it('works correctly', async () => {
const vitest = await runVitest({
root: resolve(__dirname, '../fixtures/dynamic-title'),
root: resolve(import.meta.dirname, '../fixtures/dynamic-title'),
reporters: [['default', { isTTY: true }]],
})
@ -137,7 +137,7 @@ describe('when the title is dynamic', () => {
it('throws an error if typechecker process exists', async () => {
const { stderr } = await runVitest({
root: resolve(__dirname, '../fixtures/source-error'),
root: resolve(import.meta.dirname, '../fixtures/source-error'),
typecheck: {
enabled: true,
checker: 'non-existing-command',

View File

@ -3,13 +3,13 @@ import { expect, test } from 'vitest'
import { runViteNodeCli } from '../../test-utils'
test('circular 1', async () => {
const entryPath = resolve(__dirname, '../src/circular1/index.ts')
const entryPath = resolve(import.meta.dirname, '../src/circular1/index.ts')
const cli = await runViteNodeCli(entryPath)
expect(cli.stdout).toContain('A Bindex index')
}, 60_000)
test('circular 2', async () => {
const entryPath = resolve(__dirname, '../src/circular2/index.ts')
const entryPath = resolve(import.meta.dirname, '../src/circular2/index.ts')
const cli = await runViteNodeCli(entryPath)
expect(cli.stdout).toContain('ac b')
}, 60_000)

View File

@ -3,7 +3,7 @@ import pkg from 'vite-node/package.json'
import { expect, it } from 'vitest'
import { editFile, runViteNodeCli } from '../../test-utils'
const entryPath = resolve(__dirname, '../src/cli-parse-args.js')
const entryPath = resolve(import.meta.dirname, '../src/cli-parse-args.js')
const version = (pkg as any).version
@ -40,13 +40,13 @@ it('script args in -- after', async () => {
})
it('exposes .env variables', async () => {
const { stdout } = await runViteNodeCli(resolve(__dirname, '../src/cli-print-env.js'))
const { stdout } = await runViteNodeCli(resolve(import.meta.dirname, '../src/cli-print-env.js'))
const env = JSON.parse(stdout)
expect(env.MY_TEST_ENV).toBe('hello')
})
it.each(['index.js', 'index.cjs', 'index.mjs'])('correctly runs --watch %s', async (file) => {
const entryPath = resolve(__dirname, '../src/watch', file)
const entryPath = resolve(import.meta.dirname, '../src/watch', file)
const { viteNode } = await runViteNodeCli('--watch', entryPath)
await viteNode.waitForStdout('test 1')
editFile(entryPath, c => c.replace('test 1', 'test 2'))
@ -54,19 +54,19 @@ it.each(['index.js', 'index.cjs', 'index.mjs'])('correctly runs --watch %s', asy
})
it('error stack', async () => {
const entryPath = resolve(__dirname, '../src/watch/source-map.ts')
const entryPath = resolve(import.meta.dirname, '../src/watch/source-map.ts')
const { viteNode } = await runViteNodeCli('--watch', entryPath)
await viteNode.waitForStdout('source-map.ts:7:11')
})
it('buildStart', async () => {
const root = resolve(__dirname, '../src/buildStart')
const root = resolve(import.meta.dirname, '../src/buildStart')
const result = await runViteNodeCli('--root', root, resolve(root, 'test.ts'))
await result.viteNode.waitForStdout('["buildStart:in","buildStart:out"]')
})
it('buildStart with all ssr', async () => {
const root = resolve(__dirname, '../src/buildStart')
const root = resolve(import.meta.dirname, '../src/buildStart')
const result = await runViteNodeCli(
`--root=${root}`,
'--options.transformMode.ssr=.*',
@ -76,7 +76,7 @@ it('buildStart with all ssr', async () => {
})
it('empty mappings', async () => {
const root = resolve(__dirname, '../src/empty-mappings')
const root = resolve(import.meta.dirname, '../src/empty-mappings')
const result = await runViteNodeCli('--root', root, resolve(root, 'main.ts'))
await result.viteNode.waitForStdout('[ok]')
})

View File

@ -3,7 +3,7 @@ import { test } from 'vitest'
import { editFile, runViteNodeCli } from '../../test-utils'
test('hmr.accept works correctly', async () => {
const scriptFile = resolve(__dirname, '../src/hmr-script.js')
const scriptFile = resolve(import.meta.dirname, '../src/hmr-script.js')
const { viteNode } = await runViteNodeCli('--watch', scriptFile)
@ -17,7 +17,7 @@ test('hmr.accept works correctly', async () => {
})
test('can handle top-level throw in self-accepting module', async () => {
const scriptFile = resolve(__dirname, '../src/hmr-throw.js')
const scriptFile = resolve(import.meta.dirname, '../src/hmr-throw.js')
const { viteNode } = await runViteNodeCli('--watch', scriptFile)
@ -30,6 +30,6 @@ test('can handle top-level throw in self-accepting module', async () => {
})
test('basic', async () => {
const { viteNode } = await runViteNodeCli('--watch', resolve(__dirname, '../src/testMod.ts'))
const { viteNode } = await runViteNodeCli('--watch', resolve(import.meta.dirname, '../src/testMod.ts'))
await viteNode.waitForStdout('[deps.ts] imported')
})

View File

@ -10,13 +10,13 @@ it('should export self', () => {
})
it('example 1', async () => {
const entryPath = resolve(__dirname, '../src/self-export-example1.ts')
const entryPath = resolve(import.meta.dirname, '../src/self-export-example1.ts')
const { viteNode } = await runViteNodeCli(entryPath)
await viteNode.waitForStdout('Function')
}, 60_000)
it('example 2', async () => {
const entryPath = resolve(__dirname, '../src/self-export-example2.ts')
const entryPath = resolve(import.meta.dirname, '../src/self-export-example2.ts')
const { viteNode } = await runViteNodeCli(entryPath)
await viteNode.waitForStdout('HelloWorld: 1')
}, 60_000)

View File

@ -49,7 +49,7 @@ describe('server correctly caches data', () => {
webFiles: async ({}, use) => {
await use([])
},
root: resolve(__dirname, '../'),
root: resolve(import.meta.dirname, '../'),
plugin: async ({ ssrFiles, webFiles }, use) => {
const plugin: Plugin = {
name: 'test',

View File

@ -12,12 +12,12 @@ test('when nothing is changed, run nothing but keep watching', async () => {
await vitest.waitForStdout('No affected test files found')
await vitest.waitForStdout('Waiting for file changes...')
editFile(resolve(__dirname, '../fixtures/math.ts'), content => `${content}\n\n`)
editFile(resolve(import.meta.dirname, '../fixtures/math.ts'), content => `${content}\n\n`)
await vitest.waitForStdout('RERUN ../math.ts')
await vitest.waitForStdout('1 passed')
editFile(resolve(__dirname, '../fixtures/math.test.ts'), content => `${content}\n\n`)
editFile(resolve(import.meta.dirname, '../fixtures/math.test.ts'), content => `${content}\n\n`)
await vitest.waitForStdout('RERUN ../math.test.ts')
await vitest.waitForStdout('1 passed')