@samitouri / QOS-React-2 / commits / d1c2555861

[react-devtools-shared] Added string type check for object name prop in getDisplayName function (#16798)

* [react-devtools-shared] Added string type check for object name prop in getDisplayName function from utils.js file; tests included; * Re-added empty string check to getDisplayName() * Tweaked tests to use real functions This more closely simulates how the utility is being used in production, and would catch cases like anonymous functions (with empty string names).

Pavlo Tymchuk committed Sep 17, 2019 at 22:17 UTC d1c25558614164936bb90b6c6dc590106381c446
2 files changed +43 -5
packages/react-devtools-shared/src/__tests__/utils-test.js new
+40
@@ -0,0 +1,40 @@
1 +/**
2 + * Copyright (c) Facebook, Inc. and its affiliates.
3 + *
4 + * This source code is licensed under the MIT license found in the
5 + * LICENSE file in the root directory of this source tree.
6 + *
7 + * @flow
8 + */
9 +
10 +import {getDisplayName} from 'react-devtools-shared/src/utils';
11 +
12 +describe('utils', () => {
13 + describe('getDisplayName', () => {
14 + it('should return a function name', () => {
15 + function FauxComponent() {}
16 + expect(getDisplayName(FauxComponent)).toEqual('FauxComponent');
17 + });
18 +
19 + it('should return a displayName name if specified', () => {
20 + function FauxComponent() {}
21 + FauxComponent.displayName = 'OverrideDisplayName';
22 + expect(getDisplayName(FauxComponent)).toEqual('OverrideDisplayName');
23 + });
24 +
25 + it('should return the fallback for anonymous functions', () => {
26 + expect(getDisplayName(() => {}, 'Fallback')).toEqual('Fallback');
27 + });
28 +
29 + it('should return Anonymous for anonymous functions without a fallback', () => {
30 + expect(getDisplayName(() => {})).toEqual('Anonymous');
31 + });
32 +
33 + // Simulate a reported bug:
34 + // https://github.com/facebook/react/issues/16685
35 + it('should return a fallback when the name prop is not a string', () => {
36 + const FauxComponent = {name: {}};
37 + expect(getDisplayName(FauxComponent, 'Fallback')).toEqual('Fallback');
38 + });
39 + });
40 +});
packages/react-devtools-shared/src/utils.js
+3 -5
@@ -46,17 +46,15 @@ export function getDisplayName(
46 return nameFromCache;
47 }
48
49 - let displayName;
49 + let displayName = fallbackName;
50
51 // The displayName property is not guaranteed to be a string.
52 // It's only safe to use for our purposes if it's a string.
53 // github.com/facebook/react-devtools/issues/803
54 if (typeof type.displayName === 'string') {
55 displayName = type.displayName;
56 - }
57 -
58 - if (!displayName) {
59 - displayName = type.name || fallbackName;
56 + } else if (typeof type.name === 'string' && type.name !== '') {
57 + displayName = type.name;
58 }
59
60 cachedDisplayNames.set(type, displayName);