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

[Spike] EUI snapshot serializer #6769

Closed
wants to merge 1 commit into from
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
35 changes: 35 additions & 0 deletions src/test/snapshot_serializers/components.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,35 @@
/*
* Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one
* or more contributor license agreements. Licensed under the Elastic License
* 2.0 and the Server Side Public License, v 1; you may not use this file except
* in compliance with, at your election, the Elastic License 2.0 or the Server
* Side Public License, v 1.
*/

// Components that should render as <EuiComponent /> only, with no children
// Their content is either too complex to attempt to render
// or irrelevant/completely controlled by EUI
export const COMPONENTS_EMPTY = [
'EuiDataGrid',
'EuiInMemoryTable',
'EuiBasicTable',
'EuiSpacer',
'EuiHorizontalRule',
];

// Components that should render with their text content only
export const COMPONENTS_TEXT = ['EuiButton', 'EuiBadge'];

// Components that should attempt to snapshot all HTML content within them
// as their content is likely important / custom to the consumer
export const COMPONENTS_HTML = [
'EuiPageTemplate',
'EuiPageSection',
'EuiPage',
'EuiPanel',
'EuiFlexGrid',
'EuiFlexGroup',
'EuiFlexItem',
'EuiText',
'EuiTitle',
];
11 changes: 11 additions & 0 deletions src/test/snapshot_serializers/enzyme/index.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,11 @@
/*
* Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one
* or more contributor license agreements. Licensed under the Elastic License
* 2.0 and the Server Side Public License, v 1; you may not use this file except
* in compliance with, at your election, the Elastic License 2.0 or the Server
* Side Public License, v 1.
*/

export { euiEnzymeShallowSnapshotSerializer } from './shallow';
export { euiEnzymeMountSnapshotSerializer } from './mount';
export { euiEnzymeRenderSnapshotSerializer } from './render';
Comment on lines +9 to +11
Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Just want to illustrate a large part of the problem - there's 4 different render methods (Enzyme has 3, RTL has 1) that need to be solved for when writing these serializers, which effectively quadruples the amount of work and testing needed.

77 changes: 77 additions & 0 deletions src/test/snapshot_serializers/enzyme/mount.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,77 @@
/*
* Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one
* or more contributor license agreements. Licensed under the Elastic License
* 2.0 and the Server Side Public License, v 1; you may not use this file except
* in compliance with, at your election, the Elastic License 2.0 or the Server
* Side Public License, v 1.
*/

import { ReactWrapper } from 'enzyme';

import { fixIndentation } from '../utils';
import {
getEnzymeProps,
stripUnderscorePrefix,
cleanEuiComponentNames,
} from './utils';

/**
* Utils
*/
const isReactWrapper = (wrapper: any) =>
wrapper?.constructor?.name === ReactWrapper.name;

const printChildrenShallowly = (children: string) => {
// Remove annoying Emotion wrappers
children = children.replace(/^\s*<EmotionCssPropInternal[^\n]*>\n?/gm, '');
children = children.replace(/^\s*<\/EmotionCssPropInternal>\n?/gm, '');
children = children.replace(/^\s*<Insertion[^\n]*>\n?/gm, '');
children = children.replace(/^\s*<\/Insertion>\n?/gm, '');

// Strip/replace any underscore-prefixed EUI component names
children = cleanEuiComponentNames(children);

// Attempt to remove rendered DOM content that are EUI and can be represented by wrappers
// Determine this via, e.g. <button className="euiButton [...whatever other classes" [whatever props]>
const tagRegex = /^(?<tagName>\s*<[a-z]+)[^\n]* className="eui[A-Z][A-Za-z]+[\s\w-]*"[^\n]*>\n/m;
let tagMatch;
while ((tagMatch = children.match(tagRegex))) {
const tagName = tagMatch.groups?.tagName;
const closingTagRegex = new RegExp(
`^${tagName?.replace('<', '</')}>\\n`,
'm'
);
children = children.replace(tagRegex, '');
children = children.replace(closingTagRegex, '');
}

// Indentation will potentially be messed up due to removed content/wrappers - we'll need to restore it manually
children = fixIndentation(children.trim());

return children;
};

/**
* Snapshot serializer
*/
export const euiEnzymeMountSnapshotSerializer = {
test: (val: any) => {
if (isReactWrapper(val)) {
return val.name().startsWith('Eui') || val.name().startsWith('_Eui');
} else {
return false;
}
},
print: (val: ReactWrapper) => {
const euiComponentName = stripUnderscorePrefix(val.name());

let props = getEnzymeProps(val);
props = props ? ` ${props}` : '';

const children = printChildrenShallowly(val.children().debug());

return children
? `<${euiComponentName}${props}>\n${children}\n</${euiComponentName}>`
: `<${euiComponentName}${props} />`;
},
};
52 changes: 52 additions & 0 deletions src/test/snapshot_serializers/enzyme/render.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,52 @@
/*
* Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one
* or more contributor license agreements. Licensed under the Elastic License
* 2.0 and the Server Side Public License, v 1; you may not use this file except
* in compliance with, at your election, the Elastic License 2.0 or the Server
* Side Public License, v 1.
*/

import {
getEuiComponentFromClassName,
removeSerializedSyntax,
fixIndentation,
printEmptyComponent,
printWrappingComponent,
} from '../utils';
import { COMPONENTS_HTML, COMPONENTS_TEXT } from '../components';

/**
* Utils
*/
const isCheerioWrapper = (wrapper: any) => wrapper?.cheerio != null;

/**
* Snapshot serializer
*/
export const euiEnzymeRenderSnapshotSerializer = {
test: (val: any) => {
if (isCheerioWrapper(val)) {
return val.attr('class')?.startsWith('eui');
} else {
return false;
}
},
print: (val: Cheerio, serialize: Function) => {
const euiComponentName = getEuiComponentFromClassName(val.attr('class'))!;

if (COMPONENTS_HTML.includes(euiComponentName)) {
let children = '';
children = serialize(val.children());
children = removeSerializedSyntax(children);
children = children.replace(/\n\n/g, '');
children = fixIndentation(children.trim());

return printWrappingComponent(euiComponentName, `\n${children}\n`);
}
if (COMPONENTS_TEXT.includes(euiComponentName)) {
return printWrappingComponent(euiComponentName, val.text());
}
// Default to rendering an empty component
return printEmptyComponent(euiComponentName);
},
};
74 changes: 74 additions & 0 deletions src/test/snapshot_serializers/enzyme/shallow.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,74 @@
/*
* Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one
* or more contributor license agreements. Licensed under the Elastic License
* 2.0 and the Server Side Public License, v 1; you may not use this file except
* in compliance with, at your election, the Elastic License 2.0 or the Server
* Side Public License, v 1.
*/

import { ShallowWrapper } from 'enzyme';

import { getEuiComponentFromClassName } from '../utils';
import {
getEnzymeProps,
stripUnderscorePrefix,
cleanEuiComponentNames,
} from './utils';

/**
* Utils
*/
const isShallowWrapper = (wrapper: any) =>
wrapper?.constructor?.name === ShallowWrapper.name;

const getShallowName = (wrapper: ShallowWrapper) => {
let name = wrapper.name();
// Emotion bogarts the name with its own wrapper :(
if (name === 'EmotionCssPropInternal') {
name = wrapper.prop('__EMOTION_LABEL_PLEASE_DO_NOT_USE__');
// Sometimes the emotion label isn't set - fall back to the className
if (!name)
name = getEuiComponentFromClassName(wrapper.prop('className')) || '';
}
// Some display names have underscored prefixes
name = stripUnderscorePrefix(name);
return name;
};

const printChildren = (children: string) => {
children = children.replace(/\n\n/g, '').replace(/\n/g, '\n '); // Fix indentation and spacing
children = cleanEuiComponentNames(children);
return children;
};

/**
* Snapshot serializer
*/
export const euiEnzymeShallowSnapshotSerializer = {
Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Shallow is the most robust of all the serializers, because... well.. it's basically already what we want 🥲 We wouldn't be in this situation if everyone in Kibana were using shallow snapshots however.

test: (val: any) => {
if (isShallowWrapper(val)) {
if (val.name() === 'ContextProvider') {
// Skip context providers
return true;
} else {
const name = getShallowName(val);
return name.startsWith('Eui');
}
} else {
return false;
}
},
print: (val: ShallowWrapper, serialize: Function) => {
if (val.name() === 'ContextProvider') return serialize(val.children());

const euiComponentName = getShallowName(val);

let props = getEnzymeProps(val);
props = props ? ` ${props}` : '';

const children = printChildren(val.children().debug());
return children
? `<${euiComponentName}${props}>\n ${children}\n</${euiComponentName}>`
: `<${euiComponentName}${props} />`;
},
};
36 changes: 36 additions & 0 deletions src/test/snapshot_serializers/enzyme/utils.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,36 @@
/*
* Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one
* or more contributor license agreements. Licensed under the Elastic License
* 2.0 and the Server Side Public License, v 1; you may not use this file except
* in compliance with, at your election, the Elastic License 2.0 or the Server
* Side Public License, v 1.
*/

import type { ShallowWrapper, ReactWrapper } from 'enzyme';

export const getEnzymeProps = (wrapper: ShallowWrapper | ReactWrapper) => {
const props = wrapper.props() || ({} as any);
const keys = Object.keys(props).filter((key) => {
if (key === 'children') return false;
if (key === 'css') return false;
if (key.startsWith('__EMOTION')) return false;
return true;
});
return keys
.map((key) => {
let value = props[key];
value = typeof value === 'string' ? `"${value}"` : `{${String(value)}}`;
return `${key}=${value}`;
})
.join(' ');
};

export const stripUnderscorePrefix = (string?: string) => {
return string?.replace(/^_/, '') || '';
};

export const cleanEuiComponentNames = (string: string) => {
string = string.replace(/<_Eui/g, '<Eui');
string = string.replace(/<\/_Eui/g, '</Eui');
return string;
};
9 changes: 9 additions & 0 deletions src/test/snapshot_serializers/rtl/index.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,9 @@
/*
* Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one
* or more contributor license agreements. Licensed under the Elastic License
* 2.0 and the Server Side Public License, v 1; you may not use this file except
* in compliance with, at your election, the Elastic License 2.0 or the Server
* Side Public License, v 1.
*/

export { euiRTLRenderSnapshotSerializer } from './render';
50 changes: 50 additions & 0 deletions src/test/snapshot_serializers/rtl/render.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,50 @@
/*
* Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one
* or more contributor license agreements. Licensed under the Elastic License
* 2.0 and the Server Side Public License, v 1; you may not use this file except
* in compliance with, at your election, the Elastic License 2.0 or the Server
* Side Public License, v 1.
*/

import {
getEuiComponentFromClassName,
fixIndentation,
printEmptyComponent,
printWrappingComponent,
removeSerializedSyntax,
} from '../utils';
import { COMPONENTS_HTML, COMPONENTS_TEXT } from '../components';

export const euiRTLRenderSnapshotSerializer = {
test: (val: any) => {
if (val instanceof HTMLElement) {
return val.className?.startsWith('eui');
Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

TBH, I think even just taking the RTL render snapshot serializer alone is where you start to realize things are getting kinda dicey. Basically what I'm doing is regexing HTML which everyone knows is a wild path to go down.

It also feels somewhat fragile because it relies on us correctly setting className="euiSomeComponent" as a class hook/API on everything we render, which to be fair, we do do 90% of the time, but then don't for some things like nested DOM, internal components, etc.

} else {
return false;
}
},
print: (val: HTMLElement, serialize: Function) => {
const euiComponentName = getEuiComponentFromClassName(val.className)!;

if (COMPONENTS_HTML.includes(euiComponentName)) {
let children = '';
try {
children = serialize(val.children); // serialize sometimes throws an error :/
children = removeSerializedSyntax(children);
} catch {
// Fall back to displaying the raw HTML if we can't serialize the children
children = val.innerHTML;
children = children.split('>').join('>\n');
children = children.split(/(?<!>)<\//).join('\n</'); // Negative lookbehind for, e.g. Text</div>
}
children = fixIndentation(children.trim());

return printWrappingComponent(euiComponentName, `\n${children}\n`);
}
if (COMPONENTS_TEXT.includes(euiComponentName)) {
return printWrappingComponent(euiComponentName, val.textContent);
}
// Default to rendering an empty component
return printEmptyComponent(euiComponentName);
},
};
Loading