[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
This commit is contained in:
Nicolas Gallagher
2018-06-03 08:58:12 -07:00
parent 4f9216853b
commit 8f0c39c2fe
7 changed files with 35 additions and 403 deletions
+59
View File
@@ -0,0 +1,59 @@
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;
+3 -4
View File
@@ -2,10 +2,9 @@
import Adapter from 'enzyme-adapter-react-16';
import Enzyme from 'enzyme';
import createSerializer from '../../packages/react-native-web/jest/createSerializer';
import { StyleSheet } from '../../packages/react-native-web/src';
const serializer = createSerializer(StyleSheet);
import serializer from './serializer';
Enzyme.configure({ adapter: new Adapter() });
// TODO: move off legacy serializer
expect.addSnapshotSerializer(serializer);