javascript / expert
Snippet
Deterministic Stack Trace Normalization for React Error Boundaries in Unit Tests
React Error Boundaries generate environment-specific componentStack strings containing absolute file paths. Normalizing these stack strings within test suites allows deterministic assertion testing across different OS environments and CI/CD runner filesystems.
snippet.js
javascript
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
import React from 'react';export function normalizeBoundaryStack(errorInfo) {if (!errorInfo || typeof errorInfo.componentStack !== 'string') {throw new TypeError('Invalid ComponentStack payload provided.');}const cleanLines = errorInfo.componentStack.split('\n').map(line => line.trim()).filter(Boolean).map(line => line.replace(/\(at .*\)/, '(at [normalized])'));return cleanLines.join('\n');}export class TestableErrorBoundary extends React.Component {state = { hasError: false, normalizedStack: null };componentDidCatch(error, errorInfo) {const stack = normalizeBoundaryStack(errorInfo);this.setState({ hasError: true, normalizedStack: stack });}render() {if (this.state.hasError) {return <pre data-testid="error-stack">{this.state.normalizedStack}</pre>;}return this.props.children;}}
react
Breakdown
1
if (!errorInfo || typeof errorInfo.componentStack !== 'string') {
Validates input payload type to fail early with explicit TypeError before processing.
2
const cleanLines = errorInfo.componentStack
Splits raw React component stack string into discrete array items for individual line parsing.
3
.map(line => line.replace(/\(at .*\)/, '(at [normalized])'));
Strips local directory structures from stack traces using regular expressions for snapshot consistency.
4
componentDidCatch(error, errorInfo) {
Captures unhandled child errors and passes runtime component trace details to normalization function.
5
return <pre data-testid="error-stack">{this.state.normalizedStack}</pre>;
Renders normalized error string into DOM for resilient component test runner assertions.