-
Notifications
You must be signed in to change notification settings - Fork 22
/
Copy pathreact-serializer.js
53 lines (45 loc) · 1.54 KB
/
react-serializer.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
// @flow
'use strict';
const prettyFormat = require('pretty-format');
const snapshot = require('jest-snapshot');
const defaultSerializers = snapshot.getSerializers();
let serializers = defaultSerializers;
const reactElement = Symbol.for('react.element');
function getReactComponentSerializer() {
let renderer;
try {
renderer = require('react-test-renderer'); // eslint-disable-line import/no-extraneous-dependencies
} catch (error) {
if (error.code === 'MODULE_NOT_FOUND') {
throw new Error(
`Failed to load optional module "react-test-renderer". ` +
`If you need to compare React elements, please add "react-test-renderer" to your ` +
`project's dependencies.\n` +
`${error.message}`
);
}
throw error;
}
return (value) =>
prettyFormat(renderer.create(value).toJSON(), { plugins: serializers });
}
function setSerializers(customSerializers) {
serializers = customSerializers;
}
const reactSerializer = {
test: (value: any) => value && value.$$typeof === reactElement,
print: (value: any, _serializer?: (any) => any) => {
const reactComponentSerializer = getReactComponentSerializer();
return reactComponentSerializer(value);
},
diffOptions: (valueA: any, valueB: any) => {
const prettyFormatOptions = { plugins: serializers, min: true };
return {
aAnnotation: prettyFormat(valueA, prettyFormatOptions),
bAnnotation: prettyFormat(valueB, prettyFormatOptions),
};
},
setSerializers,
defaultSerializers,
};
module.exports = reactSerializer;