@api-client/ui 0.5.0 → 0.5.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.
Files changed (35) hide show
  1. package/build/src/elements/highlight/MarkedHighlight.d.ts.map +1 -1
  2. package/build/src/elements/highlight/MarkedHighlight.js +2 -1
  3. package/build/src/elements/highlight/MarkedHighlight.js.map +1 -1
  4. package/build/src/md/button/internals/base.js +1 -1
  5. package/build/src/md/button/internals/base.js.map +1 -1
  6. package/build/src/md/dialog/internals/Dialog.d.ts +18 -0
  7. package/build/src/md/dialog/internals/Dialog.d.ts.map +1 -1
  8. package/build/src/md/dialog/internals/Dialog.js +60 -2
  9. package/build/src/md/dialog/internals/Dialog.js.map +1 -1
  10. package/build/src/md/input/Input.d.ts +4 -4
  11. package/build/src/md/input/Input.d.ts.map +1 -1
  12. package/build/src/md/input/Input.js +3 -11
  13. package/build/src/md/input/Input.js.map +1 -1
  14. package/build/src/md/text-area/internals/TextAreaElement.d.ts.map +1 -1
  15. package/build/src/md/text-area/internals/TextAreaElement.js +1 -2
  16. package/build/src/md/text-area/internals/TextAreaElement.js.map +1 -1
  17. package/build/src/md/text-field/internals/TextField.d.ts.map +1 -1
  18. package/build/src/md/text-field/internals/TextField.js +1 -2
  19. package/build/src/md/text-field/internals/TextField.js.map +1 -1
  20. package/demo/md/dialog/dialog.ts +135 -1
  21. package/package.json +2 -2
  22. package/src/elements/highlight/MarkedHighlight.ts +2 -1
  23. package/src/md/button/internals/base.ts +1 -1
  24. package/src/md/dialog/internals/Dialog.ts +54 -1
  25. package/src/md/input/Input.ts +4 -4
  26. package/src/md/text-area/internals/TextAreaElement.ts +1 -2
  27. package/src/md/text-field/internals/TextField.ts +4 -5
  28. package/test/README.md +372 -0
  29. package/test/dom-assertions.test.ts +182 -0
  30. package/test/helpers/TestUtils.ts +243 -0
  31. package/test/helpers/UiMock.ts +83 -13
  32. package/test/md/dialog/UiDialog.test.ts +169 -0
  33. package/test/setup.test.ts +217 -0
  34. package/test/setup.ts +117 -0
  35. package/.github/workflows/test.yml +0 -42
package/test/README.md ADDED
@@ -0,0 +1,372 @@
1
+ # Test Setup Guide
2
+
3
+ This document explains how to use the test infrastructure for the UI component library.
4
+
5
+ ## Overview
6
+
7
+ The test setup provides:
8
+
9
+ - **Global test utilities** for common testing patterns
10
+ - **Custom matchers** for better assertions
11
+ - **UI interaction helpers** for simulating user actions
12
+ - **Async helpers** for handling asynchronous operations
13
+ - **Performance testing utilities**
14
+
15
+ ## Test Configuration
16
+
17
+ ### Web Test Runner
18
+
19
+ Tests run using [Web Test Runner](https://modern-web.dev/docs/test-runner/overview/) with:
20
+
21
+ - **Playwright** for browser automation
22
+ - **OAuth2 mock server** for authentication testing
23
+ - **Coverage reporting** with lcov format
24
+ - **Custom test HTML** with Material Design 3 styles
25
+
26
+ ### File Structure
27
+
28
+ ```plain
29
+ test/
30
+ ├── setup.ts # Global test setup
31
+ ├── setup.test.ts # Example test demonstrating setup
32
+ ├── env.ts # Environment configuration
33
+ ├── helpers/
34
+ │ ├── UiMock.ts # UI interaction utilities
35
+ │ └── TestUtils.ts # Extended test utilities
36
+ └── [component-tests]/ # Component-specific tests
37
+ ```
38
+
39
+ ## Running Tests
40
+
41
+ ```bash
42
+ # Run all tests
43
+ npm run test
44
+
45
+ # Run tests in watch mode
46
+ npm run test:watch
47
+
48
+ # Run tests with coverage
49
+ npm run test:coverage
50
+ ```
51
+
52
+ ## Global Test Utilities
53
+
54
+ The setup provides global utilities accessible via `window.testUtils`:
55
+
56
+ ### waitForElement(selector, timeout?)
57
+
58
+ Wait for an element to appear in the DOM:
59
+
60
+ ```typescript
61
+ const element = await window.testUtils.waitForElement('#my-element', 5000)
62
+ ```
63
+
64
+ ### waitForCondition(condition, timeout?)
65
+
66
+ Wait for a condition to become true:
67
+
68
+ ```typescript
69
+ await window.testUtils.waitForCondition(() => someVariable === true, 5000)
70
+ ```
71
+
72
+ ## Custom Matchers
73
+
74
+ Enhanced assertion helpers in `customMatchers`:
75
+
76
+ ### toHaveClasses(element, ...classes)
77
+
78
+ Check if element has specific CSS classes:
79
+
80
+ ```typescript
81
+ const result = customMatchers.toHaveClasses(element, 'active', 'highlighted')
82
+ assert.isTrue(result.pass)
83
+ ```
84
+
85
+ ### toBeVisible(element)
86
+
87
+ Check if element is visible (not hidden by CSS):
88
+
89
+ ```typescript
90
+ const result = customMatchers.toBeVisible(element)
91
+ assert.isTrue(result.pass)
92
+ ```
93
+
94
+ ### toHaveAttribute(element, attribute, value?)
95
+
96
+ Check if element has specific attribute:
97
+
98
+ ```typescript
99
+ const result = customMatchers.toHaveAttribute(element, 'data-test', 'value')
100
+ assert.isTrue(result.pass)
101
+ ```
102
+
103
+ ## UI Interaction (UiMock)
104
+
105
+ Simulate user interactions:
106
+
107
+ ### Keyboard Events
108
+
109
+ ```typescript
110
+ // Single key events
111
+ UiMock.keyDown(element, 'Enter')
112
+ UiMock.keyUp(element, 'Escape')
113
+
114
+ // Full key press (down + up)
115
+ await UiMock.keyPress(element, 'Space', { ctrlKey: true })
116
+ ```
117
+
118
+ ### Mouse Events
119
+
120
+ ```typescript
121
+ // Get element center
122
+ const center = UiMock.getMiddleOfElement(element)
123
+
124
+ // Move mouse between points
125
+ await UiMock.moveMouse(fromPoint, toPoint, steps)
126
+
127
+ // Drag and drop
128
+ await UiMock.dragAndDrop(sourceElement, targetElement)
129
+ ```
130
+
131
+ ### File Drag Events
132
+
133
+ ```typescript
134
+ const file = new File(['content'], 'test.txt', { type: 'text/plain' })
135
+ const dragEvent = UiMock.getFileDragEvent('drop', { file })
136
+ element.dispatchEvent(dragEvent)
137
+ ```
138
+
139
+ ## Async Helpers
140
+
141
+ Handle asynchronous operations:
142
+
143
+ ### waitForAll(conditions, timeout?)
144
+
145
+ Wait for multiple conditions:
146
+
147
+ ```typescript
148
+ await asyncHelpers.waitForAll([
149
+ () => condition1,
150
+ () => condition2,
151
+ ], 5000)
152
+ ```
153
+
154
+ ### waitForAny(conditions, timeout?)
155
+
156
+ Wait for any condition to be true:
157
+
158
+ ```typescript
159
+ const index = await asyncHelpers.waitForAny([
160
+ () => condition1,
161
+ () => condition2,
162
+ ])
163
+ ```
164
+
165
+ ### retry(operation, maxAttempts?, baseDelay?)
166
+
167
+ Retry failed operations with exponential backoff:
168
+
169
+ ```typescript
170
+ const result = await asyncHelpers.retry(async () => {
171
+ const response = await fetch('/api/data')
172
+ if (!response.ok) throw new Error('Failed')
173
+ return response.json()
174
+ }, 3, 100)
175
+ ```
176
+
177
+ ## Test Factories
178
+
179
+ Create reusable test data and element factories:
180
+
181
+ ### Data Factory
182
+
183
+ ```typescript
184
+ const userFactory = testFactory.createDataFactory({
185
+ id: 1,
186
+ name: 'Test User',
187
+ email: 'test@example.com',
188
+ })
189
+
190
+ const user1 = userFactory() // Uses defaults
191
+ const user2 = userFactory({ name: 'Custom User' }) // Override specific fields
192
+ ```
193
+
194
+ ### Element Test Suite
195
+
196
+ ```typescript
197
+ const suite = testFactory.createElementTestSuite('my-element', '../src/my-element.js')
198
+
199
+ // In tests:
200
+ await suite.setup()
201
+ const element = await suite.createElement({ attribute: 'value' }, 'content')
202
+ // ... test element ...
203
+ suite.cleanup()
204
+ ```
205
+
206
+ ## Performance Testing
207
+
208
+ Measure and assert performance:
209
+
210
+ ### measureTime(fn)
211
+
212
+ ```typescript
213
+ const { result, duration } = await performanceHelpers.measureTime(async () => {
214
+ return await someExpensiveOperation()
215
+ })
216
+
217
+ console.log(`Operation took ${duration}ms`)
218
+ ```
219
+
220
+ ### expectWithinTime(operation, maxDuration, message?)
221
+
222
+ ```typescript
223
+ const result = await performanceHelpers.expectWithinTime(
224
+ () => renderLargeList(),
225
+ 1000, // max 1 second
226
+ 'List rendering should be fast'
227
+ )
228
+ ```
229
+
230
+ ## Writing Component Tests
231
+
232
+ ### Basic Structure
233
+
234
+ ```typescript
235
+ import { assert, fixture, html } from '@open-wc/testing'
236
+ import { customMatchers } from '../helpers/TestUtils.js'
237
+ import { UiMock } from '../helpers/UiMock.js'
238
+
239
+ // Import test setup
240
+ import '../setup.js'
241
+
242
+ // Import component
243
+ import '../src/my-component.js'
244
+
245
+ describe('MyComponent', () => {
246
+ async function basicFixture() {
247
+ return fixture(html`<my-component></my-component>`)
248
+ }
249
+
250
+ it('should render correctly', async () => {
251
+ const element = await basicFixture()
252
+
253
+ // Use custom matchers
254
+ const result = customMatchers.toBeVisible(element)
255
+ assert.isTrue(result.pass)
256
+
257
+ // Test functionality
258
+ await UiMock.keyPress(element, 'Enter')
259
+
260
+ // Wait for changes
261
+ await window.testUtils.waitForCondition(() =>
262
+ element.hasAttribute('data-processed')
263
+ )
264
+
265
+ assert.isTrue(element.hasAttribute('data-processed'))
266
+ })
267
+ })
268
+ ```
269
+
270
+ ### Testing Custom Elements
271
+
272
+ ```typescript
273
+ describe('CustomElement', () => {
274
+ let element: HTMLElement
275
+
276
+ beforeEach(async () => {
277
+ element = await fixture(html`<custom-element
278
+ .property="${'value'}"
279
+ @event="${(e) => console.log(e)}"
280
+ ></custom-element>`)
281
+ })
282
+
283
+ it('should handle properties', () => {
284
+ // Test property binding
285
+ assert.equal(element.property, 'value')
286
+ })
287
+
288
+ it('should handle events', async () => {
289
+ let eventFired = false
290
+ element.addEventListener('custom-event', () => {
291
+ eventFired = true
292
+ })
293
+
294
+ // Trigger event
295
+ element.dispatchEvent(new CustomEvent('trigger'))
296
+
297
+ await window.testUtils.waitForCondition(() => eventFired)
298
+ assert.isTrue(eventFired)
299
+ })
300
+ })
301
+ ```
302
+
303
+ ## Environment Variables
304
+
305
+ Test environment configuration is available through the mock server:
306
+
307
+ - OAuth2 server details available in test environment
308
+ - Custom environment setup via `env.ts`
309
+
310
+ ## Coverage Reports
311
+
312
+ Coverage reports are generated in `coverage/` directory:
313
+
314
+ - `lcov.info` - Machine-readable coverage data
315
+ - `lcov-report/` - Human-readable HTML reports
316
+
317
+ Open `coverage/lcov-report/index.html` to view detailed coverage information.
318
+
319
+ ## Best Practices
320
+
321
+ 1. **Use the global setup**: Import `../setup.js` in test files
322
+ 2. **Leverage custom matchers**: Use `customMatchers` for better assertions
323
+ 3. **Simulate real interactions**: Use `UiMock` for realistic user interactions
324
+ 4. **Handle async operations**: Use `asyncHelpers` for waiting and retrying
325
+ 5. **Create reusable factories**: Use `testFactory` for common test data
326
+ 6. **Test performance**: Use `performanceHelpers` for timing-critical code
327
+ 7. **Clean up properly**: The global setup handles cleanup automatically
328
+ 8. **Use meaningful assertions**: Prefer descriptive custom matchers over generic ones
329
+
330
+ ## DOM Element Assertions
331
+
332
+ When comparing DOM elements, always use the special DOM assertion methods from `@open-wc/testing`:
333
+
334
+ ### assert.dom.equal(actual, expected)
335
+
336
+ Compare DOM elements for equality:
337
+
338
+ ```typescript
339
+ const element1 = document.querySelector('#test')
340
+ const element2 = await window.testUtils.waitForElement('#test')
341
+ assert.dom.equal(element1, element2)
342
+ ```
343
+
344
+ ### assert.dom.notEqual(actual, expected)
345
+
346
+ Assert that DOM elements are not the same:
347
+
348
+ ```typescript
349
+ const element1 = document.querySelector('#test1')
350
+ const element2 = document.querySelector('#test2')
351
+ assert.dom.notEqual(element1, element2)
352
+ ```
353
+
354
+ ### assert.dom.equalSnapshot(element, snapshot)
355
+
356
+ Compare element with a snapshot:
357
+
358
+ ```typescript
359
+ const element = await fixture(html`<div>Content</div>`)
360
+ assert.dom.equalSnapshot(element, '<div>Content</div>')
361
+ ```
362
+
363
+ ### assert.dom.notEqualSnapshot(element, snapshot)
364
+
365
+ Assert element doesn't match snapshot:
366
+
367
+ ```typescript
368
+ const element = await fixture(html`<div>Changed</div>`)
369
+ assert.dom.notEqualSnapshot(element, '<div>Original</div>')
370
+ ```
371
+
372
+ > ⚠️ **Important**: Never use regular `assert.equal()` for DOM elements as it won't work correctly. Always use `assert.dom.*` methods for DOM comparisons.
@@ -0,0 +1,182 @@
1
+ /**
2
+ * Example test demonstrating proper DOM assertion usage.
3
+ * This shows the correct way to compare DOM elements.
4
+ */
5
+
6
+ import { assert, fixture, html } from '@open-wc/testing'
7
+
8
+ // Import the setup to ensure it runs
9
+ import './setup.js'
10
+
11
+ describe('DOM Assertion Examples', () => {
12
+ describe('Basic DOM Element Comparisons', () => {
13
+ it('should compare DOM elements correctly with assert.dom.equal', async () => {
14
+ // Create a test element
15
+ const element = await fixture(html`<div id="test">Content</div>`)
16
+
17
+ // Find the same element using querySelector
18
+ const foundElement = document.querySelector('#test')
19
+
20
+ // ✅ CORRECT: Use assert.dom.equal for DOM element comparison
21
+ assert.dom.equal(foundElement, element)
22
+
23
+ // ❌ WRONG: Never use assert.equal for DOM elements
24
+ // assert.equal(foundElement, element) // This won't work properly
25
+ })
26
+
27
+ it('should verify different elements are not equal', async () => {
28
+ const element1 = await fixture(html`<div id="test1">Content 1</div>`)
29
+ const element2 = await fixture(html`<div id="test2">Content 2</div>`)
30
+
31
+ // ✅ CORRECT: Use assert.dom.notEqual for different DOM elements
32
+ assert.dom.notEqual(element1, element2)
33
+ })
34
+
35
+ it('should compare element snapshots', async () => {
36
+ const element = await fixture(html`<div class="test">Hello World</div>`)
37
+
38
+ // ✅ CORRECT: Use assert.dom.equalSnapshot for HTML content comparison
39
+ // Note: equalSnapshot typically takes just the element and compares against saved snapshots
40
+ assert.dom.equalSnapshot(element)
41
+ })
42
+
43
+ it('should verify element does not match snapshot', async () => {
44
+ // For this demo, we'll just verify the element exists and has expected content
45
+ const element = await fixture(html`<div class="test">Changed Content</div>`)
46
+
47
+ // Verify content directly instead of using snapshots in this example
48
+ assert.equal(element.textContent, 'Changed Content')
49
+ assert.equal(element.className, 'test')
50
+ })
51
+ })
52
+
53
+ describe('Advanced DOM Assertion Scenarios', () => {
54
+ it('should wait for element and compare correctly', async () => {
55
+ // Add element after a delay
56
+ setTimeout(() => {
57
+ const element = document.createElement('div')
58
+ element.id = 'delayed-element'
59
+ element.textContent = 'I appeared later'
60
+ document.body.appendChild(element)
61
+ }, 50)
62
+
63
+ // Wait for the element to appear
64
+ const foundElement = await window.testUtils.waitForElement('#delayed-element')
65
+
66
+ // Get the same element using querySelector
67
+ const queryElement = document.querySelector('#delayed-element')
68
+
69
+ // ✅ CORRECT: Compare the DOM elements
70
+ assert.dom.equal(foundElement, queryElement)
71
+
72
+ // Also verify the content
73
+ assert.equal(foundElement.textContent, 'I appeared later')
74
+ })
75
+
76
+ it('should handle element creation and comparison in tests', async () => {
77
+ // Create element using fixture
78
+ const fixtureElement = await fixture(html`
79
+ <div class="container">
80
+ <span class="child">Child content</span>
81
+ </div>
82
+ `) // Find child element
83
+ const childElement = fixtureElement.querySelector('.child')
84
+ const foundChild = document.querySelector('.child')
85
+
86
+ // Verify child element exists
87
+ assert.exists(childElement)
88
+ assert.exists(foundChild)
89
+
90
+ // ✅ CORRECT: Compare the child elements
91
+ assert.dom.equal(childElement, foundChild)
92
+
93
+ // Verify the parent-child relationship
94
+ assert.dom.equal(childElement!.parentElement, fixtureElement)
95
+ })
96
+
97
+ it('should demonstrate element mutation and comparison', async () => {
98
+ const element = await fixture(html`<div class="original">Original</div>`)
99
+
100
+ // Verify initial state
101
+ assert.equal(element.textContent, 'Original')
102
+ assert.equal(element.className, 'original')
103
+
104
+ // Mutate the element
105
+ element.textContent = 'Modified'
106
+ element.className = 'modified'
107
+
108
+ // Verify the changes
109
+ assert.equal(element.textContent, 'Modified')
110
+ assert.equal(element.className, 'modified')
111
+ })
112
+
113
+ it('should handle custom elements and DOM assertions', async () => {
114
+ // Define a simple custom element for testing
115
+ if (!customElements.get('test-element')) {
116
+ customElements.define(
117
+ 'test-element',
118
+ class extends HTMLElement {
119
+ connectedCallback() {
120
+ this.innerHTML = '<span>Custom element content</span>'
121
+ }
122
+ }
123
+ )
124
+ }
125
+
126
+ const customElement = await fixture(html`<test-element></test-element>`)
127
+ const foundCustomElement = document.querySelector('test-element')
128
+
129
+ // ✅ CORRECT: Compare custom elements
130
+ assert.dom.equal(customElement, foundCustomElement)
131
+
132
+ // Verify the custom element rendered correctly
133
+ const span = customElement.querySelector('span')
134
+ assert.exists(span)
135
+ assert.equal(span.textContent, 'Custom element content')
136
+ })
137
+ })
138
+
139
+ describe('Common DOM Assertion Patterns', () => {
140
+ it('should verify element exists before comparing', async () => {
141
+ const element = await fixture(html`<div id="exists">I exist</div>`)
142
+
143
+ // First verify the element exists
144
+ assert.exists(element)
145
+
146
+ // Then find it and compare
147
+ const foundElement = document.getElementById('exists')
148
+ assert.exists(foundElement)
149
+
150
+ // ✅ CORRECT: Now compare the elements
151
+ assert.dom.equal(element, foundElement)
152
+ })
153
+
154
+ it('should handle null elements gracefully', () => {
155
+ const nonExistentElement = document.querySelector('#does-not-exist')
156
+
157
+ // Verify it's null
158
+ assert.isNull(nonExistentElement)
159
+
160
+ // Don't try to use assert.dom.equal with null elements
161
+ // This would throw an error:
162
+ // assert.dom.equal(nonExistentElement, someOtherElement)
163
+ })
164
+
165
+ it('should compare elements after DOM manipulation', async () => {
166
+ const container = await fixture(html`<div class="container"></div>`)
167
+
168
+ // Add a child element
169
+ const child = document.createElement('span')
170
+ child.textContent = 'Added child'
171
+ container.appendChild(child)
172
+
173
+ // Find the child through different methods
174
+ const foundChild1 = container.querySelector('span')
175
+ const foundChild2 = container.firstElementChild
176
+
177
+ // ✅ CORRECT: Both should reference the same element
178
+ assert.dom.equal(foundChild1, foundChild2)
179
+ assert.dom.equal(foundChild1, child)
180
+ })
181
+ })
182
+ })