@blotch/angular-lynx-testing-library 22.2.8 → 22.2.10

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
@@ -63,23 +63,37 @@ import { render } from '@blotch/angular-lynx-testing-library';
63
63
  const { container, getByText, queryByRole } = await render(MyComponent);
64
64
  ```
65
65
 
66
- `render` is **async** — it `await`s Angular's `bootstrapApplication`. The initial change detection cycle runs before the promise resolves, so the container is ready to query immediately.
66
+ `render` is **async** — it `await`s Angular's `createApplication`, then bootstraps the component. The initial change detection cycle runs before the promise resolves, so the container is ready to query immediately.
67
67
 
68
68
  **Options:**
69
69
 
70
- | Option | Type | Description |
71
- | ----------- | -------------------------------------- | --------------------------------------------------------------------- |
72
- | `providers` | `(Provider \| EnvironmentProviders)[]` | Additional providers injected into the app (services, tokens, mocks). |
70
+ | Option | Type | Description |
71
+ | ----------- | -------------------------------------- | ---------------------------------------------------------------------------------------------------------------------------------------- |
72
+ | `providers` | `(Provider \| EnvironmentProviders)[]` | Additional providers injected into the app (services, tokens, mocks). |
73
+ | `queries` | `Queries` | Custom queries to bind to `container`, next to the library's. |
74
+ | `inputs` | `RenderInputs<C>` | Values for the component's inputs, keyed by the name a template binds (an aliased input's alias). Set before the first change detection. |
75
+
76
+ ```ts
77
+ const { getByText, rerender } = await render(Greeting, {
78
+ inputs: { name: 'Lynx' },
79
+ });
80
+
81
+ // Keeps the component and changes only the inputs passed.
82
+ await rerender({ inputs: { name: 'Angular' } });
83
+ ```
84
+
85
+ `rerender({ inputs })` can change only inputs `render()` set: Angular sets them through `inputBinding()`, and a component with input bindings refuses other inputs (and `componentRef.setInput()`). Give `render()` the starting value of any input a test changes later.
73
86
 
74
87
  `provideZonelessChangeDetection()` and `provideRenderer()` are always included — you do not need to provide them.
75
88
 
76
89
  **Return value:**
77
90
 
78
- | Property | Type | Description |
79
- | ------------ | ------------ | ---------------------------------------------------------------------------------------------------------------------- |
80
- | `container` | `Element` | The JSDOM `<page>` root element. All rendered children are descendants. |
81
- | `unmount` | `() => void` | Destroys the Angular app. |
82
- | `...queries` | — | Every query in [`queries`](#queries) bound to `container` (`getByText`, `getByRole`, `getByAccessibilityLabel`, etc.). |
91
+ | Property | Type | Description |
92
+ | ------------ | ------------------------------------------------------------------------------------------- | ---------------------------------------------------------------------------------------------------------------------- |
93
+ | `container` | `Element` | The JSDOM `<page>` root element. All rendered children are descendants. |
94
+ | `unmount` | `() => void` | Destroys the Angular app. |
95
+ | `rerender` | `({ inputs }) => Promise<RenderResult>` or `(component, options?) => Promise<RenderResult>` | Changes inputs `render()` set, keeping the component; or renders another component in its place. |
96
+ | `...queries` | — | Every query in [`queries`](#queries) bound to `container` (`getByText`, `getByRole`, `getByAccessibilityLabel`, etc.). |
83
97
 
84
98
  ### `cleanup()`
85
99
 
@@ -131,15 +145,23 @@ A named helper runs the handlers a device would, in the same order:
131
145
 
132
146
  `init.eventType` fires at one kind of handler on the element and nothing else: `fireEvent.tap(element, { eventType: 'catchEvent' })` dispatches the DOM event `"catchEvent:tap"`, which reaches only the element's `(catchtap)`.
133
147
 
148
+ `init.detail` is the event's own data, as a device sends it: an `<image>`'s size once it loads, say.
149
+
150
+ ```ts
151
+ fireEvent.load(image, { detail: { width: 240, height: 340 } });
152
+ ```
153
+
134
154
  To dispatch a raw DOM event directly:
135
155
 
136
156
  ```ts
137
157
  fireEvent(element, new Event('bindEvent:tap'));
138
158
  ```
139
159
 
160
+ A `CustomEvent`'s `detail` reaches the handler too: `fireEvent(element, new CustomEvent('bindEvent:load', { detail }))`.
161
+
140
162
  **Available named helpers:**
141
163
 
142
- `tap` · `longtap` · `touchstart` · `touchmove` · `touchcancel` · `touchend` · `longpress` · `scroll` · `scrollend` · `focus` · `blur` · `input` · `confirm` · `layoutchange` · `transitionend` · `animationend`
164
+ `tap` · `longtap` · `touchstart` · `touchmove` · `touchcancel` · `touchend` · `longpress` · `keydown` · `keyup` · `mousedown` · `mouseup` · `mousemove` · `mouseclick` · `mousedblclick` · `mouselongpress` · `wheel` · `scroll` · `scrollend` · `scrolltoupper` · `scrolltolower` · `contentsizechanged` · `scrolltoupperedge` · `scrolltoloweredge` · `scrolltonormalstate` · `uiappear` · `uidisappear` · `focus` · `blur` · `input` · `confirm` · `layoutchange` · `load` · `error` · `bgload` · `bgerror` · `transitionstart` · `transitionend` · `transitioncancel` · `animationend`
143
165
 
144
166
  ### `eventMap`
145
167
 
@@ -430,6 +452,6 @@ Template binding → PAPI registration → DOM listener key:
430
452
  | `renderHook()` | ✓ | — | — |
431
453
  | Snapshot serializer | ✓ (RefProxy) | — | — |
432
454
  | Vitest plugin | ✓ | — | — (`ng test` sets up) |
433
- | Named fireEvent helpers | 30+ | 16 | 16 |
455
+ | Named fireEvent helpers | 30+ | 16 | 37 |
434
456
  | Thread-aware fireEvent | ✓ | ✓ | — (single thread) |
435
457
  | Async state helper | `waitSchedule()` | `waitForUpdate()` | `waitForUpdate()` |
@@ -130,6 +130,12 @@ export declare const eventMap: {
130
130
  scrolltonormalstate: {
131
131
  defaultInit: {};
132
132
  };
133
+ uiappear: {
134
+ defaultInit: {};
135
+ };
136
+ uidisappear: {
137
+ defaultInit: {};
138
+ };
133
139
  focus: {
134
140
  defaultInit: {};
135
141
  };
@@ -145,6 +151,12 @@ export declare const eventMap: {
145
151
  layoutchange: {
146
152
  defaultInit: {};
147
153
  };
154
+ load: {
155
+ defaultInit: {};
156
+ };
157
+ error: {
158
+ defaultInit: {};
159
+ };
148
160
  bgload: {
149
161
  defaultInit: {};
150
162
  };
@@ -1 +1 @@
1
- {"version":3,"file":"fire-event.d.ts","sourceRoot":"","sources":["../src/fire-event.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;GAaG;AAUH;;;;;;;;;;;;GAYG;AACH,eAAO,MAAM,QAAQ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;CA2CpB,CAAC;AAEF,KAAK,SAAS,GAAG,MAAM,OAAO,QAAQ,CAAC;AACvC,KAAK,YAAY,GAAG,CAAC,IAAI,EAAE,OAAO,EAAE,IAAI,CAAC,EAAE,MAAM,CAAC,MAAM,EAAE,OAAO,CAAC,KAAK,OAAO,CAAC;AAC/E,KAAK,SAAS,GAAG,CAAC,CAAC,IAAI,EAAE,OAAO,EAAE,KAAK,EAAE,KAAK,KAAK,OAAO,CAAC,GAAG;KAC3D,CAAC,IAAI,SAAS,GAAG,YAAY;CAC/B,CAAC;AA8GF,eAAO,MAAM,SAAS,EAAE,SAET,CAAC"}
1
+ {"version":3,"file":"fire-event.d.ts","sourceRoot":"","sources":["../src/fire-event.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;GAaG;AAoBH;;;;;;;;;;;;GAYG;AACH,eAAO,MAAM,QAAQ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;CAqDpB,CAAC;AAEF,KAAK,SAAS,GAAG,MAAM,OAAO,QAAQ,CAAC;AACvC,KAAK,YAAY,GAAG,CAAC,IAAI,EAAE,OAAO,EAAE,IAAI,CAAC,EAAE,MAAM,CAAC,MAAM,EAAE,OAAO,CAAC,KAAK,OAAO,CAAC;AAC/E,KAAK,SAAS,GAAG,CAAC,CAAC,IAAI,EAAE,OAAO,EAAE,KAAK,EAAE,KAAK,KAAK,OAAO,CAAC,GAAG;KAC3D,CAAC,IAAI,SAAS,GAAG,YAAY;CAC/B,CAAC;AA+JF,eAAO,MAAM,SAAS,EAAE,SAET,CAAC"}
@@ -13,7 +13,17 @@
13
13
  * Lynx sends the event (see deliver()).
14
14
  */
15
15
  import { createEvent, fireEvent as domFireEvent, getConfig, } from '@testing-library/dom';
16
- const EVENT_INIT_KEYS = new Set(['bubbles', 'cancelable', 'composed']);
16
+ /**
17
+ * Init keys that aren't copied onto the event: the standard EventInit ones,
18
+ * which are read-only on a constructed event, and `target`, which Testing
19
+ * Library's createEvent sets on the element (`{ target: { value } }`).
20
+ */
21
+ const EVENT_INIT_KEYS = new Set([
22
+ 'bubbles',
23
+ 'cancelable',
24
+ 'composed',
25
+ 'target',
26
+ ]);
17
27
  /**
18
28
  * The events the named helpers fire. Those with `bubbles: true` travel Lynx's
19
29
  * event response chain, from the element up to the page, so a tap on a row
@@ -56,13 +66,23 @@ export const eventMap = {
56
66
  scrolltoupperedge: { defaultInit: {} },
57
67
  scrolltoloweredge: { defaultInit: {} },
58
68
  scrolltonormalstate: { defaultInit: {} },
69
+ // Exposure: an element coming into view, inside its scroll containers and
70
+ // the screen, and leaving it. What `[lynxExposure]` and the runtime's
71
+ // IntersectionObserver listen for.
72
+ uiappear: { defaultInit: {} },
73
+ uidisappear: { defaultInit: {} },
59
74
  // Form / focus
60
75
  focus: { defaultInit: {} },
61
76
  blur: { defaultInit: {} },
62
77
  input: { defaultInit: {} },
63
78
  confirm: { defaultInit: {} },
64
- // Layout / image
79
+ // Layout / loading. `load` is an <image>, <svg>, <frame> or <webview>
80
+ // reporting its content arrived, and `error` an <image>, <video>,
81
+ // <webview> or <overlay> reporting it didn't. A device sends both to the
82
+ // element alone, with what happened in `detail` (an image's size, say).
65
83
  layoutchange: { defaultInit: {} },
84
+ load: { defaultInit: {} },
85
+ error: { defaultInit: {} },
66
86
  bgload: { defaultInit: {} },
67
87
  bgerror: { defaultInit: {} },
68
88
  // Transition / animation
@@ -97,11 +117,34 @@ const createLynxEvent = (elem, type, name, init) => {
97
117
  const eventInit = { eventType: type, eventName: name, ...init };
98
118
  const event = createEvent(`${type}:${name}`, elem, eventInit);
99
119
  Object.assign(event, Object.fromEntries(Object.entries(eventInit).filter(([k]) => !EVENT_INIT_KEYS.has(k))));
120
+ // The element the event happened on, by its unique id, as a device names
121
+ // it: the runtime finds a touch's element by it, for the target of the
122
+ // pointer events `document:` listeners get. A DOM event's own `target` is
123
+ // a getter, which the testing environment doesn't copy to the handler, so
124
+ // it's shadowed.
125
+ Object.defineProperty(event, 'target', {
126
+ value: { uid: globalThis.__GetElementUniqueID(elem) },
127
+ enumerable: true,
128
+ configurable: true,
129
+ });
100
130
  return event;
101
131
  };
132
+ /**
133
+ * Every element in `target`'s tree with a `global-bind` handler for `name`:
134
+ * Lynx runs one for an event on any element of the page.
135
+ */
136
+ const globalHandlersOf = (target, name) => {
137
+ let root = target;
138
+ while (root.parentElement)
139
+ root = root.parentElement;
140
+ return [root, ...root.querySelectorAll('*')].filter((element) => handlerOf(element, 'global-bindEvent', name));
141
+ };
102
142
  /**
103
143
  * Runs the handlers for the event `name` fired at `target`, as Lynx's
104
- * TouchEventHandler::HandleEventInternal does on a device. An event that
144
+ * TouchEventHandler::HandleEventInternal does on a device. First every
145
+ * `global-bind` handler for it, on any element: they're what the runtime's
146
+ * `document` and `window` hear the screen's events with, so a `document:` or
147
+ * `window:` listener runs. An event that
105
148
  * bubbles goes down from the page to the target, running `capture-bind` and
106
149
  * `capture-catch` handlers, then back up, running `bind` and `catch` ones. A
107
150
  * `catch` handler of either phase runs and stops the event there. Any other
@@ -148,14 +191,37 @@ const deliver = (target, name, init) => {
148
191
  }
149
192
  return false;
150
193
  };
194
+ for (const element of globalHandlersOf(target, name)) {
195
+ const event = createLynxEvent(target, 'global-bindEvent', name, init);
196
+ handlerOf(element, 'global-bindEvent', name)(event);
197
+ notCanceled &&= !event.defaultPrevented;
198
+ }
151
199
  // Lynx has no capture phase for the events that stay on their target.
152
200
  const captured = !!init['bubbles'] && runPhase([...chain].reverse(), CAPTURE_PHASE);
153
201
  if (!captured)
154
202
  runPhase(chain, BUBBLE_PHASE);
155
203
  return notCanceled;
156
204
  };
205
+ /**
206
+ * Makes the `detail` an event inherits, as a CustomEvent's is a getter on its
207
+ * prototype, a property of the event itself. The testing environment hands a
208
+ * handler `Object.assign({}, event)`, which copies only own properties, so a
209
+ * `new CustomEvent('bindEvent:load', { detail })` would otherwise run the
210
+ * handler with no `detail` at all. A named helper's init is already copied
211
+ * onto its event (see createLynxEvent).
212
+ */
213
+ const keepDetail = (event) => {
214
+ if ('detail' in event && !Object.hasOwn(event, 'detail')) {
215
+ Object.defineProperty(event, 'detail', {
216
+ value: event.detail,
217
+ enumerable: true,
218
+ configurable: true,
219
+ });
220
+ }
221
+ return event;
222
+ };
157
223
  export const fireEvent = ((elem, event) => {
158
- return domFireEvent(elem, event);
224
+ return domFireEvent(elem, keepDetail(event));
159
225
  });
160
226
  for (const key of Object.keys(eventMap)) {
161
227
  fireEvent[key] = (elem, init) => {
package/dist/index.d.ts CHANGED
@@ -1,5 +1,5 @@
1
1
  export { render, cleanup, waitForUpdate } from './render.js';
2
- export type { RenderOptions, RenderResult } from './render.js';
2
+ export type { RenderInputs, RenderOptions, RenderResult } from './render.js';
3
3
  export type { ComponentRef } from '@angular/core';
4
4
  export { fireEvent, eventMap } from './fire-event.js';
5
5
  export { screen, within, getQueriesForElement, queries } from './queries.js';
@@ -1 +1 @@
1
- {"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../src/index.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,MAAM,EAAE,OAAO,EAAE,aAAa,EAAE,MAAM,aAAa,CAAC;AAC7D,YAAY,EAAE,aAAa,EAAE,YAAY,EAAE,MAAM,aAAa,CAAC;AAC/D,YAAY,EAAE,YAAY,EAAE,MAAM,eAAe,CAAC;AAClD,OAAO,EAAE,SAAS,EAAE,QAAQ,EAAE,MAAM,iBAAiB,CAAC;AACtD,OAAO,EAAE,MAAM,EAAE,MAAM,EAAE,oBAAoB,EAAE,OAAO,EAAE,MAAM,cAAc,CAAC;AAC7E,YAAY,EACV,8BAA8B,EAC9B,gBAAgB,EAChB,WAAW,EACX,UAAU,GACX,MAAM,cAAc,CAAC;AACtB,OAAO,EACL,4BAA4B,EAC5B,yBAAyB,EACzB,0BAA0B,EAC1B,uBAAuB,EACvB,2BAA2B,EAC3B,wBAAwB,GACzB,MAAM,kCAAkC,CAAC;AAC1C,OAAO,EACL,cAAc,EACd,WAAW,EACX,YAAY,EACZ,SAAS,EACT,aAAa,EACb,UAAU,GACX,MAAM,mBAAmB,CAAC"}
1
+ {"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../src/index.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,MAAM,EAAE,OAAO,EAAE,aAAa,EAAE,MAAM,aAAa,CAAC;AAC7D,YAAY,EAAE,YAAY,EAAE,aAAa,EAAE,YAAY,EAAE,MAAM,aAAa,CAAC;AAC7E,YAAY,EAAE,YAAY,EAAE,MAAM,eAAe,CAAC;AAClD,OAAO,EAAE,SAAS,EAAE,QAAQ,EAAE,MAAM,iBAAiB,CAAC;AACtD,OAAO,EAAE,MAAM,EAAE,MAAM,EAAE,oBAAoB,EAAE,OAAO,EAAE,MAAM,cAAc,CAAC;AAC7E,YAAY,EACV,8BAA8B,EAC9B,gBAAgB,EAChB,WAAW,EACX,UAAU,GACX,MAAM,cAAc,CAAC;AACtB,OAAO,EACL,4BAA4B,EAC5B,yBAAyB,EACzB,0BAA0B,EAC1B,uBAAuB,EACvB,2BAA2B,EAC3B,wBAAwB,GACzB,MAAM,kCAAkC,CAAC;AAC1C,OAAO,EACL,cAAc,EACd,WAAW,EACX,YAAY,EACZ,SAAS,EACT,aAAa,EACb,UAAU,GACX,MAAM,mBAAmB,CAAC"}
package/dist/render.d.ts CHANGED
@@ -5,7 +5,8 @@
5
5
  *
6
6
  * Pipeline:
7
7
  * 1. switchToMainThread() → PAPI globals (__CreatePage, __CreateView, …) active
8
- * 2. bootstrapApplication(component, { provideRenderer(), … })
8
+ * 2. createApplication({ provideRenderer(), … }), then
9
+ * appRef.bootstrap(component, { bindings }) with options.inputs as bindings
9
10
  * → LynxDocument.createRootElement() → __CreatePage → JSDOM <page> in body
10
11
  * → Angular renders tree → __CreateView/Text/… → JSDOM children
11
12
  * → LynxRendererFactory2.end() → __FlushElementTree() (no-op in tests)
@@ -13,10 +14,29 @@
13
14
  * 4. Return JSDOM container + queries (@testing-library/dom's, with the
14
15
  * Lynx-aware *ByRole and *ByAccessibilityLabel; see queries.ts)
15
16
  */
16
- import { type ComponentRef, type EnvironmentProviders, type Provider, type Type } from '@angular/core';
17
+ import { type ComponentRef, type EnvironmentProviders, type InputSignalWithTransform, type Provider, type Type } from '@angular/core';
17
18
  import { type BoundFunctions, type Queries } from '@testing-library/dom';
18
19
  import { type BoundLynxQueries, type LynxQueries } from './queries.js';
19
- export type RenderOptions<Q extends Queries = LynxQueries> = {
20
+ /**
21
+ * The value an input takes from a test: what a signal input or model accepts
22
+ * (its transform's input type, if it has one), or the property's own type for
23
+ * an `@Input()` or an input listed in `inputs` metadata.
24
+ */
25
+ type InputValue<T> = T extends InputSignalWithTransform<any, infer Write> ? Write : T;
26
+ /**
27
+ * Inputs for `render()` and `rerender()`, keyed by the name a template binds.
28
+ *
29
+ * Each of the component's properties is typed with the value its input takes,
30
+ * so `inputs: { count: 'three' }` fails to compile for `count = input(0)`. Any
31
+ * other name is allowed too, because an aliased input's name (such as `class`
32
+ * for `input('', { alias: 'class' })`) isn't one of the component's
33
+ * properties. `render()` checks each name against the component's inputs, so a
34
+ * misspelled one still fails the test, at run time.
35
+ */
36
+ export type RenderInputs<C = unknown> = {
37
+ [K in keyof C]?: InputValue<C[K]>;
38
+ } & Record<string, unknown>;
39
+ export type RenderOptions<Q extends Queries = LynxQueries, C = unknown> = {
20
40
  providers?: (Provider | EnvironmentProviders)[];
21
41
  /**
22
42
  * Custom query helpers to merge with the library's queries (see queries.ts).
@@ -24,8 +44,21 @@ export type RenderOptions<Q extends Queries = LynxQueries> = {
24
44
  * Workaround if omitted: call `getQueriesForElement(container, customQueries)` directly.
25
45
  */
26
46
  queries?: Q;
47
+ /**
48
+ * Values for the component's inputs, as a parent template would bind them.
49
+ *
50
+ * They're set before the first change detection, so a required input has
51
+ * its value when the template first reads it, and `ngOnInit` sees them all.
52
+ * Change them afterwards with `rerender({ inputs })`.
53
+ *
54
+ * render() passes them to Angular as `inputBinding()`s, which needs the
55
+ * input metadata ahead-of-time compilation registers. `ng test` compiles
56
+ * tests that way. Under plain Vitest, which compiles just in time, Angular
57
+ * sees `@Input()` and `inputs` metadata, but not `input()` or `model()`.
58
+ */
59
+ inputs?: RenderInputs<C>;
27
60
  };
28
- export type RenderResult<Q extends Queries = LynxQueries> = {
61
+ export type RenderResult<Q extends Queries = LynxQueries, C = unknown> = {
29
62
  /**
30
63
  * The JSDOM root element (page element) containing all rendered children.
31
64
  */
@@ -34,11 +67,24 @@ export type RenderResult<Q extends Queries = LynxQueries> = {
34
67
  * Unmount the current Angular app.
35
68
  */
36
69
  unmount: () => void;
70
+ /**
71
+ * Change inputs that `render()` set, keeping the component and its state,
72
+ * then run change detection. Inputs left out keep their values: Angular has
73
+ * no way to put an input back to its initial value.
74
+ *
75
+ * Only inputs `render()` set can change. Angular sets those through
76
+ * `inputBinding()`, and a component with input bindings refuses
77
+ * `setInput()`, so there's no way to set another input later. Give
78
+ * `render()` the input's starting value to change it here.
79
+ */
80
+ rerender(update: {
81
+ inputs: RenderInputs<C>;
82
+ }): Promise<RenderResult<Q, C>>;
37
83
  /**
38
84
  * Re-render a (possibly different) component into the same body position,
39
85
  * replacing the running app without manually calling cleanup() first.
40
86
  */
41
- rerender: <R extends Queries = Q>(component: Type<unknown>, options?: RenderOptions<R>) => Promise<RenderResult<R>>;
87
+ rerender<R extends Queries = Q, D = unknown>(component: Type<D>, options?: RenderOptions<R, NoInfer<D>>): Promise<RenderResult<R, D>>;
42
88
  /**
43
89
  * Returns a DocumentFragment snapshot of the container — use for snapshot testing.
44
90
  */
@@ -55,14 +101,24 @@ export type RenderResult<Q extends Queries = LynxQueries> = {
55
101
  * `ng test` compiles tests that way, so it works there. Under plain Vitest,
56
102
  * which compiles components just in time, that metadata isn't available;
57
103
  * expose writable signals on the component instance instead.
104
+ *
105
+ * After `render()` with `inputs`, change inputs with `rerender({ inputs })`:
106
+ * Angular refuses `setInput()` on a component whose inputs are bound
107
+ * (NG0317).
58
108
  */
59
- componentRef: ComponentRef<unknown>;
109
+ componentRef: ComponentRef<C>;
60
110
  } & BoundLynxQueries & BoundFunctions<Q>;
61
111
  export declare const cleanup: () => void;
62
- export declare const render: <Q extends Queries = LynxQueries>(rootComponent: Type<unknown>, options?: RenderOptions<Q>) => Promise<RenderResult<Q>>;
112
+ /**
113
+ * Renders `rootComponent` as a Lynx app's root component, with
114
+ * `options.inputs` bound to its inputs, and resolves once the first change
115
+ * detection has run.
116
+ */
117
+ export declare const render: <Q extends Queries = LynxQueries, C = unknown>(rootComponent: Type<C>, options?: RenderOptions<Q, NoInfer<C>>) => Promise<RenderResult<Q, C>>;
63
118
  /**
64
119
  * Wait for all pending Angular reactive updates to flush through the pipeline.
65
120
  * Call this after programmatic signal changes that happen outside event handlers.
66
121
  */
67
122
  export declare const waitForUpdate: () => Promise<void>;
123
+ export {};
68
124
  //# sourceMappingURL=render.d.ts.map
@@ -1 +1 @@
1
- {"version":3,"file":"render.d.ts","sourceRoot":"","sources":["../src/render.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;;GAcG;AAEH,OAAO,EAEL,KAAK,YAAY,EACjB,KAAK,oBAAoB,EACzB,KAAK,QAAQ,EAEb,KAAK,IAAI,EACV,MAAM,eAAe,CAAC;AAEvB,OAAO,EACL,KAAK,cAAc,EACnB,KAAK,OAAO,EAEb,MAAM,sBAAsB,CAAC;AAE9B,OAAO,EAAE,KAAK,gBAAgB,EAAE,KAAK,WAAW,EAAW,MAAM,cAAc,CAAC;AAEhF,MAAM,MAAM,aAAa,CAAC,CAAC,SAAS,OAAO,GAAG,WAAW,IAAI;IAC3D,SAAS,CAAC,EAAE,CAAC,QAAQ,GAAG,oBAAoB,CAAC,EAAE,CAAC;IAChD;;;;OAIG;IACH,OAAO,CAAC,E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,CAAC,CAAC,CAAC,CAAC,GACrC,OAAO,CAAC,YAAY,CAAC,CAAC,EAAE,CAAC,CAAC,CAAC,CAAC;IAC/B;;OAEG;IACH,UAAU,EAAE,MAAM,gBAAgB,CAAC;IACnC;;;;;;;;;;;;;;;;OAgBG;IACH,YAAY,EAAE,YAAY,CAAC,CAAC,CAAC,CAAC;CAC/B,GAAG,gBAAgB,GAClB,cAAc,CAAC,CAAC,CAAC,CAAC;AAIpB,eAAO,MAAM,OAAO,QAAO,IAM1B,CAAC;AAmFF;;;;GAIG;AACH,eAAO,MAAM,MAAM,GAAU,CAAC,SAAS,OAAO,GAAG,WAAW,EAAE,CAAC,GAAG,OAAO,EACvE,eAAe,IAAI,CAAC,CAAC,CAAC,EACtB,UAAS,aAAa,CAAC,CAAC,EAAE,OAAO,CAAC,CAAC,CAAC,CAAM,KACzC,OAAO,CAAC,YAAY,CAAC,CAAC,EAAE,CAAC,CAAC,CA+G5B,CAAC;AAEF;;;GAGG;AACH,eAAO,MAAM,aAAa,QAAa,OAAO,CAAC,IAAI,CAKlD,CAAC"}
package/dist/render.js CHANGED
@@ -5,7 +5,8 @@
5
5
  *
6
6
  * Pipeline:
7
7
  * 1. switchToMainThread() → PAPI globals (__CreatePage, __CreateView, …) active
8
- * 2. bootstrapApplication(component, { provideRenderer(), … })
8
+ * 2. createApplication({ provideRenderer(), … }), then
9
+ * appRef.bootstrap(component, { bindings }) with options.inputs as bindings
9
10
  * → LynxDocument.createRootElement() → __CreatePage → JSDOM <page> in body
10
11
  * → Angular renders tree → __CreateView/Text/… → JSDOM children
11
12
  * → LynxRendererFactory2.end() → __FlushElementTree() (no-op in tests)
@@ -13,8 +14,8 @@
13
14
  * 4. Return JSDOM container + queries (@testing-library/dom's, with the
14
15
  * Lynx-aware *ByRole and *ByAccessibilityLabel; see queries.ts)
15
16
  */
16
- import { provideZonelessChangeDetection, } from '@angular/core';
17
- import { bootstrapApplication } from '@angular/platform-browser';
17
+ import { inputBinding, provideZonelessChangeDetection, reflectComponentType, signal, } from '@angular/core';
18
+ import { createApplication } from '@angular/platform-browser';
18
19
  import { getQueriesForElement, } from '@testing-library/dom';
19
20
  import { provideRenderer } from '@blotch/angular-lynx';
20
21
  import { queries } from './queries.js';
@@ -26,8 +27,80 @@ export const cleanup = () => {
26
27
  ref.destroy();
27
28
  }
28
29
  };
30
+ /**
31
+ * The microtask turns that passed between bootstrap and an
32
+ * `await bootstrapApplication()` resuming, as measured on Angular 22.2: the
33
+ * promise chain its bootstrap returns through.
34
+ */
35
+ const BOOTSTRAP_MICROTASK_TURNS = 6;
36
+ /**
37
+ * Lets the microtasks the first change detection queued run, as many turns as
38
+ * awaiting bootstrapApplication() did, so render() keeps its timing.
39
+ *
40
+ * Only microtasks: waiting for a timer would hang a test that turned on fake
41
+ * timers, and would run the component's own timers before render() returns.
42
+ */
43
+ const settleBootstrapMicrotasks = async () => {
44
+ for (let turn = 0; turn < BOOTSTRAP_MICROTASK_TURNS; turn++) {
45
+ await Promise.resolve();
46
+ }
47
+ };
48
+ /**
49
+ * Returns the component's mirror, after the check bootstrapApplication() makes:
50
+ * that it's a standalone component. appRef.bootstrap() doesn't check, and given
51
+ * a plain class it fails reading the missing definition, with a TypeError that
52
+ * doesn't say what's wrong.
53
+ */
54
+ const reflectRootComponent = (component) => {
55
+ const mirror = reflectComponentType(component);
56
+ if (!mirror) {
57
+ throw new Error(`render() can't render ${component.name}: it isn't an Angular component. Give it the @Component decorator.`);
58
+ }
59
+ if (!mirror.isStandalone) {
60
+ throw new Error(`render() can't render ${component.name}: it isn't standalone, and render() bootstraps it as an app's root component. Remove standalone: false.`);
61
+ }
62
+ return mirror;
63
+ };
64
+ /**
65
+ * Throws unless each name is one of the component's inputs, as a template
66
+ * binds it.
67
+ *
68
+ * Angular reports a binding to a missing input during the first change
69
+ * detection, which bootstrap runs inside a try/catch that hands the error to
70
+ * the ErrorHandler and carries on. The test would go on with the input unset,
71
+ * and LynxErrorHandler reports through lynx.reportError, which prints nothing
72
+ * in a test, so render() checks first and names the inputs the component has.
73
+ */
74
+ const assertInputsExist = (mirror, names, caller) => {
75
+ const templateNames = new Set(mirror.inputs.map((input) => input.templateName));
76
+ const missing = names.find((name) => !templateNames.has(name));
77
+ if (missing === undefined)
78
+ return;
79
+ const component = mirror.type.name;
80
+ // An aliased input's property name is the natural thing to type, since
81
+ // that's what the component's code reads; say which name to use instead.
82
+ const aliased = mirror.inputs.find((input) => input.propName === missing);
83
+ if (aliased) {
84
+ throw new Error(`${caller} can't set "${missing}": it's the property of ${component}'s "${aliased.templateName}" input. Use "${aliased.templateName}", the name a template binds.`);
85
+ }
86
+ const known = mirror.inputs
87
+ .map((input) => `"${input.templateName}"`)
88
+ .join(', ');
89
+ throw new Error(`${caller} can't set "${missing}": ${component} has no input by that name. ` +
90
+ (known ? `Its inputs are ${known}. ` : 'It has no inputs. ') +
91
+ 'Plain Vitest compiles components just in time, where Angular sees no input() or model() inputs; ng test compiles them ahead of time.');
92
+ };
93
+ /**
94
+ * Renders `rootComponent` as a Lynx app's root component, with
95
+ * `options.inputs` bound to its inputs, and resolves once the first change
96
+ * detection has run.
97
+ */
29
98
  export const render = async (rootComponent, options = {}) => {
30
99
  cleanup();
100
+ const mirror = reflectRootComponent(rootComponent);
101
+ const inputs = { ...options.inputs };
102
+ const boundNames = new Set(Object.keys(inputs));
103
+ assertInputsExist(mirror, [...boundNames], 'render()');
31
104
  // Switch to main thread so PAPI functions (__CreatePage, __CreateView, …)
32
105
  // are available as globals. LynxDocument requires them to create elements.
33
106
  const env = globalThis.lynxTestingEnv;
@@ -35,27 +108,70 @@ export const render = async (rootComponent, options = {}) => {
35
108
  // Clear JSDOM body so previous render's elements are gone.
36
109
  const doc = globalThis.document;
37
110
  doc.body.innerHTML = '';
38
- // Bootstrap Angular. LynxDocument.createRootElement() runs during bootstrap,
39
- // calling __CreatePage which appends the <page> element to document.body.
40
- const appRef = await bootstrapApplication(rootComponent, {
111
+ // Each input reads its value from this signal. A binding is evaluated in the
112
+ // root view on every change detection, so rerender({ inputs }) only has to
113
+ // set the signal: reading it marks the root view for refresh, and Angular
114
+ // passes the new value on as a parent template's binding would. With no
115
+ // inputs there are no bindings, so componentRef.setInput() still works.
116
+ const inputValues = signal(inputs);
117
+ const bindings = [...boundNames].map((name) => inputBinding(name, () => inputValues()[name]));
118
+ // bootstrapApplication() takes no bindings, and setting inputs after it
119
+ // returns would be too late: bootstrap runs the first change detection, so
120
+ // ngOnInit would see the defaults and reading an unset required input would
121
+ // throw (NG0950). createApplication() plus appRef.bootstrap() is the same
122
+ // bootstrap, split so the bindings can go in.
123
+ const appRef = await createApplication({
41
124
  providers: [
42
125
  provideZonelessChangeDetection(),
43
126
  provideRenderer(),
44
127
  ...(options.providers ?? []),
45
128
  ],
46
129
  });
130
+ // Set before bootstrapping, so cleanup() destroys the app even when the
131
+ // component throws while it's created.
47
132
  currentAppRef = appRef;
133
+ // LynxDocument.createRootElement() runs during bootstrap, calling
134
+ // __CreatePage which appends the <page> element to document.body.
135
+ const componentRef = appRef.bootstrap(rootComponent, { bindings });
48
136
  // Force a synchronous CD cycle so signal-initialized state is reflected in
49
- // the DOM before we return. bootstrapApplication already triggers one CD,
50
- // but zoneless scheduling may defer follow-up updates to a microtask.
137
+ // the DOM before we return. bootstrap already triggers one CD, but work it
138
+ // starts may defer follow-up updates to a microtask: ngModel writes its
139
+ // value a microtask later, and the control only shows it at the next CD.
140
+ // Awaiting bootstrapApplication() let those run first, so wait as long.
141
+ await settleBootstrapMicrotasks();
51
142
  appRef.tick();
52
143
  // elementTree.root is the JSDOM <page> element created by __CreatePage.
53
144
  const container = globalThis.elementTree.root;
54
- const componentRef = appRef.components[0];
55
- return {
145
+ /**
146
+ * rerender({ inputs }): updates the bound inputs in place and runs change
147
+ * detection, so the DOM shows them when the promise resolves.
148
+ */
149
+ const changeInputs = async (changed) => {
150
+ // A result whose app was unmounted, or replaced by a later render(), has
151
+ // no component left to change. Setting the signal would do nothing, and
152
+ // the tick would only warn that the app is destroyed.
153
+ if (currentAppRef !== appRef) {
154
+ throw new Error('rerender({ inputs }) has no component to change: it was unmounted, or a later render() replaced it.');
155
+ }
156
+ const names = Object.keys(changed);
157
+ assertInputsExist(mirror, names, 'rerender({ inputs })');
158
+ const unbound = names.find((name) => !boundNames.has(name));
159
+ if (unbound !== undefined) {
160
+ throw new Error(`rerender({ inputs }) can only change inputs render() set, and render() didn't set "${unbound}". ` +
161
+ "Give it a starting value in render()'s inputs: Angular sets those through input bindings, and a component with input bindings can't take other inputs.");
162
+ }
163
+ inputValues.update((values) => ({ ...values, ...changed }));
164
+ appRef.tick();
165
+ return result;
166
+ };
167
+ const result = {
56
168
  container,
57
169
  unmount: () => cleanup(),
58
- rerender: (newComponent, newOptions) => render(newComponent, newOptions ?? {}),
170
+ rerender: (componentOrUpdate, newOptions) =>
171
+ // A component is a class, so a function; the update is a plain object.
172
+ typeof componentOrUpdate === 'function'
173
+ ? render(componentOrUpdate, newOptions)
174
+ : changeInputs(componentOrUpdate.inputs),
59
175
  asFragment: () => document.createRange().createContextualFragment(container.outerHTML),
60
176
  componentRef,
61
177
  ...getQueriesForElement(container, {
@@ -63,6 +179,7 @@ export const render = async (rootComponent, options = {}) => {
63
179
  ...options.queries,
64
180
  }),
65
181
  };
182
+ return result;
66
183
  };
67
184
  /**
68
185
  * Wait for all pending Angular reactive updates to flush through the pipeline.
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@blotch/angular-lynx-testing-library",
3
- "version": "22.2.8",
3
+ "version": "22.2.10",
4
4
  "description": "Testing utilities for AngularLynx apps",
5
5
  "homepage": "https://github.com/Blotch-Smart-Frames/AngularLynx#readme",
6
6
  "bugs": {