@xoong/test 0.0.0-stage → 0.0.35

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.
Files changed (4) hide show
  1. package/LICENSE +21 -0
  2. package/README.md +27 -2
  3. package/package.json +40 -4
  4. package/src/index.js +142 -0
package/LICENSE ADDED
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2026 Duong Tran Xuan
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
package/README.md CHANGED
@@ -1,3 +1,28 @@
1
- # Temporary Holding Version
1
+ # @xoong/test
2
2
 
3
- This version is a temporary placeholder for this package. An operational version to replace this has been submitted for review and is awaiting a staged release.
3
+ Test helpers for xoong screens: mount markup with a mocked API generated from `operations.json`, click, submit and push live events. Runs on Vitest.
4
+
5
+ ## Install
6
+
7
+ ```bash
8
+ npm install @xoong/test
9
+ ```
10
+
11
+ ## Use
12
+
13
+ ```js
14
+ import { mount, mockApi } from '@xoong/test';
15
+
16
+ const api = mockApi(operations, { listPeople: () => ({ items: [{ id: 1, name: 'Ada' }] }) });
17
+ const screen = await mount('<xo-view get="listPeople"><li xo-each="items">{name}</li></xo-view>', { api });
18
+ expect(screen.texts('li')).toEqual(['Ada']);
19
+ ```
20
+
21
+ ## More
22
+
23
+ * Documentation and demos: https://github.com/fpt-duongtx/xoong#readme
24
+ * Source: https://github.com/fpt-duongtx/xoong/tree/main/packages/test
25
+ * All packages share one version number and are released together: https://github.com/fpt-duongtx/xoong/releases
26
+ * xoong is a working prototype (0.0.x): the HTML syntax is still Draft.
27
+
28
+ MIT licence.
package/package.json CHANGED
@@ -1,6 +1,42 @@
1
1
  {
2
2
  "name": "@xoong/test",
3
- "version": "0.0.0-stage",
4
- "stub": true,
5
- "description": "Temporary package placeholder for staged publishing"
6
- }
3
+ "version": "0.0.35",
4
+ "description": "Test helpers for xoong UI: mount screens, mock the API from operations.json, push live events. Runs on Vitest (happy-dom or browser mode).",
5
+ "type": "module",
6
+ "exports": {
7
+ ".": "./src/index.js"
8
+ },
9
+ "peerDependencies": {
10
+ "vitest": ">=2"
11
+ },
12
+ "dependencies": {
13
+ "@xoong/core": "0.0.35",
14
+ "@xoong/data": "0.0.35"
15
+ },
16
+ "license": "MIT",
17
+ "files": [
18
+ "src"
19
+ ],
20
+ "keywords": [
21
+ "xoong",
22
+ "web-framework",
23
+ "openapi",
24
+ "custom-elements"
25
+ ],
26
+ "author": "Duong Tran Xuan <duongtx1505@icloud.com>",
27
+ "repository": {
28
+ "type": "git",
29
+ "url": "git+https://github.com/fpt-duongtx/xoong.git",
30
+ "directory": "packages/test"
31
+ },
32
+ "bugs": {
33
+ "url": "https://github.com/fpt-duongtx/xoong/issues"
34
+ },
35
+ "homepage": "https://github.com/fpt-duongtx/xoong#readme",
36
+ "publishConfig": {
37
+ "access": "public"
38
+ },
39
+ "engines": {
40
+ "node": ">=22.12"
41
+ }
42
+ }
package/src/index.js ADDED
@@ -0,0 +1,142 @@
1
+ // @ts-check
2
+ /**
3
+ * Test helpers for xoong screens. Framework-agnostic: they use the real DOM
4
+ * and the real data layer, and replace only the network.
5
+ *
6
+ * import { mount, mockApi } from '@xoong/test'
7
+ * const api = mockApi(operations, { listUsers: () => [{ id: 1, name: 'Ada' }] })
8
+ * const screen = await mount('<xo-view get="/users">...</xo-view>', { api })
9
+ * expect(screen.text('b')).toBe('Ada')
10
+ */
11
+ import { configure } from '@xoong/data';
12
+ import '@xoong/data/view';
13
+
14
+ const tick = (ms = 0) => new Promise((r) => setTimeout(r, ms));
15
+
16
+ /** Build a Response with a JSON body (problem+json for errors). */
17
+ export function respond(status, body) {
18
+ return new Response(body === null || body === undefined ? null : JSON.stringify(body), {
19
+ status,
20
+ headers: { 'content-type': status >= 400 ? 'application/problem+json' : 'application/json' },
21
+ });
22
+ }
23
+
24
+ const toRegex = (path) => new RegExp('^' + path.replace(/[.*+?^$()|[\]\\]/g, '\\$&').replace(/\{[^}]+\}/g, '([^/]+)') + '$');
25
+
26
+ /**
27
+ * A fetch replacement driven by operations.json. Handlers are keyed by
28
+ * operationId (or "METHOD /path") and receive { params, query, body }.
29
+ * Return data (200), or respond(status, body). Unhandled operations answer
30
+ * 404 and are listed in `unhandled` so a test can assert nothing unexpected ran.
31
+ *
32
+ * @param {{ operations: Record<string, any> }} table contents of .xoong/operations.json
33
+ * @param {Record<string, (req: {params: Record<string,string>, query: Record<string,string>, body: any}) => any>} handlers
34
+ */
35
+ export function mockApi(table, handlers = {}) {
36
+ const ops = Object.values(table.operations).map((o) => ({ o, re: toRegex(o.path), names: [...o.path.matchAll(/\{([^}]+)\}/g)].map((m) => m[1]) }));
37
+ /** @type {{ operation: string, params: any, query: any, body: any }[]} */
38
+ const calls = [];
39
+ /** @type {string[]} */
40
+ const unhandled = [];
41
+ const overrides = { ...handlers };
42
+ async function fetch(url, init = {}) {
43
+ const u = new URL(String(url), 'http://mock');
44
+ const method = (init.method ?? 'GET').toUpperCase();
45
+ const hit = ops.find(({ o, re }) => o.method === method && re.test(u.pathname));
46
+ if (!hit) { unhandled.push(`${method} ${u.pathname}`); return respond(404, { title: 'Not Found', detail: `mockApi: no operation for ${method} ${u.pathname}` }); }
47
+ const m = hit.re.exec(u.pathname);
48
+ const params = Object.fromEntries(hit.names.map((n, i) => [n, decodeURIComponent(m[i + 1])]));
49
+ const query = Object.fromEntries(u.searchParams);
50
+ const body = init.body ? JSON.parse(init.body) : undefined;
51
+ calls.push({ operation: hit.o.id, params, query, body });
52
+ const handler = overrides[hit.o.id] ?? overrides[`${method} ${hit.o.path}`];
53
+ if (!handler) { unhandled.push(hit.o.id); return respond(404, { title: 'Not Found', detail: `mockApi: no handler for ${hit.o.id}` }); }
54
+ const out = await handler({ params, query, body });
55
+ return out instanceof Response ? out : respond(200, out);
56
+ }
57
+ return {
58
+ fetch, calls, unhandled, table,
59
+ /** Replace or add a handler mid-test. */
60
+ on(id, handler) { overrides[id] = handler; },
61
+ /** Calls of one operation. */
62
+ callsOf: (id) => calls.filter((c) => c.operation === id),
63
+ };
64
+ }
65
+
66
+ /** A controllable EventSource so tests can push live events. */
67
+ function createStreamHub() {
68
+ /** @type {Set<any>} */ const sources = new Set();
69
+ class FakeEventSource {
70
+ constructor(url) { this.url = url; sources.add(this); queueMicrotask(() => this.onopen?.()); }
71
+ close() { sources.delete(this); }
72
+ }
73
+ return {
74
+ EventSource: FakeEventSource,
75
+ push: (ev) => sources.forEach((s) => s.onmessage?.({ data: JSON.stringify(ev) })),
76
+ get connections() { return sources.size; },
77
+ };
78
+ }
79
+
80
+ /**
81
+ * Render HTML containing xoong elements against a mocked API.
82
+ * @param {string} html
83
+ * @param {{ api: ReturnType<typeof mockApi>, streamUrl?: string, headers?: any }} options
84
+ */
85
+ export async function mount(html, { api, streamUrl = '/events', headers } = {}) {
86
+ if (!api) throw new Error('xoong test: mount() needs { api: mockApi(...) }');
87
+ const hub = createStreamHub();
88
+ const previous = globalThis.EventSource;
89
+ globalThis.EventSource = /** @type {any} */ (hub.EventSource);
90
+ const client = configure({ api: api.table, fetch: /** @type {any} */ (api.fetch), streamUrl, headers, retry: 0, gcTime: Infinity });
91
+ const container = document.createElement('div');
92
+ document.body.append(container);
93
+ container.innerHTML = html;
94
+
95
+ /** Wait until requests and reactive updates have settled. */
96
+ async function settle() {
97
+ for (let i = 0; i < 50; i++) {
98
+ await tick(0);
99
+ if (client.pending === 0) { await tick(0); if (client.pending === 0) return; }
100
+ }
101
+ throw new Error('xoong test: requests did not settle (a handler may never resolve)');
102
+ }
103
+ await settle();
104
+
105
+ /** @type {any[]} */ const errors = [];
106
+ container.addEventListener('xo-error', (e) => errors.push(/** @type {CustomEvent} */ (e).detail));
107
+
108
+ const $ = (sel) => container.querySelector(sel);
109
+ const $$ = (sel) => [...container.querySelectorAll(sel)];
110
+ const screen = {
111
+ container, client, settle, $, $$,
112
+ /** Errors emitted by xo-click/xo-submit (API failures and screen mistakes). */
113
+ errors,
114
+ /** Text content of the first match (whitespace-collapsed). */
115
+ text: (sel) => ($(sel)?.textContent ?? '').replace(/\s+/g, ' ').trim(),
116
+ /** Texts of all matches. */
117
+ texts: (sel) => $$(sel).map((e) => (e.textContent ?? '').replace(/\s+/g, ' ').trim()),
118
+ /** Click an element (selector or element) and wait for the app to settle. */
119
+ async click(target) {
120
+ const el = typeof target === 'string' ? $(target) : target;
121
+ if (!el) throw new Error(`xoong test: nothing matches "${target}"`);
122
+ el.click();
123
+ await settle();
124
+ },
125
+ /** Submit a form after filling fields: submit('form', { name: 'Ada' }). */
126
+ async submit(target, fields = {}) {
127
+ const form = /** @type {HTMLFormElement} */ (typeof target === 'string' ? $(target) : target);
128
+ for (const [k, v] of Object.entries(fields)) {
129
+ const input = /** @type {HTMLInputElement} */ (form.elements.namedItem(k));
130
+ if (!input) throw new Error(`xoong test: form has no field "${k}"`);
131
+ input.value = v;
132
+ }
133
+ form.dispatchEvent(new Event('submit', { bubbles: true, cancelable: true }));
134
+ await settle();
135
+ },
136
+ /** Deliver a live event (as if the server pushed it) and settle. */
137
+ async push(event) { hub.push(event); await settle(); },
138
+ stream: hub,
139
+ unmount() { container.remove(); globalThis.EventSource = previous; },
140
+ };
141
+ return screen;
142
+ }