Skip to content

Commit 10e4cee

Browse files
authored
Refactor getComponentName function (#1)
1 parent ec29ca1 commit 10e4cee

File tree

2 files changed

+28
-18
lines changed

2 files changed

+28
-18
lines changed

src/utils.test.ts

Lines changed: 13 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -23,6 +23,19 @@ describe('utils', () => {
2323
it('gets component name', () => {
2424
expect(getComponentName()).toEqual('_callCircusTest')
2525
})
26+
27+
it('returns empty string if error.stack is not supported by the browser', () => {
28+
const customError = new Error('error without stack')
29+
delete customError.stack
30+
expect(getComponentName(customError)).toEqual('')
31+
})
32+
33+
it('returns empty string if error.stack has different format', () => {
34+
const customError = new Error('error with unsupported stack')
35+
customError.stack =
36+
'This is custom implementation of stack: calledThis > calledThat'
37+
expect(getComponentName(customError)).toEqual('')
38+
})
2639
})
2740

2841
describe('getPrinter', () => {

src/utils.ts

Lines changed: 15 additions & 18 deletions
Original file line numberDiff line numberDiff line change
@@ -65,25 +65,22 @@ export function getGroupLabel(
6565
return `${typeWrapper}${componentNameWrapper}${timeWrapper}`
6666
}
6767

68-
export function getComponentName(): string {
69-
// Tested in the scope of useLog testing
70-
try {
71-
throw new Error('Getting the stack of error to parse it for component name')
72-
} catch (error) {
73-
/* istanbul ignore next */
74-
if (error instanceof Error && error?.stack) {
75-
const re = /(\w+)@|at (\w+) \(/g
76-
77-
re.exec(error.stack ?? '')
78-
re.exec(error.stack ?? '')
79-
const m = re.exec(error.stack ?? '') ?? []
80-
81-
return String(m[1] || m[2])
82-
}
83-
84-
/* istanbul ignore next */
85-
return '' // will be never reached since getComponentName always throws an instance of Error to parse the stack
68+
export function getComponentName(
69+
error = new Error(
70+
'Getting the stack of error to parse it for component name',
71+
),
72+
): string {
73+
if (!error.stack) {
74+
return ''
8675
}
76+
77+
const re = /(\w+)@|at (\w+) \(/g
78+
79+
re.exec(error.stack)
80+
re.exec(error.stack)
81+
const m = re.exec(error.stack)
82+
83+
return m ? String(m[1] || m[2]) : ''
8784
}
8885

8986
export function getRenderFunctionProps<T>(

0 commit comments

Comments
 (0)