forked from vitest-dev/vitest
/
cli-api.ts
90 lines (74 loc) · 2.36 KB
/
cli-api.ts
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
import { execa } from 'execa'
import type { UserConfig as ViteUserConfig } from 'vite'
import c from 'picocolors'
import type { UserConfig } from '../types'
import { ensurePackageInstalled } from '../utils'
import { createVitest } from './create'
import { registerConsoleShortcuts } from './stdin'
import { divider } from './reporters/renderers/utils'
export interface CliOptions extends UserConfig {
/**
* Override the watch mode
*/
run?: boolean
}
export async function startVitest(cliFilters: string[], options: CliOptions, viteOverrides?: ViteUserConfig) {
process.env.TEST = 'true'
process.env.VITEST = 'true'
process.env.NODE_ENV ??= options.mode || 'test'
if (options.run)
options.watch = false
if (!await ensurePackageInstalled('vite')) {
process.exitCode = 1
return false
}
if (typeof options.coverage === 'boolean')
options.coverage = { enabled: options.coverage }
const ctx = await createVitest(options, viteOverrides)
process.env.VITEST_MODE = ctx.config.watch ? 'WATCH' : 'RUN'
if (ctx.config.coverage.enabled) {
if (!await ensurePackageInstalled('c8')) {
process.exitCode = 1
return false
}
if (!process.env.NODE_V8_COVERAGE) {
process.env.NODE_V8_COVERAGE = ctx.config.coverage.tempDirectory
// thread enable test will exec in thread
// so don't need to restarting Vitest
if (!ctx.config.threads) {
await ctx.server.close()
const { exitCode } = await execa(process.argv0, process.argv.slice(1), { stdio: 'inherit', reject: false })
process.exitCode = exitCode
return false
}
}
}
if (ctx.config.environment && ctx.config.environment !== 'node') {
if (!await ensurePackageInstalled(ctx.config.environment)) {
process.exitCode = 1
return false
}
}
if (process.stdin.isTTY && ctx.config.watch)
registerConsoleShortcuts(ctx)
process.chdir(ctx.config.root)
ctx.onServerRestarted(() => {
// TODO: re-consider how to re-run the tests the server smartly
ctx.start(cliFilters)
})
try {
await ctx.start(cliFilters)
}
catch (e) {
process.exitCode = 1
ctx.error(`\n${c.red(divider(c.bold(c.inverse(' Unhandled Error '))))}`)
await ctx.printError(e, true)
ctx.error('\n\n')
return false
}
if (!ctx.config.watch) {
await ctx.exit()
return !process.exitCode
}
return true
}