forked from vitest-dev/vitest
/
error.ts
278 lines (238 loc) · 8.53 KB
/
error.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
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
/* eslint-disable prefer-template */
import { existsSync, readFileSync } from 'node:fs'
import { normalize, relative } from 'pathe'
import c from 'picocolors'
import cliTruncate from 'cli-truncate'
import { stringify } from '@vitest/utils'
import type { ErrorWithDiff, ParsedStack } from '../types'
import { lineSplitRE, parseErrorStacktrace, positionToOffset } from '../utils/source-map'
import { F_POINTER } from '../utils/figures'
import { TypeCheckError } from '../typecheck/typechecker'
import { isPrimitive } from '../utils'
import type { Vitest } from './core'
import { divider } from './reporters/renderers/utils'
import type { Logger } from './logger'
interface PrintErrorOptions {
type?: string
fullStack?: boolean
showCodeFrame?: boolean
}
export async function printError(error: unknown, ctx: Vitest, options: PrintErrorOptions = {}) {
const { showCodeFrame = true, fullStack = false, type } = options
let e = error as ErrorWithDiff
if (isPrimitive(e)) {
e = {
message: String(error).split(/\n/g)[0],
stack: String(error),
} as any
}
if (!e) {
const error = new Error('unknown error')
e = {
message: e ?? error.message,
stack: error.stack,
} as any
}
// Error may have occured even before the configuration was resolved
if (!ctx.config)
return printErrorMessage(e, ctx.logger)
const stacks = parseErrorStacktrace(e, fullStack ? [] : undefined)
const nearest = error instanceof TypeCheckError
? error.stacks[0]
: stacks.find(stack =>
ctx.getModuleProjects(stack.file).length
&& existsSync(stack.file),
)
const errorProperties = getErrorProperties(e)
if (type)
printErrorType(type, ctx)
printErrorMessage(e, ctx.logger)
// if the error provide the frame
if (e.frame) {
ctx.logger.error(c.yellow(e.frame))
}
else {
printStack(ctx, stacks, nearest, errorProperties, (s) => {
if (showCodeFrame && s === nearest && nearest) {
const sourceCode = readFileSync(nearest.file, 'utf-8')
ctx.logger.error(c.yellow(generateCodeFrame(sourceCode, 4, s.line, s.column)))
}
})
}
const testPath = (e as any).VITEST_TEST_PATH
const testName = (e as any).VITEST_TEST_NAME
const afterEnvTeardown = (e as any).VITEST_AFTER_ENV_TEARDOWN
// testName has testPath inside
if (testPath)
ctx.logger.error(c.red(`This error originated in "${c.bold(testPath)}" test file. It doesn't mean the error was thrown inside the file itself, but while it was running.`))
if (testName) {
ctx.logger.error(c.red(`The latest test that might've caused the error is "${c.bold(testName)}". It might mean one of the following:`
+ '\n- The error was thrown, while Vitest was running this test.'
+ '\n- This was the last recorded test before the error was thrown, if error originated after test finished its execution.'))
}
if (afterEnvTeardown) {
ctx.logger.error(c.red('This error was caught after test environment was torn down. Make sure to cancel any running tasks before test finishes:'
+ '\n- cancel timeouts using clearTimeout and clearInterval'
+ '\n- wait for promises to resolve using the await keyword'))
}
if (typeof e.cause === 'object' && e.cause && 'name' in e.cause) {
(e.cause as any).name = `Caused by: ${(e.cause as any).name}`
await printError(e.cause, ctx, { fullStack, showCodeFrame: false })
}
handleImportOutsideModuleError(e.stack || e.stackStr || '', ctx)
// E.g. AssertionError from assert does not set showDiff but has both actual and expected properties
if (e.diff)
displayDiff(e.diff, ctx.logger.console)
}
function printErrorType(type: string, ctx: Vitest) {
ctx.logger.error(`\n${c.red(divider(c.bold(c.inverse(` ${type} `))))}`)
}
const skipErrorProperties = new Set([
'nameStr',
'stack',
'cause',
'stacks',
'stackStr',
'type',
'showDiff',
'diff',
'actual',
'expected',
'VITEST_TEST_NAME',
'VITEST_TEST_PATH',
'VITEST_AFTER_ENV_TEARDOWN',
...Object.getOwnPropertyNames(Error.prototype),
...Object.getOwnPropertyNames(Object.prototype),
])
function getErrorProperties(e: ErrorWithDiff) {
const errorObject = Object.create(null)
if (e.name === 'AssertionError')
return errorObject
for (const key of Object.getOwnPropertyNames(e)) {
if (!skipErrorProperties.has(key))
errorObject[key] = e[key as keyof ErrorWithDiff]
}
return errorObject
}
const esmErrors = [
'Cannot use import statement outside a module',
'Unexpected token \'export\'',
]
function handleImportOutsideModuleError(stack: string, ctx: Vitest) {
if (!esmErrors.some(e => stack.includes(e)))
return
const path = normalize(stack.split('\n')[0].trim())
let name = path.split('/node_modules/').pop() || ''
if (name?.startsWith('@'))
name = name.split('/').slice(0, 2).join('/')
else
name = name.split('/')[0]
if (name)
printModuleWarningForPackage(ctx.logger, path, name)
else
printModuleWarningForSourceCode(ctx.logger, path)
}
function printModuleWarningForPackage(logger: Logger, path: string, name: string) {
logger.error(c.yellow(
`Module ${path} seems to be an ES Module but shipped in a CommonJS package. `
+ `You might want to create an issue to the package ${c.bold(`"${name}"`)} asking `
+ 'them to ship the file in .mjs extension or add "type": "module" in their package.json.'
+ '\n\n'
+ 'As a temporary workaround you can try to inline the package by updating your config:'
+ '\n\n'
+ c.gray(c.dim('// vitest.config.js'))
+ '\n'
+ c.green(`export default {
test: {
deps: {
inline: [
${c.yellow(c.bold(`"${name}"`))}
]
}
}
}\n`)))
}
function printModuleWarningForSourceCode(logger: Logger, path: string) {
logger.error(c.yellow(
`Module ${path} seems to be an ES Module but shipped in a CommonJS package. `
+ 'To fix this issue, change the file extension to .mjs or add "type": "module" in your package.json.',
))
}
export function displayDiff(diff: string, console: Console) {
console.error(diff)
}
function printErrorMessage(error: ErrorWithDiff, logger: Logger) {
const errorName = error.name || error.nameStr || 'Unknown Error'
logger.error(c.red(`${c.bold(errorName)}: ${error.message}`))
}
function printStack(
ctx: Vitest,
stack: ParsedStack[],
highlight: ParsedStack | undefined,
errorProperties: Record<string, unknown>,
onStack?: ((stack: ParsedStack) => void),
) {
const logger = ctx.logger
for (const frame of stack) {
const color = frame === highlight ? c.yellow : c.gray
const path = relative(ctx.config.root, frame.file)
logger.error(color(` ${c.dim(F_POINTER)} ${[frame.method, c.dim(`${path}:${frame.line}:${frame.column}`)].filter(Boolean).join(' ')}`))
onStack?.(frame)
}
if (stack.length)
logger.error()
const hasProperties = Object.keys(errorProperties).length > 0
if (hasProperties) {
logger.error(c.red(c.dim(divider())))
const propertiesString = stringify(errorProperties, 10, { printBasicPrototype: false })
logger.error(c.red(c.bold('Serialized Error:')), c.gray(propertiesString))
}
}
export function generateCodeFrame(
source: string,
indent = 0,
lineNumber: number,
columnNumber: number,
range = 2,
): string {
const start = positionToOffset(source, lineNumber, columnNumber)
const end = start
const lines = source.split(lineSplitRE)
let count = 0
let res: string[] = []
const columns = process.stdout?.columns || 80
function lineNo(no: number | string = '') {
return c.gray(`${String(no).padStart(3, ' ')}| `)
}
for (let i = 0; i < lines.length; i++) {
count += lines[i].length + 1
if (count >= start) {
for (let j = i - range; j <= i + range || end > count; j++) {
if (j < 0 || j >= lines.length)
continue
const lineLength = lines[j].length
// to long, maybe it's a minified file, skip for codeframe
if (lineLength > 200)
return ''
res.push(lineNo(j + 1) + cliTruncate(lines[j].replace(/\t/g, ' '), columns - 5 - indent))
if (j === i) {
// push underline
const pad = start - (count - lineLength)
const length = Math.max(1, end > count ? lineLength - pad : end - start)
res.push(lineNo() + ' '.repeat(pad) + c.red('^'.repeat(length)))
}
else if (j > i) {
if (end > count) {
const length = Math.max(1, Math.min(end - count, lineLength))
res.push(lineNo() + c.red('^'.repeat(length)))
}
count += lineLength + 1
}
}
break
}
}
if (indent)
res = res.map(line => ' '.repeat(indent) + line)
return res.join('\n')
}