Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Fix pretty-format to respect displayName on forwardRef. #9422

Merged
merged 2 commits into from Jan 17, 2020
Merged
Show file tree
Hide file tree
Changes from 1 commit
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Jump to
Jump to file
Failed to load files.
Diff view
Diff view
52 changes: 52 additions & 0 deletions packages/pretty-format/src/__tests__/ReactElement.test.ts
@@ -0,0 +1,52 @@
/**
* Copyright (c) Facebook, Inc. and its affiliates. All Rights Reserved.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/

import React from 'react';
import setPrettyPrint from './setPrettyPrint';
import prettyFormat from '..';

const {ReactElement} = prettyFormat.plugins;

setPrettyPrint([ReactElement]);

describe('ReactElement Plugin', () => {
let forwardRefComponent: {
(_props: any, _ref: any): any;
displayName?: string;
};

let forwardRefExample: ReturnType<typeof React.forwardRef>;

beforeEach(() => {
forwardRefComponent = (_props, _ref) => null;

forwardRefExample = React.forwardRef(forwardRefComponent);

forwardRefExample.displayName = undefined;
});

test('serializes forwardRef without displayName', () => {
forwardRefExample = React.forwardRef((_props, _ref) => null);
expect(React.createElement(forwardRefExample)).toPrettyPrintTo(
'<ForwardRef />',
);
});

test('serializes forwardRef with displayName', () => {
forwardRefExample.displayName = 'Display';
expect(React.createElement(forwardRefExample)).toPrettyPrintTo(
'<Display />',
);
});

test('serializes forwardRef component with displayName', () => {
forwardRefComponent.displayName = 'Display';
expect(React.createElement(forwardRefExample)).toPrettyPrintTo(
'<ForwardRef(Display) />',
);
});
});
4 changes: 4 additions & 0 deletions packages/pretty-format/src/plugins/ReactElement.ts
Expand Up @@ -53,6 +53,10 @@ const getType = (element: any) => {
}

if (ReactIs.isForwardRef(element)) {
if (type.displayName) {
return type.displayName;
}

const functionName = type.render.displayName || type.render.name || '';

return functionName !== ''
Expand Down