@pie-element/shared-test-utils 0.1.1-next.1 → 0.1.1-next.20261002100925

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/README.md CHANGED
@@ -1,11 +1,11 @@
1
- # @pie-element/test-utils
1
+ # @pie-element/shared-test-utils
2
2
 
3
3
  Testing utilities for PIE element development.
4
4
 
5
5
  ## Installation
6
6
 
7
7
  ```bash
8
- bun add -D @pie-element/test-utils
8
+ bun add -D @pie-element/shared-test-utils
9
9
  ```
10
10
 
11
11
  ## Usage
@@ -13,13 +13,13 @@ bun add -D @pie-element/test-utils
13
13
  ### Controller Testing
14
14
 
15
15
  ```typescript
16
- import { testController, testEnvironments } from '@pie-element/test-utils';
16
+ import { testController, testEnvironments } from '@pie-element/shared-test-utils';
17
17
  import { myController } from './controller';
18
18
 
19
19
  const testCases = [
20
20
  {
21
21
  name: 'returns correct view model in gather mode',
22
- question: { id: '1', element: '@pie-element/my-element' },
22
+ question: { id: '1', element: 'my-element' },
23
23
  session: null,
24
24
  env: testEnvironments.studentGather,
25
25
  expectedViewModel: {
@@ -36,7 +36,7 @@ console.log(results); // [{ passed: true, testCase: '...', errors: [] }]
36
36
  ### Fixtures
37
37
 
38
38
  ```typescript
39
- import { createTestModel, createTestSession, testPrompts } from '@pie-element/test-utils';
39
+ import { createTestModel, createTestSession, testPrompts } from '@pie-element/shared-test-utils';
40
40
 
41
41
  const model = createTestModel({ prompt: testPrompts.withMath });
42
42
  const session = createTestSession({ value: ['answer1'] });
@@ -50,7 +50,7 @@ import {
50
50
  waitForEvent,
51
51
  simulateClick,
52
52
  querySelector,
53
- } from '@pie-element/test-utils';
53
+ } from '@pie-element/shared-test-utils';
54
54
 
55
55
  // Mount a component
56
56
  const element = await mountComponent('my-element', {
@@ -58,14 +58,37 @@ const element = await mountComponent('my-element', {
58
58
  session: mySession,
59
59
  });
60
60
 
61
- // Wait for events
62
- const sessionData = await waitForEvent(element, 'pie.session_changed');
61
+ // Wait for events: resolves with the event's detail
62
+ const { complete } = await waitForEvent<{ complete: boolean; component: string }>(
63
+ element,
64
+ 'session-changed'
65
+ );
63
66
 
64
67
  // Simulate interactions
65
68
  const button = querySelector(element, 'button');
66
69
  simulateClick(button);
67
70
  ```
68
71
 
72
+ ### Author Element Contract
73
+
74
+ `assertAuthorModelUpdate` mounts an author element, sets `model` and `configuration` as a player does, makes one edit, and throws unless the edit's `model.updated` meets the [Authoring Contract](https://github.com/pie-framework/pie-elements-ng/blob/develop/docs/PIE_ELEMENT_CONTRACT.md#authoring-contract). `assertAuthorElementProperties` checks only that the element declares both properties.
75
+
76
+ ```typescript
77
+ import { assertAuthorModelUpdate } from '@pie-element/shared-test-utils';
78
+
79
+ const { event, cleanup } = await assertAuthorModelUpdate({
80
+ tag: 'my-element-config',
81
+ model: { id: '1', element: 'my-element', prompt: '<p>Q</p>' },
82
+ settle: async () => {
83
+ await new Promise((r) => setTimeout(r, 0));
84
+ flushSync(); // Svelte
85
+ },
86
+ edit: (element) => typeInto(element.querySelector('input'), 'edited'),
87
+ });
88
+ expect(event.detail.update).toMatchObject({ prompt: '<p>Q</p>' });
89
+ cleanup();
90
+ ```
91
+
69
92
  ## API Reference
70
93
 
71
94
  See [TypeScript definitions](./src/index.ts) for complete API documentation.
@@ -0,0 +1,42 @@
1
+ /**
2
+ * Author Element Contract
3
+ *
4
+ * Checks for the host-facing half of an author element, as
5
+ * `docs/PIE_ELEMENT_CONTRACT.md` sets it out under "Authoring Contract". They
6
+ * throw on a violation, so they run under any test runner.
7
+ */
8
+ type ModelUpdated = CustomEvent<{
9
+ update: unknown;
10
+ reset: boolean;
11
+ }> & {
12
+ update?: unknown;
13
+ reset?: unknown;
14
+ };
15
+ export interface AuthorModelUpdateOptions {
16
+ /** A tag the author element is registered under. */
17
+ tag: string;
18
+ /** The item's model, with the `id` and `element` a player stamps on it. */
19
+ model: Record<string, unknown>;
20
+ configuration?: Record<string, unknown>;
21
+ /** Makes one edit through the authoring view. */
22
+ edit: (element: HTMLElement) => void | Promise<void>;
23
+ /** Lets the element render once its properties are set; defaults to one macrotask. */
24
+ settle?: () => void | Promise<void>;
25
+ }
26
+ export interface AuthorModelUpdate {
27
+ element: HTMLElement;
28
+ /** The edit's `model.updated`, as a host hears it. */
29
+ event: ModelUpdated;
30
+ /** Removes the element and the ancestor it was mounted under. */
31
+ cleanup: () => void;
32
+ }
33
+ /** Throws unless the element declares the properties a player sets: `model`, then `configuration`. */
34
+ export declare function assertAuthorElementProperties(tag: string): void;
35
+ /**
36
+ * Mounts the element under an ancestor, sets `model` and `configuration` as a
37
+ * player does, makes the edit, and throws unless exactly one `model.updated`
38
+ * meets the contract and a readable `model` keeps the edit across a detach and
39
+ * re-attach. Returns that event for element-specific assertions.
40
+ */
41
+ export declare function assertAuthorModelUpdate(options: AuthorModelUpdateOptions): Promise<AuthorModelUpdate>;
42
+ export {};
@@ -0,0 +1,119 @@
1
+ /**
2
+ * Author Element Contract
3
+ *
4
+ * Checks for the host-facing half of an author element, as
5
+ * `docs/PIE_ELEMENT_CONTRACT.md` sets it out under "Authoring Contract". They
6
+ * throw on a violation, so they run under any test runner.
7
+ */
8
+ const PLAYER_PROPERTIES = ['model', 'configuration'];
9
+ function hasSetter(prototype, name) {
10
+ for (let p = prototype; p && p !== HTMLElement.prototype; p = Object.getPrototypeOf(p)) {
11
+ if (Object.getOwnPropertyDescriptor(p, name)?.set)
12
+ return true;
13
+ }
14
+ return false;
15
+ }
16
+ // Models are JSON: compare as such, with key order ignored.
17
+ function sameJson(a, b) {
18
+ if (a === b)
19
+ return true;
20
+ if (typeof a !== 'object' || typeof b !== 'object' || a === null || b === null)
21
+ return false;
22
+ if (Array.isArray(a) !== Array.isArray(b))
23
+ return false;
24
+ const aKeys = Object.keys(a).filter((k) => a[k] !== undefined);
25
+ const bKeys = Object.keys(b).filter((k) => b[k] !== undefined);
26
+ return (aKeys.length === bKeys.length && aKeys.every((k) => sameJson(a[k], b[k])));
27
+ }
28
+ function fail(tag, problems) {
29
+ if (problems.length) {
30
+ throw new Error(`${tag} breaks the authoring contract:\n- ${problems.join('\n- ')}`);
31
+ }
32
+ }
33
+ /** Throws unless the element declares the properties a player sets: `model`, then `configuration`. */
34
+ export function assertAuthorElementProperties(tag) {
35
+ const ctor = customElements.get(tag);
36
+ if (!ctor)
37
+ throw new Error(`${tag} is not registered`);
38
+ fail(tag, PLAYER_PROPERTIES.filter((name) => !hasSetter(ctor.prototype, name)).map((name) => `declares no \`${name}\` property, so a player's \`element.${name} = …\` is ignored`));
39
+ }
40
+ /**
41
+ * Mounts the element under an ancestor, sets `model` and `configuration` as a
42
+ * player does, makes the edit, and throws unless exactly one `model.updated`
43
+ * meets the contract and a readable `model` keeps the edit across a detach and
44
+ * re-attach. Returns that event for element-specific assertions.
45
+ */
46
+ export async function assertAuthorModelUpdate(options) {
47
+ const { tag, model, configuration, edit, settle = () => new Promise((r) => setTimeout(r, 0)), } = options;
48
+ assertAuthorElementProperties(tag);
49
+ const root = document.createElement('div');
50
+ document.body.appendChild(root);
51
+ const element = document.createElement(tag);
52
+ const cleanup = () => root.remove();
53
+ const heard = [];
54
+ let captured = 0;
55
+ // The item player listens on an ancestor in the capture phase, legacy
56
+ // pie-author in the bubble phase.
57
+ root.addEventListener('model.updated', () => captured++, true);
58
+ root.addEventListener('model.updated', (e) => {
59
+ heard.push({ event: e, modelAtDispatch: element.model });
60
+ });
61
+ try {
62
+ root.appendChild(element);
63
+ element.model = structuredClone(model);
64
+ if (configuration)
65
+ element.configuration = structuredClone(configuration);
66
+ await settle();
67
+ // Elements may announce the model they were given; only the edit's event counts.
68
+ heard.length = 0;
69
+ captured = 0;
70
+ await edit(element);
71
+ if (captured > heard.length) {
72
+ fail(tag, ['`model.updated` does not bubble, so legacy pie-author never hears it']);
73
+ }
74
+ if (heard.length !== 1) {
75
+ fail(tag, [`an edit reached an ancestor as ${heard.length} \`model.updated\` events, not 1`]);
76
+ }
77
+ const [{ event, modelAtDispatch }] = heard;
78
+ const update = event.detail?.update;
79
+ const problems = [];
80
+ if (event.target !== element) {
81
+ problems.push('dispatches `model.updated` from an inner node instead of the element');
82
+ }
83
+ if (event.update !== event.detail?.update || event.reset !== event.detail?.reset) {
84
+ problems.push('dispatches a plain CustomEvent; legacy pie-author reads `event.update`, which a `ModelUpdatedEvent` carries');
85
+ }
86
+ if (typeof event.detail?.reset !== 'boolean') {
87
+ problems.push('`detail.reset` is not a boolean');
88
+ }
89
+ if (!update || update.id !== model.id || update.element !== model.element) {
90
+ problems.push("`detail.update` lacks the model's `id` and `element`, which hosts match it by");
91
+ }
92
+ if (update && event.detail?.reset === false) {
93
+ const dropped = Object.keys(model).filter((k) => model[k] !== undefined && !(k in update));
94
+ if (dropped.length) {
95
+ problems.push(`\`detail.update\` leaves out ${dropped.map((k) => `\`${k}\``).join(', ')}; it is the whole model`);
96
+ }
97
+ }
98
+ if (modelAtDispatch !== undefined && !sameJson(modelAtDispatch, update)) {
99
+ problems.push('`element.model` does not hold the edit when `model.updated` fires');
100
+ }
101
+ fail(tag, problems);
102
+ if (modelAtDispatch !== undefined) {
103
+ // A host may move the element; the edit has to outlive the remount.
104
+ element.remove();
105
+ await settle();
106
+ root.appendChild(element);
107
+ await settle();
108
+ if (!sameJson(element.model, update)) {
109
+ fail(tag, ['`element.model` loses the edit when the element is detached and re-attached']);
110
+ }
111
+ }
112
+ return { element, event, cleanup };
113
+ }
114
+ catch (error) {
115
+ cleanup();
116
+ throw error;
117
+ }
118
+ }
119
+ //# sourceMappingURL=author-contract.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"author-contract.js","sourceRoot":"","sources":["../src/author-contract.ts"],"names":[],"mappings":"AAAA;;;;;;GAMG;AA6BH,MAAM,iBAAiB,GAAG,CAAC,OAAO,EAAE,eAAe,CAAU,CAAC;AAE9D,SAAS,SAAS,CAAC,SAAwB,EAAE,IAAY;IACvD,KAAK,IAAI,CAAC,GAAG,SAAS,EAAE,CAAC,IAAI,CAAC,KAAK,WAAW,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C;QACrF,CAAC;QACD,IAAI,CAAC,GAAG,EAAE,QAAQ,CAAC,CAAC;QAEpB,IAAI,eAAe,KAAK,SAAS,EAAE,CAAC;YAClC,oEAAoE;YACpE,OAAO,CAAC,MAAM,EAAE,CAAC;YACjB,MAAM,MAAM,EAAE,CAAC;YACf,IAAI,CAAC,WAAW,CAAC,OAAO,CAAC,CAAC;YAC1B,MAAM,MAAM,EAAE,CAAC;YACf,IAAI,CAAC,QAAQ,CAAC,OAAO,CAAC,KAAK,EAAE,MAAM,CAAC,EAAE,CAAC;gBACrC,IAAI,CAAC,GAAG,EAAE,CAAC,6EAA6E,CAAC,CAAC,CAAC;YAC7F,CAAC;QACH,CAAC;QAED,OAAO,EAAE,OAAO,EAAE,KAAK,EAAE,OAAO,EAAE,CAAC;IACrC,CAAC;IAAC,OAAO,KAAK,EAAE,CAAC;QACf,OAAO,EAAE,CAAC;QACV,MAAM,KAAK,CAAC;IACd,CAAC;AACH,CAAC","sourcesContent":["/**\n * Author Element Contract\n *\n * Checks for the host-facing half of an author element, as\n * `docs/PIE_ELEMENT_CONTRACT.md` sets it out under \"Authoring Contract\". They\n * throw on a violation, so they run under any test runner.\n */\n\ntype AuthorElement = HTMLElement & { model?: unknown; configuration?: unknown };\n\ntype ModelUpdated = CustomEvent<{ update: unknown; reset: boolean }> & {\n update?: unknown;\n reset?: unknown;\n};\n\nexport interface AuthorModelUpdateOptions {\n /** A tag the author element is registered under. */\n tag: string;\n /** The item's model, with the `id` and `element` a player stamps on it. */\n model: Record<string, unknown>;\n configuration?: Record<string, unknown>;\n /** Makes one edit through the authoring view. */\n edit: (element: HTMLElement) => void | Promise<void>;\n /** Lets the element render once its properties are set; defaults to one macrotask. */\n settle?: () => void | Promise<void>;\n}\n\nexport interface AuthorModelUpdate {\n element: HTMLElement;\n /** The edit's `model.updated`, as a host hears it. */\n event: ModelUpdated;\n /** Removes the element and the ancestor it was mounted under. */\n cleanup: () => void;\n}\n\nconst PLAYER_PROPERTIES = ['model', 'configuration'] as const;\n\nfunction hasSetter(prototype: object | null, name: string): boolean {\n for (let p = prototype; p && p !== HTMLElement.prototype; p = Object.getPrototypeOf(p)) {\n if (Object.getOwnPropertyDescriptor(p, name)?.set) return true;\n }\n return false;\n}\n\n// Models are JSON: compare as such, with key order ignored.\nfunction sameJson(a: unknown, b: unknown): boolean {\n if (a === b) return true;\n if (typeof a !== 'object' || typeof b !== 'object' || a === null || b === null) return false;\n if (Array.isArray(a) !== Array.isArray(b)) return false;\n const aKeys = Object.keys(a).filter((k) => (a as any)[k] !== undefined);\n const bKeys = Object.keys(b).filter((k) => (b as any)[k] !== undefined);\n return (\n aKeys.length === bKeys.length && aKeys.every((k) => sameJson((a as any)[k], (b as any)[k]))\n );\n}\n\nfunction fail(tag: string, problems: string[]): void {\n if (problems.length) {\n throw new Error(`${tag} breaks the authoring contract:\\n- ${problems.join('\\n- ')}`);\n }\n}\n\n/** Throws unless the element declares the properties a player sets: `model`, then `configuration`. */\nexport function assertAuthorElementProperties(tag: string): void {\n const ctor = customElements.get(tag);\n if (!ctor) throw new Error(`${tag} is not registered`);\n fail(\n tag,\n PLAYER_PROPERTIES.filter((name) => !hasSetter(ctor.prototype, name)).map(\n (name) => `declares no \\`${name}\\` property, so a player's \\`element.${name} = …\\` is ignored`\n )\n );\n}\n\n/**\n * Mounts the element under an ancestor, sets `model` and `configuration` as a\n * player does, makes the edit, and throws unless exactly one `model.updated`\n * meets the contract and a readable `model` keeps the edit across a detach and\n * re-attach. Returns that event for element-specific assertions.\n */\nexport async function assertAuthorModelUpdate(\n options: AuthorModelUpdateOptions\n): Promise<AuthorModelUpdate> {\n const {\n tag,\n model,\n configuration,\n edit,\n settle = () => new Promise((r) => setTimeout(r, 0)),\n } = options;\n assertAuthorElementProperties(tag);\n\n const root = document.createElement('div');\n document.body.appendChild(root);\n const element = document.createElement(tag) as AuthorElement;\n const cleanup = () => root.remove();\n const heard: { event: ModelUpdated; modelAtDispatch: unknown }[] = [];\n let captured = 0;\n // The item player listens on an ancestor in the capture phase, legacy\n // pie-author in the bubble phase.\n root.addEventListener('model.updated', () => captured++, true);\n root.addEventListener('model.updated', (e) => {\n heard.push({ event: e as ModelUpdated, modelAtDispatch: element.model });\n });\n\n try {\n root.appendChild(element);\n element.model = structuredClone(model);\n if (configuration) element.configuration = structuredClone(configuration);\n await settle();\n // Elements may announce the model they were given; only the edit's event counts.\n heard.length = 0;\n captured = 0;\n await edit(element);\n\n if (captured > heard.length) {\n fail(tag, ['`model.updated` does not bubble, so legacy pie-author never hears it']);\n }\n if (heard.length !== 1) {\n fail(tag, [`an edit reached an ancestor as ${heard.length} \\`model.updated\\` events, not 1`]);\n }\n const [{ event, modelAtDispatch }] = heard;\n const update = event.detail?.update as Record<string, unknown> | undefined;\n const problems: string[] = [];\n\n if (event.target !== element) {\n problems.push('dispatches `model.updated` from an inner node instead of the element');\n }\n if (event.update !== event.detail?.update || event.reset !== event.detail?.reset) {\n problems.push(\n 'dispatches a plain CustomEvent; legacy pie-author reads `event.update`, which a `ModelUpdatedEvent` carries'\n );\n }\n if (typeof event.detail?.reset !== 'boolean') {\n problems.push('`detail.reset` is not a boolean');\n }\n if (!update || update.id !== model.id || update.element !== model.element) {\n problems.push(\n \"`detail.update` lacks the model's `id` and `element`, which hosts match it by\"\n );\n }\n if (update && event.detail?.reset === false) {\n const dropped = Object.keys(model).filter((k) => model[k] !== undefined && !(k in update));\n if (dropped.length) {\n problems.push(\n `\\`detail.update\\` leaves out ${dropped.map((k) => `\\`${k}\\``).join(', ')}; it is the whole model`\n );\n }\n }\n if (modelAtDispatch !== undefined && !sameJson(modelAtDispatch, update)) {\n problems.push('`element.model` does not hold the edit when `model.updated` fires');\n }\n fail(tag, problems);\n\n if (modelAtDispatch !== undefined) {\n // A host may move the element; the edit has to outlive the remount.\n element.remove();\n await settle();\n root.appendChild(element);\n await settle();\n if (!sameJson(element.model, update)) {\n fail(tag, ['`element.model` loses the edit when the element is detached and re-attached']);\n }\n }\n\n return { element, event, cleanup };\n } catch (error) {\n cleanup();\n throw error;\n }\n}\n"]}
package/dist/index.d.ts CHANGED
@@ -3,6 +3,7 @@
3
3
  *
4
4
  * Testing utilities for PIE element development.
5
5
  */
6
+ export * from './author-contract.js';
6
7
  export * from './controller-test-harness.js';
7
8
  export * from './fixtures.js';
8
9
  export * from './web-component-helpers.js';
package/dist/index.js CHANGED
@@ -3,6 +3,7 @@
3
3
  *
4
4
  * Testing utilities for PIE element development.
5
5
  */
6
+ export * from './author-contract.js';
6
7
  export * from './controller-test-harness.js';
7
8
  export * from './fixtures.js';
8
9
  export * from './web-component-helpers.js';
package/dist/index.js.map CHANGED
@@ -1 +1 @@
1
- {"version":3,"file":"index.js","sourceRoot":"","sources":["../src/index.ts"],"names":[],"mappings":"AAAA;;;;GAIG;AAEH,cAAc,8BAA8B,CAAC;AAC7C,cAAc,eAAe,CAAC;AAC9B,cAAc,4BAA4B,CAAC","sourcesContent":["/**\n * PIE Elements NG - Test Utils\n *\n * Testing utilities for PIE element development.\n */\n\nexport * from './controller-test-harness.js';\nexport * from './fixtures.js';\nexport * from './web-component-helpers.js';\n"]}
1
+ {"version":3,"file":"index.js","sourceRoot":"","sources":["../src/index.ts"],"names":[],"mappings":"AAAA;;;;GAIG;AAEH,cAAc,sBAAsB,CAAC;AACrC,cAAc,8BAA8B,CAAC;AAC7C,cAAc,eAAe,CAAC;AAC9B,cAAc,4BAA4B,CAAC","sourcesContent":["/**\n * PIE Elements NG - Test Utils\n *\n * Testing utilities for PIE element development.\n */\n\nexport * from './author-contract.js';\nexport * from './controller-test-harness.js';\nexport * from './fixtures.js';\nexport * from './web-component-helpers.js';\n"]}
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@pie-element/shared-test-utils",
3
- "version": "0.1.1-next.1",
3
+ "version": "0.1.1-next.20261002100925",
4
4
  "description": "Testing utilities for PIE elements",
5
5
  "type": "module",
6
6
  "main": "./dist/index.js",
@@ -22,12 +22,8 @@
22
22
  "clean": "rm -rf dist"
23
23
  },
24
24
  "dependencies": {
25
- "@pie-element/shared-types": "0.2.0-next.0",
26
- "@pie-element/shared-utils": "0.1.1-next.2"
27
- },
28
- "devDependencies": {
29
- "@types/bun": "latest",
30
- "typescript": "^5.9.3"
25
+ "@pie-element/shared-types": "0.2.0-next.20261002100925",
26
+ "@pie-element/shared-utils": "0.1.1-next.20261002100925"
31
27
  },
32
28
  "publishConfig": {
33
29
  "access": "public"