@khanacademy/wonder-blocks-testing 0.0.2

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/CHANGELOG.md ADDED
@@ -0,0 +1,7 @@
1
+ # @khanacademy/wonder-blocks-testing
2
+
3
+ ## 0.0.2
4
+ ### Patch Changes
5
+
6
+ - d2dba67a: Implemented the fixture framework and added the storybook adapter for it
7
+ - b7a100f2: Add the new wonder-blocks-testing package
@@ -0,0 +1,354 @@
1
+ import _extends from '@babel/runtime/helpers/extends';
2
+ import * as React from 'react';
3
+ import { action } from '@storybook/addon-actions';
4
+ import { clone } from '@khanacademy/wonder-stuff-core';
5
+
6
+ /**
7
+ * Simple adapter group implementation.
8
+ */
9
+ class AdapterGroup {
10
+ /**
11
+ * Create an adapter group.
12
+ *
13
+ * @param {CloseGroupFn<TProps, Options, Exports>} closeGroupFn A function
14
+ * to invoke when the group is closed.
15
+ * @param {AdapterGroupOptions} options The options for the group.
16
+ */
17
+ constructor(closeGroupFn, _options) {
18
+ this.closeGroup = (adapterOptions = null) => {
19
+ if (this._closeGroupFn == null) {
20
+ throw new Error("Group already closed");
21
+ }
22
+
23
+ try {
24
+ return this._closeGroupFn(this._options, adapterOptions, this._fixtures);
25
+ } finally {
26
+ this._closeGroupFn = null;
27
+ }
28
+ };
29
+
30
+ this.declareFixture = options => {
31
+ if (typeof options !== "object" || options === null) {
32
+ throw new TypeError("options must be an object");
33
+ }
34
+
35
+ if (this._closeGroupFn == null) {
36
+ throw new Error("Cannot declare fixtures after closing the group");
37
+ }
38
+
39
+ this._fixtures.push(options);
40
+ };
41
+
42
+ if (typeof closeGroupFn !== "function") {
43
+ throw new TypeError("closeGroupFn must be a function");
44
+ }
45
+
46
+ if (typeof _options !== "object" || _options === null) {
47
+ throw new TypeError("options must be an object");
48
+ }
49
+
50
+ this._closeGroupFn = closeGroupFn;
51
+ this._options = _options;
52
+ this._fixtures = [];
53
+ }
54
+ /**
55
+ * Close the group.
56
+ *
57
+ * This declares that no more fixtures are to be added to the group,
58
+ * and will call the parent adapter with the declared fixtures so that they
59
+ * can be adapted for the target fixture framework, such as Storybook.
60
+ */
61
+
62
+
63
+ }
64
+
65
+ /**
66
+ * Class for implementing a custom adapter.
67
+ */
68
+ class Adapter {
69
+ /**
70
+ * @param {string} name The name of the adapter.
71
+ * @param {CloseGroupFn<any, Options, Exports>} closeGroupFn The function
72
+ * an adapter group should call when the group is closed. This is invoked
73
+ * by an adapter group when it is closed. This function is where an
74
+ * adapter implements the logic to generate the actual fixtures for the
75
+ * adapter's target framework.
76
+ */
77
+ constructor(name, closeGroupFn) {
78
+ if (typeof name !== "string") {
79
+ throw new TypeError("name must be a string");
80
+ }
81
+
82
+ if (name.trim() === "") {
83
+ throw new Error("name must be a non-empty string");
84
+ }
85
+
86
+ if (typeof closeGroupFn !== "function") {
87
+ throw new TypeError("closeGroupFn must be a function");
88
+ }
89
+
90
+ this._name = name;
91
+ this._closeGroupFn = closeGroupFn;
92
+ }
93
+ /**
94
+ * The name of the adapter.
95
+ */
96
+
97
+
98
+ get name() {
99
+ return this._name;
100
+ }
101
+ /**
102
+ * Declare a new fixture group.
103
+ *
104
+ * @param {AdapterGroupOptions} options The options describing the fixture
105
+ * group.
106
+ * @returns {AdapterGroupInterface} The new fixture group.
107
+ */
108
+
109
+
110
+ declareGroup(options) {
111
+ return new AdapterGroup(this._closeGroupFn, options);
112
+ }
113
+
114
+ }
115
+
116
+ /**
117
+ * Get a fixture framework adapter for Storybook support.
118
+ */
119
+ const getAdapter = (MountingComponent = null) => new Adapter("storybook", ({
120
+ title,
121
+ description: groupDescription
122
+ }, adapterOptions, declaredFixtures) => {
123
+ const templateMap = new WeakMap();
124
+
125
+ const log = (message, ...args) => action(message).apply(void 0, args);
126
+
127
+ const exports = declaredFixtures.reduce((acc, {
128
+ description,
129
+ getProps,
130
+ component: Component
131
+ }, i) => {
132
+ const storyName = `${i + 1} ${description}`;
133
+ const exportName = storyName // Make word boundaries start with an upper case letter.
134
+ .replace(/\b\w/g, c => c.toUpperCase()) // Remove all non-alphanumeric characters.
135
+ .replace(/[^\w]+/g, "") // Remove all underscores.
136
+ .replace(/[_]+/g, ""); // We create a “template” of how args map to rendering
137
+ // for each type of component as the component here could
138
+ // be the component under test, or wrapped in a wrapper
139
+ // component. We don't use decorators for the wrapper
140
+ // because we may not be in a storybook context and it
141
+ // keeps the framework API simpler this way.
142
+
143
+ let Template = templateMap.get(Component);
144
+
145
+ if (Template == null) {
146
+ // The MountingComponent is a bit different than just a
147
+ // Storybook decorator. It's a React component that
148
+ // takes over rendering the component in the fixture
149
+ // with the given args, allowing for greater
150
+ // customization in a platform-agnostic manner (i.e.
151
+ // not just story format).
152
+ Template = MountingComponent ? args => /*#__PURE__*/React.createElement(MountingComponent, {
153
+ component: Component,
154
+ props: args,
155
+ log: log
156
+ }) : args => /*#__PURE__*/React.createElement(Component, args);
157
+ templateMap.set(Component, Template);
158
+ } // Each story that shares that component then reuses that
159
+ // template.
160
+
161
+
162
+ acc[exportName] = Template.bind({});
163
+ acc[exportName].args = getProps({
164
+ log
165
+ }); // Adding a story name here means that we don't have to
166
+ // care about naming the exports correctly, if we don't
167
+ // want (useful if we need to autogenerate or manually
168
+ // expose ESM exports).
169
+
170
+ acc[exportName].storyName = storyName;
171
+ return acc;
172
+ }, {
173
+ default: _extends({
174
+ title
175
+ }, adapterOptions)
176
+ });
177
+ return Object.freeze(exports);
178
+ });
179
+
180
+ var adapters = /*#__PURE__*/Object.freeze({
181
+ __proto__: null,
182
+ storybook: getAdapter
183
+ });
184
+
185
+ let _configuration = null;
186
+ /**
187
+ * Setup the fixture framework.
188
+ */
189
+
190
+ const setup = configuration => {
191
+ _configuration = configuration;
192
+ };
193
+ /**
194
+ * Get the framework configuration.
195
+ *
196
+ * @returns {Configuration} The configuration as provided via setup().
197
+ * @throws {Error} If the configuration has not been set.
198
+ */
199
+
200
+ const getConfiguration = () => {
201
+ if (_configuration == null) {
202
+ throw new Error("Not configured");
203
+ }
204
+
205
+ return _configuration;
206
+ };
207
+
208
+ /**
209
+ * Combine two values.
210
+ *
211
+ * This method clones val2 before using any of its properties to try to ensure
212
+ * the combined object is not linked back to the original.
213
+ *
214
+ * If the values are objects, it will merge them at the top level. Properties
215
+ * themselves are not merged; val2 properties will overwrite val1 where there
216
+ * are conflicts
217
+ *
218
+ * If the values are arrays, it will concatenate and dedupe them.
219
+ * NOTE: duplicates in either val1 or val2 will also be deduped.
220
+ *
221
+ * If the values are any other type, or val2 has a different type to val1, val2
222
+ * will be returned.
223
+ */
224
+
225
+ const combineTopLevel = (val1, val2) => {
226
+ const obj2Clone = clone(val2); // Only merge if they're both arrays or both objects.
227
+ // If not, we will just return val2.
228
+
229
+ if (val1 !== null && val2 !== null && typeof val1 === "object" && typeof val2 === "object") {
230
+ const val1IsArray = Array.isArray(val1);
231
+ const val2IsArray = Array.isArray(val2);
232
+
233
+ if (val1IsArray && val2IsArray) {
234
+ return Array.from(new Set([].concat(val1, obj2Clone)));
235
+ } else if (!val1IsArray && !val2IsArray) {
236
+ return _extends({}, val1, obj2Clone);
237
+ }
238
+ }
239
+
240
+ return obj2Clone;
241
+ };
242
+
243
+ /**
244
+ * Combine one or more objects into a single object.
245
+ *
246
+ * Objects later in the argument list take precedence over those that are
247
+ * earlier. Object and array values at the root level are merged.
248
+ */
249
+
250
+ const combineOptions = (...toBeCombined) => {
251
+ const combined = toBeCombined.filter(Boolean).reduce((acc, cur) => {
252
+ for (const key of Object.keys(cur)) {
253
+ // We always call combine, even if acc[key] is undefined
254
+ // because we need to make sure we clone values.
255
+ acc[key] = combineTopLevel(acc[key], cur[key]);
256
+ }
257
+
258
+ return acc;
259
+ }, {}); // We know that we are creating a compatible return type.
260
+ // $FlowIgnore[incompatible-return]
261
+
262
+ return combined;
263
+ };
264
+
265
+ /**
266
+ * Describe a group of fixtures for a given component.
267
+ *
268
+ * Only one `fixtures` call should be used per fixture file as it returns
269
+ * the exports for that file.
270
+ *
271
+ * @param {FixtureOptions<TProps>} options Options describing the
272
+ * fixture group.
273
+ * @param {FixtureFn<TProps> => void} fn A function that provides a `fixture`
274
+ * function for defining fixtures.
275
+ * @returns {Exports} The object to be exported as `module.exports`.
276
+ *
277
+ * TODO(somewhatabstract): Determine a way around this requirement so we
278
+ * can support named exports and default exports via the adapters in a
279
+ * deterministic way. Currently this is imposed on us because of how
280
+ * storybook, the popular framework, uses both default and named exports for
281
+ * its interface.
282
+ */
283
+ const fixtures = (options, fn) => {
284
+ var _additionalAdapterOpt;
285
+
286
+ const {
287
+ adapter,
288
+ defaultAdapterOptions
289
+ } = getConfiguration();
290
+ const {
291
+ title,
292
+ component,
293
+ description: groupDescription,
294
+ defaultWrapper,
295
+ additionalAdapterOptions
296
+ } = options; // 1. Create a new adapter group.
297
+
298
+ const group = adapter.declareGroup({
299
+ title: title || component.displayName || component.name || "Component",
300
+ description: groupDescription
301
+ }); // 2. Invoke fn with a function that can add a new fixture.
302
+
303
+ const addFixture = (description, props, wrapper = null) => {
304
+ var _ref;
305
+
306
+ group.declareFixture({
307
+ description,
308
+ getProps: options => typeof props === "function" ? props(options) : props,
309
+ component: (_ref = wrapper != null ? wrapper : defaultWrapper) != null ? _ref : component
310
+ });
311
+ };
312
+
313
+ fn(addFixture); // 3. Combine the adapter options from the fixture group with the
314
+ // defaults from our setup.
315
+
316
+ const groupAdapterOverrides = (_additionalAdapterOpt = additionalAdapterOptions == null ? void 0 : additionalAdapterOptions[adapter.name]) != null ? _additionalAdapterOpt : {};
317
+ const combinedAdapterOptions = combineOptions(defaultAdapterOptions, groupAdapterOverrides); // 4. Call close on the group and return the result.
318
+
319
+ return group.closeGroup(combinedAdapterOptions);
320
+ };
321
+
322
+ // Opt this file out of coverage because it's super hard to test.
323
+
324
+ /* istanbul ignore file */
325
+
326
+ /**
327
+ * Isolate imports within a given action using jest.isolateModules.
328
+ *
329
+ * This is a helper for the `jest.isolateModules` API, allowing
330
+ * code to avoid the clunky closure syntax in their tests.
331
+ *
332
+ * @param {() => T} action The action that contains the isolated module imports.
333
+ * We do it this way so that any `require` calls are relative to the calling
334
+ * code and not this function. Note that we don't support promises here to
335
+ * discourage dynamic `import` use, which doesn't play well with standard
336
+ * jest yet.
337
+ */
338
+ const isolateModules = action => {
339
+ if (typeof jest === "undefined") {
340
+ throw new Error(`jest is not available in global scope`);
341
+ }
342
+
343
+ let result = undefined;
344
+ jest.isolateModules(() => {
345
+ result = action();
346
+ }); // We know that we'll have a result of the appropriate type at this point.
347
+ // We could use a promise to make everything happy, but this doesn't need
348
+ // to be async, so why bother.
349
+ // $FlowIgnore[incompatible-return]
350
+
351
+ return result;
352
+ };
353
+
354
+ export { adapters, fixtures, isolateModules, setup as setupFixtures };