Files
react-native-web/scripts/jest/serializer.js
Nicolas Gallagher 8f0c39c2fe [change] introduce Jest preset
A simple Jest preset that configures module mapping and produces
human-readable styles (i.e., not converted to numeric form).

Fix #928
Fix #963
2018-06-04 11:40:07 -07:00

60 lines
1.5 KiB
JavaScript

import React from 'react';
import { StyleSheet } from '../../packages/react-native-web/src';
function createSerializer(styleSheet) {
function flattenNodeStyles(node) {
if (node && node.props) {
// check for React elements in any props
const nextProps = Object.keys(node.props).reduce((acc, curr) => {
const value = node.props[curr];
if (React.isValidElement(value)) {
acc[curr] = flattenNodeStyles(value);
}
return acc;
}, {});
// flatten styles and avoid empty objects in snapshots
if (node.props.style) {
const style = styleSheet.flatten(node.props.style);
if (Object.keys(style).length > 0) {
nextProps.style = style;
} else {
delete nextProps.style;
}
}
const args = [node, nextProps];
// recurse over children too
const children = node.children || node.props.children;
if (children) {
if (Array.isArray(children)) {
children.forEach(child => {
args.push(flattenNodeStyles(child));
});
} else {
args.push(flattenNodeStyles(children));
}
}
return React.cloneElement.apply(React.cloneElement, args);
}
return node;
}
function test(value) {
return !!value && value.$$typeof === Symbol.for('react.test.json');
}
function print(value, serializer) {
return serializer(flattenNodeStyles(value));
}
return { test, print };
}
const serializer = createSerializer(StyleSheet);
export default serializer;