/
test-bodies.ts
77 lines (62 loc) · 2.29 KB
/
test-bodies.ts
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
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
import 'jest-specific-snapshot';
import { StoryshotsTestMethod, TestMethodOptions } from './api/StoryshotsOptions';
const isFunction = (obj: any) => !!(obj && obj.constructor && obj.call && obj.apply);
const optionsOrCallOptions = (opts: any, story: any) => (isFunction(opts) ? opts(story) : opts);
type SnapshotsWithOptionsReturnType = (
options: Pick<TestMethodOptions, 'story' | 'context' | 'renderTree' | 'snapshotFileName'>
) => any;
export function snapshotWithOptions(
options: { renderer?: any; serializer?: any } | Function = {}
): SnapshotsWithOptionsReturnType {
return ({ story, context, renderTree, snapshotFileName }) => {
const result = renderTree(story, context, optionsOrCallOptions(options, story));
function match(tree: any) {
let target = tree;
const isReact = story.parameters.framework === 'react';
if (isReact && typeof tree.childAt === 'function') {
target = tree.childAt(0);
}
if (isReact && Array.isArray(tree.children)) {
[target] = tree.children;
}
if (snapshotFileName) {
expect(target).toMatchSpecificSnapshot(snapshotFileName);
} else {
expect(target).toMatchSnapshot();
}
if (typeof tree.unmount === 'function') {
tree.unmount();
}
}
if (typeof result.then === 'function') {
return result.then(match);
}
return match(result);
};
}
export function multiSnapshotWithOptions(options = {}): StoryshotsTestMethod {
return ({ story, context, renderTree, stories2snapsConverter }) => {
const snapshotFileName = stories2snapsConverter.getSnapshotFileName(context);
return snapshotWithOptions(options)({ story, context, renderTree, snapshotFileName });
};
}
export const shallowSnapshot: StoryshotsTestMethod = ({
story,
context,
renderShallowTree,
options = {},
}) => {
const result = renderShallowTree(story, context, options);
expect(result).toMatchSnapshot();
};
export function renderWithOptions(options = {}): StoryshotsTestMethod {
return ({ story, context, renderTree }) => {
const result = renderTree(story, context, options);
if (typeof result.then === 'function') {
return result;
}
return undefined;
};
}
export const renderOnly = renderWithOptions();
export const snapshot = snapshotWithOptions();