Skip to content

Commit 2533338

Browse files
committed
feat: add getDisplayName() and tests
1 parent 417fc5f commit 2533338

File tree

2 files changed

+99
-0
lines changed

2 files changed

+99
-0
lines changed
Lines changed: 83 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,83 @@
1+
import {Component} from 'react';
2+
import {h} from '../../util';
3+
import getDisplayName from '../getDisplayName';
4+
5+
describe('getDisplayName()', () => {
6+
it('is a function', () => {
7+
expect(getDisplayName).toBeInstanceOf(Function);
8+
});
9+
10+
it('stateless component', () => {
11+
const Comp = () => null;
12+
13+
expect(getDisplayName(Comp)).toBe('Comp');
14+
});
15+
16+
it('stateless component JSX', () => {
17+
const Comp = () => null;
18+
19+
expect(getDisplayName(<Comp />)).toBe('<Comp>');
20+
});
21+
22+
it('stateless named component', () => {
23+
const Comp = function MyComp () {};
24+
25+
expect(getDisplayName(Comp)).toBe('MyComp');
26+
});
27+
28+
it('stateless named component JSX', () => {
29+
const Comp = function MyComp () {
30+
return null;
31+
};
32+
33+
expect(getDisplayName(<Comp />)).toBe('<MyComp>');
34+
});
35+
36+
it('class Component', () => {
37+
const Comp = class MyComp extends Component {
38+
render () {
39+
return null;
40+
}
41+
}
42+
43+
expect(getDisplayName(Comp)).toBe('MyComp');
44+
});
45+
46+
it('class Component JSX', () => {
47+
const Comp = class MyComp extends Component {
48+
render () {
49+
return null;
50+
}
51+
}
52+
53+
expect(getDisplayName(<Comp />)).toBe('<MyComp>');
54+
});
55+
56+
it('class Component renamed', () => {
57+
const Comp = class MyComp extends Component {
58+
static displayName = 'Foobar';
59+
60+
render () {
61+
return null;
62+
}
63+
}
64+
65+
expect(getDisplayName(Comp)).toBe('Foobar');
66+
});
67+
68+
it('class Component renamed JSX', () => {
69+
const Comp = class MyComp extends Component {
70+
static displayName = 'Foobar';
71+
72+
render () {
73+
return null;
74+
}
75+
}
76+
77+
expect(getDisplayName(<Comp />)).toBe('<Foobar>');
78+
});
79+
80+
it('unknown', () => {
81+
expect(getDisplayName(123)).toBe('Unknown');
82+
});
83+
});

src/util/getDisplayName.ts

Lines changed: 16 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,16 @@
1+
const getDisplayName = (Comp: any) => {
2+
const tipof = typeof Comp;
3+
4+
switch (tipof) {
5+
case 'string':
6+
return Comp;
7+
case 'function':
8+
return Comp.displayName || Comp.name || 'Unknown';
9+
case 'object':
10+
return `<${Comp.type.displayName || Comp.type.name || String(Comp)}>`;
11+
default:
12+
return 'Unknown';
13+
}
14+
}
15+
16+
export default getDisplayName;

0 commit comments

Comments
 (0)