-
-
Notifications
You must be signed in to change notification settings - Fork 1.3k
/
jestUtils.ts
251 lines (226 loc) · 6.52 KB
/
jestUtils.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
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
/* eslint-disable @typescript-eslint/no-namespace */
'use strict';
import type { ReactTestInstance } from 'react-test-renderer';
import type {
AnimatedComponentProps,
IAnimatedComponentInternal,
InitialComponentProps,
} from '../createAnimatedComponent/commonTypes';
import { isJest } from './PlatformChecker';
import type { DefaultStyle } from './hook/commonTypes';
declare global {
namespace jest {
interface Matchers<R> {
toHaveAnimatedStyle(
style: Record<string, unknown>[] | Record<string, unknown>,
config?: {
shouldMatchAllProps?: boolean;
}
): R;
}
}
}
const defaultFramerateConfig = {
fps: 60,
};
const getCurrentStyle = (component: TestComponent): DefaultStyle => {
const styleObject = component.props.style;
let currentStyle = {};
if (Array.isArray(styleObject)) {
styleObject.forEach((style) => {
currentStyle = {
...currentStyle,
...style,
};
});
} else {
currentStyle = {
...styleObject,
...component.props.jestAnimatedStyle?.value,
};
}
return currentStyle;
};
const checkEqual = <Value>(current: Value, expected: Value) => {
if (Array.isArray(expected)) {
if (!Array.isArray(current) || expected.length !== current.length) {
return false;
}
for (let i = 0; i < current.length; i++) {
if (!checkEqual(current[i], expected[i])) {
return false;
}
}
} else if (typeof current === 'object' && current) {
if (typeof expected !== 'object' || !expected) {
return false;
}
for (const property in expected) {
if (!checkEqual(current[property], expected[property])) {
return false;
}
}
} else {
return current === expected;
}
return true;
};
const findStyleDiff = (
current: DefaultStyle,
expected: DefaultStyle,
shouldMatchAllProps?: boolean
) => {
const diffs = [];
let isEqual = true;
let property: keyof DefaultStyle;
for (property in expected) {
if (!checkEqual(current[property], expected[property])) {
isEqual = false;
diffs.push({
property,
current: current[property],
expect: expected[property],
});
}
}
if (
shouldMatchAllProps &&
Object.keys(current).length !== Object.keys(expected).length
) {
isEqual = false;
// eslint-disable-next-line @typescript-eslint/no-shadow
let property: keyof DefaultStyle;
for (property in current) {
if (expected[property] === undefined) {
diffs.push({
property,
current: current[property],
expect: expected[property],
});
}
}
}
return { isEqual, diffs };
};
const compareStyle = (
component: TestComponent,
expectedStyle: DefaultStyle,
config: ToHaveAnimatedStyleConfig
) => {
if (!component.props.style) {
return { message: () => `Component doesn't have a style.`, pass: false };
}
const { shouldMatchAllProps } = config;
const currentStyle = getCurrentStyle(component);
const { isEqual, diffs } = findStyleDiff(
currentStyle,
expectedStyle,
shouldMatchAllProps
);
if (isEqual) {
return { message: () => 'ok', pass: true };
}
const currentStyleStr = JSON.stringify(currentStyle);
const expectedStyleStr = JSON.stringify(expectedStyle);
const differences = diffs
.map(
(diff) =>
`- '${diff.property}' should be ${JSON.stringify(
diff.expect
)}, but is ${JSON.stringify(diff.current)}`
)
.join('\n');
return {
message: () =>
`Expected: ${expectedStyleStr}\nReceived: ${currentStyleStr}\n\nDifferences:\n${differences}`,
pass: false,
};
};
let frameTime = Math.round(1000 / defaultFramerateConfig.fps);
const beforeTest = () => {
jest.useFakeTimers();
};
const afterTest = () => {
jest.runOnlyPendingTimers();
jest.useRealTimers();
};
export const withReanimatedTimer = (animationTest: () => void) => {
console.warn(
'This method is deprecated, you should define your own before and after test hooks to enable jest.useFakeTimers(). Check out the documentation for details on testing'
);
beforeTest();
animationTest();
afterTest();
};
export const advanceAnimationByTime = (time = frameTime) => {
console.warn(
'This method is deprecated, use jest.advanceTimersByTime directly'
);
jest.advanceTimersByTime(time);
jest.runOnlyPendingTimers();
};
export const advanceAnimationByFrame = (count: number) => {
console.warn(
'This method is deprecated, use jest.advanceTimersByTime directly'
);
jest.advanceTimersByTime(count * frameTime);
jest.runOnlyPendingTimers();
};
const requireFunction = isJest()
? require
: () => {
throw new Error(
'[Reanimated] `setUpTests` is available only in Jest environment.'
);
};
type ToHaveAnimatedStyleConfig = {
shouldMatchAllProps?: boolean;
};
export const setUpTests = (userFramerateConfig = {}) => {
let expect: jest.Expect = (global as typeof global & { expect: jest.Expect })
.expect;
if (expect === undefined) {
const expectModule = requireFunction('expect');
expect = expectModule;
// Starting from Jest 28, "expect" package uses named exports instead of default export.
// So, requiring "expect" package doesn't give direct access to "expect" function anymore.
// It gives access to the module object instead.
// We use this info to detect if the project uses Jest 28 or higher.
if (typeof expect === 'object') {
const jestGlobals = requireFunction('@jest/globals');
expect = jestGlobals.expect;
}
if (expect === undefined || expect.extend === undefined) {
expect = expectModule.default;
}
}
const framerateConfig = {
...defaultFramerateConfig,
...userFramerateConfig,
};
frameTime = Math.round(1000 / framerateConfig.fps);
expect.extend({
toHaveAnimatedStyle(
component: React.Component<
AnimatedComponentProps<InitialComponentProps>
> &
IAnimatedComponentInternal,
expectedStyle: DefaultStyle,
config: ToHaveAnimatedStyleConfig = {}
) {
return compareStyle(component, expectedStyle, config);
},
});
};
type TestComponent = React.Component<
AnimatedComponentProps<InitialComponentProps> & {
jestAnimatedStyle?: { value: DefaultStyle };
}
>;
export const getAnimatedStyle = (component: ReactTestInstance) => {
return getCurrentStyle(
// This type assertion is needed to get type checking in the following
// functions since `ReactTestInstance` has its `props` defined as `any`.
component as unknown as TestComponent
);
};