Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
52 changes: 34 additions & 18 deletions packages/vitest/src/node/test-run.ts
Original file line number Diff line number Diff line change
Expand Up @@ -33,9 +33,12 @@ import mime from 'mime/lite'
import { basename, extname, resolve } from 'pathe'

export class TestRun {
private externalSourceMaps = new Map<string, unknown>()

constructor(private vitest: Vitest) {}

async start(specifications: TestSpecification[]): Promise<void> {
this.externalSourceMaps.clear()
const filepaths = specifications.map((spec) => spec.moduleId)
this.vitest.state.collectPaths(filepaths)

Expand Down Expand Up @@ -108,7 +111,7 @@ export class TestRun {
? project.browser?.parseStacktrace(entry.stack, { firstOnly: true }) || []
: parseStacktrace(entry.stack, {
firstOnly: true,
getSourceMap: (file) => getExternalSourceMap(project, file),
getSourceMap: (file) => this.getExternalSourceMap(project, file),
})
if (stack) {
entry.location = { file: stack.file, line: stack.line, column: stack.column }
Expand Down Expand Up @@ -194,12 +197,20 @@ export class TestRun {
update.forEach(([taskId, result]) => {
const task = this.vitest.state.idMap.get(taskId)
const isBrowser = task && task.file.pool === 'browser'
// the worker sends all errors of the task again in each update
const previous = task?.result

result?.errors?.forEach((error) => {
result?.errors?.forEach((error, i) => {
if (isPrimitive(error)) {
return
}

const parsed = previous?.errors?.[i]
if (error.stack && parsed?.stacks && parsed.stack === error.stack) {
error.stacks = parsed.stacks
return
}

const project = this.vitest.getProjectByName(task!.file.projectName || '')
if (isBrowser) {
error.stacks =
Expand All @@ -209,13 +220,33 @@ export class TestRun {
} else {
error.stacks = parseErrorStacktrace(error, {
frameFilter: project.config.onStackTrace,
getSourceMap: (file) => getExternalSourceMap(project, file),
getSourceMap: (file) => this.getExternalSourceMap(project, file),
})
}
})
})
}

private getExternalSourceMap(project: TestProject, file: string): unknown {
// This only handles external modules since
// source map is already applied for inlined modules.
// Module node exists due to Vitest fetch module,
// but transformResult should be empty for external modules.
// TODO: this uses client module graph and thus miss detects
// inlined modules in ssr environment as if external.
const mod = project.vite.moduleGraph.getModuleById(file)
if (mod?.transformResult) {
return undefined
}
if (!this.externalSourceMaps.has(file)) {
const map = existsSync(file)
? extractSourcemapFromFile(readFileSync(file, 'utf-8'), file)?.map
: undefined
this.externalSourceMaps.set(file, map)
}
return this.externalSourceMaps.get(file)
}

private async reportEvent(id: string, event: TaskUpdateEvent, data: TaskEventData | undefined) {
const task = this.vitest.state.idMap.get(id)
const entity = task && this.vitest.state.getReportedEntity(task)
Expand Down Expand Up @@ -343,18 +374,3 @@ export class TestRun {
}
}
}

function getExternalSourceMap(project: TestProject, file: string) {
// This only handles external modules since
// source map is already applied for inlined modules.
// Module node exists due to Vitest fetch module,
// but transformResult should be empty for external modules.
// TODO: this uses client module graph and thus miss detects
// inlined modules in ssr environment as if external.
const mod = project.vite.moduleGraph.getModuleById(file)
if (!mod?.transformResult && existsSync(file)) {
const code = readFileSync(file, 'utf-8')
const result = extractSourcemapFromFile(code, file)
return result?.map
}
}
78 changes: 76 additions & 2 deletions test/e2e/test/stacktraces.test.ts
Original file line number Diff line number Diff line change
@@ -1,8 +1,8 @@
import { resolve } from 'pathe'
import { relative, resolve } from 'pathe'
import { glob } from 'tinyglobby'
import { describe, expect, it } from 'vitest'
import { rolldownVersion } from 'vitest/node'
import { runInlineTests, runVitest } from '../../test-utils'
import { runInlineTests, runVitest, ts } from '../../test-utils'

// To prevent the warning coming up in snapshots
process.setMaxListeners(20)
Expand Down Expand Up @@ -105,6 +105,80 @@ describe('stacktrace in dependency package', () => {
)
expect(removeNodeModules(removeLines(stderr))).toMatchSnapshot()
})

it('uses the changed source map in the next run', async () => {
const { ctx, fs, root, buildTree } = await runInlineTests(
{
'node_modules/dep/package.json': JSON.stringify({
name: 'dep',
type: 'module',
exports: './index.js',
}),
'node_modules/dep/index.js': ts`
export function parse() {
throw new Error('parse failed')
}
export function format() {
throw new Error('format failed')
}
//# sourceMappingURL=index.js.map
`,
'node_modules/dep/index.js.map': JSON.stringify({
version: 3,
sources: ['index.ts'],
names: [],
mappings: ';;AASA;;;AAUA',
}),
'basic.test.js': ts`
import { format, parse } from 'dep'
import { test } from 'vitest'

let tries = 0
test('flaky', { retry: 1 }, () => {
if (tries++ === 0) {
parse()
}
format()
})
`,
},
{ watch: true },
)
const errorLocations = () =>
buildTree((test) =>
test.result().errors?.map((error) => {
const [frame] = error.stacks || []
return `${error.message} at ${relative(root, frame.file)}:${frame.line}:${frame.column}`
}),
)

expect(errorLocations()).toMatchInlineSnapshot(`
{
"basic.test.js": {
"flaky": [
"parse failed at node_modules/dep/index.ts:10:1",
"format failed at node_modules/dep/index.ts:20:1",
],
},
}
`)

fs.editFile('node_modules/dep/index.js.map', (map) => map.replace('index.ts', 'main.ts'))
await ctx!.rerunTestSpecifications(
ctx!.state.getTestModules().map((testModule) => testModule.toTestSpecification()),
)

expect(errorLocations()).toMatchInlineSnapshot(`
{
"basic.test.js": {
"flaky": [
"parse failed at node_modules/dep/main.ts:10:1",
"format failed at node_modules/dep/main.ts:20:1",
],
},
}
`)
})
})

it('stacktrace in vmThreads', async () => {
Expand Down
Loading