@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.
@@ -0,0 +1,88 @@
1
+ // @flow
2
+ import type {
3
+ AdapterGroup as AdapterGroupInterface,
4
+ AdapterGroupOptions,
5
+ AdapterFixtureOptions,
6
+ } from "../types.js";
7
+
8
+ export type CloseGroupFn<TProps: {...}, Options: {...}, Exports: {...}> = (
9
+ options: $ReadOnly<AdapterGroupOptions>,
10
+ adapterOptions: ?$ReadOnly<Options>,
11
+ declaredFixtures: $ReadOnlyArray<AdapterFixtureOptions<TProps>>,
12
+ ) => ?$ReadOnly<Exports>;
13
+
14
+ /**
15
+ * Simple adapter group implementation.
16
+ */
17
+ export class AdapterGroup<TProps: {...}, Options: {...}, Exports: {...}>
18
+ implements AdapterGroupInterface<TProps, Options, Exports>
19
+ {
20
+ _closeGroupFn: ?CloseGroupFn<TProps, Options, Exports>;
21
+ +_fixtures: Array<AdapterFixtureOptions<TProps>>;
22
+ +_options: $ReadOnly<AdapterGroupOptions>;
23
+
24
+ /**
25
+ * Create an adapter group.
26
+ *
27
+ * @param {CloseGroupFn<TProps, Options, Exports>} closeGroupFn A function
28
+ * to invoke when the group is closed.
29
+ * @param {AdapterGroupOptions} options The options for the group.
30
+ */
31
+ constructor(
32
+ closeGroupFn: CloseGroupFn<TProps, Options, Exports>,
33
+ options: $ReadOnly<AdapterGroupOptions>,
34
+ ) {
35
+ if (typeof closeGroupFn !== "function") {
36
+ throw new TypeError("closeGroupFn must be a function");
37
+ }
38
+ if (typeof options !== "object" || options === null) {
39
+ throw new TypeError("options must be an object");
40
+ }
41
+ this._closeGroupFn = closeGroupFn;
42
+ this._options = options;
43
+ this._fixtures = [];
44
+ }
45
+
46
+ /**
47
+ * Close the group.
48
+ *
49
+ * This declares that no more fixtures are to be added to the group,
50
+ * and will call the parent adapter with the declared fixtures so that they
51
+ * can be adapted for the target fixture framework, such as Storybook.
52
+ */
53
+ +closeGroup: (
54
+ adapterOptions: ?$ReadOnly<Partial<Options>>,
55
+ ) => ?$ReadOnly<Exports> = (adapterOptions = null) => {
56
+ if (this._closeGroupFn == null) {
57
+ throw new Error("Group already closed");
58
+ }
59
+
60
+ try {
61
+ return this._closeGroupFn(
62
+ this._options,
63
+ adapterOptions,
64
+ this._fixtures,
65
+ );
66
+ } finally {
67
+ this._closeGroupFn = null;
68
+ }
69
+ };
70
+
71
+ /**
72
+ * Declare a fixture within the group.
73
+ *
74
+ * @param {AdapterFixtureOptions<Config>} fixtureOptions The options
75
+ * describing the fixture.
76
+ */
77
+ +declareFixture: (
78
+ options: $ReadOnly<AdapterFixtureOptions<TProps>>,
79
+ ) => void = (options) => {
80
+ if (typeof options !== "object" || options === null) {
81
+ throw new TypeError("options must be an object");
82
+ }
83
+ if (this._closeGroupFn == null) {
84
+ throw new Error("Cannot declare fixtures after closing the group");
85
+ }
86
+ this._fixtures.push(options);
87
+ };
88
+ }
@@ -0,0 +1,63 @@
1
+ // @flow
2
+ import {AdapterGroup, type CloseGroupFn} from "./adapter-group.js";
3
+ import type {
4
+ Adapter as AdapterInterface,
5
+ AdapterGroup as AdapterGroupInterface,
6
+ AdapterGroupOptions,
7
+ } from "../types.js";
8
+
9
+ /**
10
+ * Class for implementing a custom adapter.
11
+ */
12
+ export class Adapter<Options: {...}, Exports: {...}>
13
+ implements AdapterInterface<Options, Exports>
14
+ {
15
+ +_name: string;
16
+ +_closeGroupFn: CloseGroupFn<any, Options, Exports>;
17
+
18
+ /**
19
+ * @param {string} name The name of the adapter.
20
+ * @param {CloseGroupFn<any, Options, Exports>} closeGroupFn The function
21
+ * an adapter group should call when the group is closed. This is invoked
22
+ * by an adapter group when it is closed. This function is where an
23
+ * adapter implements the logic to generate the actual fixtures for the
24
+ * adapter's target framework.
25
+ */
26
+ constructor(
27
+ name: string,
28
+ closeGroupFn: CloseGroupFn<any, Options, Exports>,
29
+ ) {
30
+ if (typeof name !== "string") {
31
+ throw new TypeError("name must be a string");
32
+ }
33
+ if (name.trim() === "") {
34
+ throw new Error("name must be a non-empty string");
35
+ }
36
+ if (typeof closeGroupFn !== "function") {
37
+ throw new TypeError("closeGroupFn must be a function");
38
+ }
39
+
40
+ this._name = name;
41
+ this._closeGroupFn = closeGroupFn;
42
+ }
43
+
44
+ /**
45
+ * The name of the adapter.
46
+ */
47
+ get name(): string {
48
+ return this._name;
49
+ }
50
+
51
+ /**
52
+ * Declare a new fixture group.
53
+ *
54
+ * @param {AdapterGroupOptions} options The options describing the fixture
55
+ * group.
56
+ * @returns {AdapterGroupInterface} The new fixture group.
57
+ */
58
+ declareGroup<Config: {...}>(
59
+ options: $ReadOnly<AdapterGroupOptions>,
60
+ ): AdapterGroupInterface<Config, Options, Exports> {
61
+ return new AdapterGroup(this._closeGroupFn, options);
62
+ }
63
+ }
@@ -0,0 +1,2 @@
1
+ // @flow
2
+ export {getAdapter as storybook} from "./storybook.js";
@@ -0,0 +1,119 @@
1
+ // @flow
2
+ import * as React from "react";
3
+ import {action} from "@storybook/addon-actions";
4
+ import {Adapter} from "./adapter.js";
5
+
6
+ import type {
7
+ AdapterGroupOptions,
8
+ AdapterFixtureOptions,
9
+ AdapterFactory,
10
+ } from "../types.js";
11
+
12
+ type StoryContext = {|
13
+ args: $ReadOnly<any>,
14
+ argTypes: $ReadOnly<any>,
15
+ globals: $ReadOnlyArray<any>,
16
+ hooks: $ReadOnlyArray<any>,
17
+ parameters: $ReadOnly<any>,
18
+ viewMode: mixed,
19
+ |};
20
+
21
+ export type StorybookOptions = {|
22
+ decorators?: Array<
23
+ (story: React.ComponentType<any>, context: StoryContext) => React.Node,
24
+ >,
25
+ parameters?: $ReadOnly<any>,
26
+ |};
27
+
28
+ type DefaultExport = {|
29
+ title: string,
30
+ ...StorybookOptions,
31
+ |};
32
+
33
+ type Exports<TProps: {...}> = {|
34
+ default: DefaultExport,
35
+ [story: string]: React.ComponentType<TProps>,
36
+ |};
37
+
38
+ /**
39
+ * Get a fixture framework adapter for Storybook support.
40
+ */
41
+ export const getAdapter: AdapterFactory<StorybookOptions, Exports<any>> = (
42
+ MountingComponent = null,
43
+ ) =>
44
+ new Adapter<StorybookOptions, Exports<any>>(
45
+ "storybook",
46
+ <TProps: {...}>(
47
+ {
48
+ title,
49
+ description: groupDescription,
50
+ }: $ReadOnly<AdapterGroupOptions>,
51
+ adapterOptions: ?$ReadOnly<StorybookOptions>,
52
+ declaredFixtures: $ReadOnlyArray<AdapterFixtureOptions<TProps>>,
53
+ ): ?$ReadOnly<Exports<TProps>> => {
54
+ const templateMap = new WeakMap();
55
+
56
+ const log = (message, ...args) => action(message)(...args);
57
+
58
+ const exports = declaredFixtures.reduce(
59
+ (acc, {description, getProps, component: Component}, i) => {
60
+ const storyName = `${i + 1} ${description}`;
61
+ const exportName = storyName
62
+ // Make word boundaries start with an upper case letter.
63
+ .replace(/\b\w/g, (c) => c.toUpperCase())
64
+ // Remove all non-alphanumeric characters.
65
+ .replace(/[^\w]+/g, "")
66
+ // Remove all underscores.
67
+ .replace(/[_]+/g, "");
68
+
69
+ // We create a “template” of how args map to rendering
70
+ // for each type of component as the component here could
71
+ // be the component under test, or wrapped in a wrapper
72
+ // component. We don't use decorators for the wrapper
73
+ // because we may not be in a storybook context and it
74
+ // keeps the framework API simpler this way.
75
+ let Template = templateMap.get(Component);
76
+ if (Template == null) {
77
+ // The MountingComponent is a bit different than just a
78
+ // Storybook decorator. It's a React component that
79
+ // takes over rendering the component in the fixture
80
+ // with the given args, allowing for greater
81
+ // customization in a platform-agnostic manner (i.e.
82
+ // not just story format).
83
+ Template = MountingComponent
84
+ ? (args) => (
85
+ <MountingComponent
86
+ component={Component}
87
+ props={args}
88
+ log={log}
89
+ />
90
+ )
91
+ : (args) => <Component {...args} />;
92
+ templateMap.set(Component, Template);
93
+ }
94
+
95
+ // Each story that shares that component then reuses that
96
+ // template.
97
+ acc[exportName] = Template.bind({});
98
+ acc[exportName].args = getProps({log});
99
+ // Adding a story name here means that we don't have to
100
+ // care about naming the exports correctly, if we don't
101
+ // want (useful if we need to autogenerate or manually
102
+ // expose ESM exports).
103
+ acc[exportName].storyName = storyName;
104
+
105
+ return acc;
106
+ },
107
+ {
108
+ default: {
109
+ title,
110
+ // TODO(somewhatabstract): Use groupDescription
111
+ // Possibly via a decorator?
112
+ ...adapterOptions,
113
+ },
114
+ },
115
+ );
116
+
117
+ return Object.freeze(exports);
118
+ },
119
+ );
@@ -0,0 +1,25 @@
1
+ // @flow
2
+ import {combineTopLevel} from "./combine-top-level.js";
3
+
4
+ /**
5
+ * Combine one or more objects into a single object.
6
+ *
7
+ * Objects later in the argument list take precedence over those that are
8
+ * earlier. Object and array values at the root level are merged.
9
+ */
10
+ export const combineOptions = <Options: {...}>(
11
+ ...toBeCombined: $ReadOnlyArray<Partial<Options>>
12
+ ): $ReadOnly<Partial<Options>> => {
13
+ const combined = toBeCombined.filter(Boolean).reduce((acc, cur) => {
14
+ for (const key of Object.keys(cur)) {
15
+ // We always call combine, even if acc[key] is undefined
16
+ // because we need to make sure we clone values.
17
+ acc[key] = combineTopLevel(acc[key], cur[key]);
18
+ }
19
+ return acc;
20
+ }, {});
21
+
22
+ // We know that we are creating a compatible return type.
23
+ // $FlowIgnore[incompatible-return]
24
+ return combined;
25
+ };
@@ -0,0 +1,44 @@
1
+ // @flow
2
+ import {clone} from "@khanacademy/wonder-stuff-core";
3
+
4
+ /**
5
+ * Combine two values.
6
+ *
7
+ * This method clones val2 before using any of its properties to try to ensure
8
+ * the combined object is not linked back to the original.
9
+ *
10
+ * If the values are objects, it will merge them at the top level. Properties
11
+ * themselves are not merged; val2 properties will overwrite val1 where there
12
+ * are conflicts
13
+ *
14
+ * If the values are arrays, it will concatenate and dedupe them.
15
+ * NOTE: duplicates in either val1 or val2 will also be deduped.
16
+ *
17
+ * If the values are any other type, or val2 has a different type to val1, val2
18
+ * will be returned.
19
+ */
20
+ export const combineTopLevel = (
21
+ val1: $ReadOnly<any>,
22
+ val2: $ReadOnly<any>,
23
+ ): any => {
24
+ const obj2Clone = clone(val2);
25
+
26
+ // Only merge if they're both arrays or both objects.
27
+ // If not, we will just return val2.
28
+ if (
29
+ val1 !== null &&
30
+ val2 !== null &&
31
+ typeof val1 === "object" &&
32
+ typeof val2 === "object"
33
+ ) {
34
+ const val1IsArray = Array.isArray(val1);
35
+ const val2IsArray = Array.isArray(val2);
36
+
37
+ if (val1IsArray && val2IsArray) {
38
+ return Array.from(new Set([...val1, ...obj2Clone]));
39
+ } else if (!val1IsArray && !val2IsArray) {
40
+ return {...val1, ...obj2Clone};
41
+ }
42
+ }
43
+ return obj2Clone;
44
+ };
@@ -0,0 +1,64 @@
1
+ // @flow
2
+ import * as React from "react";
3
+
4
+ import {setupFixtures, fixtures, adapters} from "../index.js";
5
+
6
+ // Normally would call setup from the storybook.main.js for a project.
7
+ setupFixtures({
8
+ adapter: adapters.storybook(),
9
+ });
10
+
11
+ const MyComponent = (props) =>
12
+ `I am a component. Here are my props: ${JSON.stringify(props, null, 2)}`;
13
+
14
+ const Wrapper = (props) => (
15
+ <>
16
+ Wrapper &gt;&gt;&gt;
17
+ <MyComponent {...props} />
18
+ &lt;&lt;&lt; Wrapper
19
+ </>
20
+ );
21
+
22
+ const stories: Array<mixed> = Object.values(
23
+ fixtures(
24
+ {
25
+ component: MyComponent,
26
+ title: "Testing/Fixtures/Basic",
27
+ },
28
+ (fixture) => {
29
+ fixture("This is a fixture with some regular props", {
30
+ see: "this is a prop",
31
+ and: "this is another",
32
+ });
33
+
34
+ fixture(
35
+ "This is a fixture with props from functions, and a bit of logging",
36
+ ({log}) => {
37
+ log(
38
+ "This is a log from a fixture during props generation",
39
+ {
40
+ and: "some data",
41
+ },
42
+ );
43
+ return {
44
+ this: "prop was made from a function",
45
+ };
46
+ },
47
+ );
48
+
49
+ fixture(
50
+ "This fixture uses a custom wrapper",
51
+ {
52
+ just: "some props again",
53
+ like: "this one",
54
+ },
55
+ Wrapper,
56
+ );
57
+ },
58
+ ) ?? {},
59
+ );
60
+
61
+ export default stories[0];
62
+ export const F1 = stories[1];
63
+ export const F2 = stories[2];
64
+ export const F3 = stories[3];
@@ -0,0 +1,59 @@
1
+ // @flow
2
+ import * as React from "react";
3
+
4
+ import {setupFixtures, fixtures, adapters} from "../index.js";
5
+
6
+ // Normally would call setup from the storybook.main.js for a project.
7
+ setupFixtures({
8
+ adapter: adapters.storybook(),
9
+ });
10
+
11
+ const MyComponent = (props) => `My props: ${JSON.stringify(props, null, 2)}`;
12
+
13
+ const Wrapper = (props) => (
14
+ <>
15
+ Wrapper &gt;&gt;&gt;
16
+ <MyComponent {...props} />
17
+ &lt;&lt;&lt; Wrapper
18
+ </>
19
+ );
20
+
21
+ const DefaultWrapper = (props) => (
22
+ <>
23
+ DefaultWrapper &gt;&gt;&gt;
24
+ <MyComponent {...props} />
25
+ &lt;&lt;&lt; DefaultWrapper
26
+ </>
27
+ );
28
+
29
+ const stories: Array<mixed> = Object.values(
30
+ fixtures(
31
+ {
32
+ component: MyComponent,
33
+ title: "Testing/Fixtures/DefaultWrapper",
34
+ defaultWrapper: DefaultWrapper,
35
+ },
36
+ (fixture) => {
37
+ fixture(
38
+ "This is a fixture with some regular props and the default wrapper",
39
+ {
40
+ see: "this is a prop",
41
+ and: "this is another",
42
+ },
43
+ );
44
+
45
+ fixture(
46
+ "This fixture uses a custom wrapper",
47
+ {
48
+ just: "some props again",
49
+ like: "this one",
50
+ },
51
+ Wrapper,
52
+ );
53
+ },
54
+ ) ?? {},
55
+ );
56
+
57
+ export default stories[0];
58
+ export const F1 = stories[1];
59
+ export const F2 = stories[2];
@@ -0,0 +1,77 @@
1
+ // @flow
2
+ import * as React from "react";
3
+ import {getConfiguration} from "./setup.js";
4
+ import {combineOptions} from "./combine-options.js";
5
+
6
+ import type {FixturesOptions, GetPropsOptions} from "./types.js";
7
+
8
+ type FixtureProps<TProps: {...}> =
9
+ | $ReadOnly<TProps>
10
+ | ((options: $ReadOnly<GetPropsOptions>) => $ReadOnly<TProps>);
11
+
12
+ /**
13
+ * Describe a group of fixtures for a given component.
14
+ *
15
+ * Only one `fixtures` call should be used per fixture file as it returns
16
+ * the exports for that file.
17
+ *
18
+ * @param {FixtureOptions<TProps>} options Options describing the
19
+ * fixture group.
20
+ * @param {FixtureFn<TProps> => void} fn A function that provides a `fixture`
21
+ * function for defining fixtures.
22
+ * @returns {Exports} The object to be exported as `module.exports`.
23
+ *
24
+ * TODO(somewhatabstract): Determine a way around this requirement so we
25
+ * can support named exports and default exports via the adapters in a
26
+ * deterministic way. Currently this is imposed on us because of how
27
+ * storybook, the popular framework, uses both default and named exports for
28
+ * its interface.
29
+ */
30
+ export const fixtures = <TProps: {...}>(
31
+ options: $ReadOnly<FixturesOptions<TProps>>,
32
+ fn: (
33
+ fixture: (
34
+ description: string,
35
+ props: FixtureProps<TProps>,
36
+ wrapper?: React.ComponentType<TProps>,
37
+ ) => void,
38
+ ) => void,
39
+ ): ?$ReadOnly<mixed> => {
40
+ const {adapter, defaultAdapterOptions} = getConfiguration();
41
+ const {
42
+ title,
43
+ component,
44
+ description: groupDescription,
45
+ defaultWrapper,
46
+ additionalAdapterOptions,
47
+ } = options;
48
+
49
+ // 1. Create a new adapter group.
50
+ const group = adapter.declareGroup<TProps>({
51
+ title: title || component.displayName || component.name || "Component",
52
+ description: groupDescription,
53
+ });
54
+
55
+ // 2. Invoke fn with a function that can add a new fixture.
56
+ const addFixture = (description, props, wrapper = null): void => {
57
+ group.declareFixture({
58
+ description,
59
+ getProps: (options) =>
60
+ typeof props === "function" ? props(options) : props,
61
+ component: wrapper ?? defaultWrapper ?? component,
62
+ });
63
+ };
64
+ fn(addFixture);
65
+
66
+ // 3. Combine the adapter options from the fixture group with the
67
+ // defaults from our setup.
68
+ const groupAdapterOverrides =
69
+ additionalAdapterOptions?.[adapter.name] ?? {};
70
+ const combinedAdapterOptions = combineOptions(
71
+ defaultAdapterOptions,
72
+ groupAdapterOverrides,
73
+ );
74
+
75
+ // 4. Call close on the group and return the result.
76
+ return group.closeGroup(combinedAdapterOptions);
77
+ };
@@ -0,0 +1,26 @@
1
+ // @flow
2
+ import type {Configuration} from "./types.js";
3
+
4
+ let _configuration: ?$ReadOnly<Configuration<any, any>> = null;
5
+
6
+ /**
7
+ * Setup the fixture framework.
8
+ */
9
+ export const setup = <TAdapterOptions: {...}, TAdapterExports: {...}>(
10
+ configuration: $ReadOnly<Configuration<TAdapterOptions, TAdapterExports>>,
11
+ ) => {
12
+ _configuration = configuration;
13
+ };
14
+
15
+ /**
16
+ * Get the framework configuration.
17
+ *
18
+ * @returns {Configuration} The configuration as provided via setup().
19
+ * @throws {Error} If the configuration has not been set.
20
+ */
21
+ export const getConfiguration = (): $ReadOnly<Configuration<any, any>> => {
22
+ if (_configuration == null) {
23
+ throw new Error("Not configured");
24
+ }
25
+ return _configuration;
26
+ };