@api-client/ui 0.5.0 → 0.5.1

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,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
+ })
@@ -0,0 +1,243 @@
1
+ /**
2
+ * Extended test utilities for the UI component library.
3
+ * Provides Jest-like matchers and additional testing helpers.
4
+ */
5
+
6
+ import { expect } from '@open-wc/testing'
7
+
8
+ /**
9
+ * Custom matchers for better test assertions
10
+ */
11
+ export const customMatchers = {
12
+ /**
13
+ * Check if an element has specific CSS classes
14
+ */
15
+ toHaveClasses(received: Element, ...classes: string[]) {
16
+ const classList = Array.from(received.classList)
17
+ const missing = classes.filter((cls) => !classList.includes(cls))
18
+
19
+ if (missing.length === 0) {
20
+ return {
21
+ message: () => `Expected element not to have classes: ${classes.join(', ')}`,
22
+ pass: true,
23
+ }
24
+ } else {
25
+ return {
26
+ message: () => `Expected element to have classes: ${missing.join(', ')}`,
27
+ pass: false,
28
+ }
29
+ }
30
+ },
31
+
32
+ /**
33
+ * Check if an element is visible (not hidden by CSS)
34
+ */
35
+ toBeVisible(received: Element) {
36
+ const style = window.getComputedStyle(received)
37
+ const isVisible = style.display !== 'none' && style.visibility !== 'hidden' && style.opacity !== '0'
38
+
39
+ if (isVisible) {
40
+ return {
41
+ message: () => 'Expected element to be hidden',
42
+ pass: true,
43
+ }
44
+ } else {
45
+ return {
46
+ message: () => 'Expected element to be visible',
47
+ pass: false,
48
+ }
49
+ }
50
+ },
51
+
52
+ /**
53
+ * Check if an element has a specific attribute value
54
+ */
55
+ toHaveAttribute(received: Element, attribute: string, value?: string) {
56
+ const hasAttribute = received.hasAttribute(attribute)
57
+
58
+ if (!hasAttribute) {
59
+ return {
60
+ message: () => `Expected element to have attribute "${attribute}"`,
61
+ pass: false,
62
+ }
63
+ }
64
+
65
+ if (value !== undefined) {
66
+ const actualValue = received.getAttribute(attribute)
67
+ if (actualValue !== value) {
68
+ return {
69
+ message: () => `Expected attribute "${attribute}" to be "${value}", but got "${actualValue}"`,
70
+ pass: false,
71
+ }
72
+ }
73
+ }
74
+
75
+ return {
76
+ message: () => `Expected element not to have attribute "${attribute}"${value ? ` with value "${value}"` : ''}`,
77
+ pass: true,
78
+ }
79
+ },
80
+
81
+ /**
82
+ * Helper to demonstrate proper DOM element comparison
83
+ * Note: Always use assert.dom.equal() for DOM element comparison, not assert.equal()
84
+ */
85
+ domElementsEqual(actual: Element, expected: Element): boolean {
86
+ // This is just a helper - in actual tests, use assert.dom.equal(actual, expected)
87
+ return actual === expected && actual.isEqualNode(expected)
88
+ },
89
+ }
90
+
91
+ /**
92
+ * Test factory functions for common test scenarios
93
+ */
94
+ export const testFactory = {
95
+ /**
96
+ * Create a test suite for a custom element
97
+ */
98
+ createElementTestSuite(elementName: string, importPath: string) {
99
+ return {
100
+ async setup() {
101
+ await import(importPath)
102
+ },
103
+
104
+ async createElement(attributes: Record<string, string> = {}, content = '') {
105
+ const attrs = Object.entries(attributes)
106
+ .map(([key, value]) => `${key}="${value}"`)
107
+ .join(' ')
108
+
109
+ const element = document.createElement('div')
110
+ element.innerHTML = `<${elementName} ${attrs}>${content}</${elementName}>`
111
+ document.body.appendChild(element)
112
+
113
+ return element.firstElementChild as HTMLElement
114
+ },
115
+
116
+ cleanup() {
117
+ document.body.innerHTML = ''
118
+ },
119
+ }
120
+ },
121
+
122
+ /**
123
+ * Create a test data factory
124
+ */
125
+ createDataFactory<T>(defaults: T) {
126
+ return (overrides: Partial<T> = {}): T => ({
127
+ ...defaults,
128
+ ...overrides,
129
+ })
130
+ },
131
+ }
132
+
133
+ /**
134
+ * Async test helpers
135
+ */
136
+ export const asyncHelpers = {
137
+ /**
138
+ * Wait for multiple conditions to be true
139
+ */
140
+ async waitForAll(conditions: (() => boolean)[], timeout = 5000): Promise<void> {
141
+ const promises = conditions.map((condition) => window.testUtils.waitForCondition(condition, timeout))
142
+ await Promise.all(promises)
143
+ },
144
+
145
+ /**
146
+ * Wait for any of multiple conditions to be true
147
+ */
148
+ async waitForAny(conditions: (() => boolean)[], timeout = 5000): Promise<number> {
149
+ return new Promise((resolve, reject) => {
150
+ const startTime = Date.now()
151
+ let resolved = false
152
+
153
+ function checkConditions() {
154
+ if (resolved) return
155
+
156
+ for (let i = 0; i < conditions.length; i++) {
157
+ try {
158
+ if (conditions[i]()) {
159
+ resolved = true
160
+ resolve(i)
161
+ return
162
+ }
163
+ } catch {
164
+ // Continue checking other conditions
165
+ }
166
+ }
167
+
168
+ if (Date.now() - startTime > timeout) {
169
+ resolved = true
170
+ reject(new Error(`None of the conditions met within ${timeout}ms`))
171
+ return
172
+ }
173
+
174
+ setTimeout(checkConditions, 50)
175
+ }
176
+
177
+ checkConditions()
178
+ })
179
+ },
180
+
181
+ /**
182
+ * Retry an async operation with exponential backoff
183
+ */
184
+ async retry<T>(operation: () => Promise<T>, maxAttempts = 3, baseDelay = 100): Promise<T> {
185
+ let lastError: Error
186
+
187
+ for (let attempt = 1; attempt <= maxAttempts; attempt++) {
188
+ try {
189
+ return await operation()
190
+ } catch (error) {
191
+ lastError = error as Error
192
+
193
+ if (attempt === maxAttempts) {
194
+ throw lastError
195
+ }
196
+
197
+ const delay = baseDelay * Math.pow(2, attempt - 1)
198
+ await new Promise((resolve) => setTimeout(resolve, delay))
199
+ }
200
+ }
201
+
202
+ throw lastError!
203
+ },
204
+ }
205
+
206
+ /**
207
+ * Performance testing utilities
208
+ */
209
+ export const performanceHelpers = {
210
+ /**
211
+ * Measure the execution time of a function
212
+ */
213
+ async measureTime<T>(fn: () => Promise<T> | T): Promise<{ result: T; duration: number }> {
214
+ const start = performance.now()
215
+ const result = await fn()
216
+ const duration = performance.now() - start
217
+
218
+ return { result, duration }
219
+ },
220
+
221
+ /**
222
+ * Assert that an operation completes within a time limit
223
+ */
224
+ async expectWithinTime<T>(operation: () => Promise<T> | T, maxDuration: number, message?: string): Promise<T> {
225
+ const { result, duration } = await this.measureTime(operation)
226
+
227
+ if (duration > maxDuration) {
228
+ const errorMessage = message || `Operation took ${duration.toFixed(2)}ms, expected < ${maxDuration}ms`
229
+ throw new Error(errorMessage)
230
+ }
231
+
232
+ return result
233
+ },
234
+ }
235
+
236
+ // Export all utilities
237
+ export { expect }
238
+ export default {
239
+ customMatchers,
240
+ testFactory,
241
+ asyncHelpers,
242
+ performanceHelpers,
243
+ }
@@ -1,13 +1,34 @@
1
1
  import { nextFrame } from '@open-wc/testing'
2
2
  import { sendMouse } from '@web/test-runner-commands'
3
3
 
4
+ /**
5
+ * Represents a 2D point with x and y coordinates.
6
+ */
4
7
  export interface Point {
8
+ /** The x-coordinate of the point. */
5
9
  x: number
10
+ /** The y-coordinate of the point. */
6
11
  y: number
7
12
  }
8
13
 
14
+ /**
15
+ * A utility class for mocking user interface interactions in tests.
16
+ * It provides static methods to simulate keyboard and mouse events.
17
+ * This class is designed as a collection of static helpers, hence it has no constructor or instances.
18
+ */
9
19
  // eslint-disable-next-line @typescript-eslint/no-extraneous-class
10
20
  export class UiMock {
21
+ /**
22
+ * Dispatches a 'keydown' event on a given element.
23
+ *
24
+ * @param element The target element for the event.
25
+ * @param code The `code` value for the KeyboardEvent (e.g., 'Enter', 'KeyA').
26
+ * @param opts Additional options to pass to the KeyboardEvent constructor.
27
+ *
28
+ * @example
29
+ * UiMock.keyDown(document.body, 'Enter');
30
+ * UiMock.keyDown(myInputElement, 'KeyA', { ctrlKey: true });
31
+ */
11
32
  static keyDown(element: EventTarget, code: string, opts: KeyboardEventInit = {}): void {
12
33
  const defaults: KeyboardEventInit = {
13
34
  bubbles: true,
@@ -19,6 +40,16 @@ export class UiMock {
19
40
  element.dispatchEvent(down)
20
41
  }
21
42
 
43
+ /**
44
+ * Dispatches a 'keyup' event on a given element.
45
+ *
46
+ * @param element The target element for the event.
47
+ * @param code The `code` value for the KeyboardEvent (e.g., 'Escape', 'KeyB').
48
+ * @param opts Additional options to pass to the KeyboardEvent constructor.
49
+ *
50
+ * @example
51
+ * UiMock.keyUp(document.body, 'Escape');
52
+ */
22
53
  static keyUp(element: EventTarget, code: string, opts: KeyboardEventInit = {}): void {
23
54
  const defaults: KeyboardEventInit = {
24
55
  bubbles: true,
@@ -30,12 +61,35 @@ export class UiMock {
30
61
  element.dispatchEvent(down)
31
62
  }
32
63
 
64
+ /**
65
+ * Simulates a full key press by dispatching 'keydown' and 'keyup' events sequentially.
66
+ * It waits for the next animation frame between the two events.
67
+ *
68
+ * @param element The target element for the event.
69
+ * @param code The `code` value for the KeyboardEvent.
70
+ * @param opts Additional options to pass to the KeyboardEvent constructor.
71
+ *
72
+ * @example
73
+ * await UiMock.keyPress(myButton, 'Space');
74
+ */
33
75
  static async keyPress(element: EventTarget, code: string, opts?: KeyboardEventInit): Promise<void> {
34
76
  this.keyDown(element, code, opts)
35
77
  await nextFrame()
36
78
  this.keyUp(element, code, opts)
37
79
  }
38
80
 
81
+ /**
82
+ * Calculates the coordinates of the center of a given element.
83
+ *
84
+ * Note: This method mixes coordinate systems. `getBoundingClientRect` is viewport-relative,
85
+ * while `window.scrollY` is for document scrolling and `window.screenX` is for the
86
+ * screen position of the browser window. For use with `@web/test-runner-commands`'s `sendMouse`,
87
+ * which expects viewport-relative coordinates, the calculation should likely be:
88
+ * `x: Math.floor(x + width / 2)` and `y: Math.floor(y + height / 2)`.
89
+ *
90
+ * @param element The element to find the center of.
91
+ * @returns A `Point` object with the x and y coordinates of the element's center.
92
+ */
39
93
  static getMiddleOfElement(element: Element): Point {
40
94
  const { x, y, width, height } = element.getBoundingClientRect()
41
95
 
@@ -46,20 +100,21 @@ export class UiMock {
46
100
  }
47
101
 
48
102
  /**
49
- * Moves the mouse from the `from` point to the `to` point using the Playwright API.
50
- * This means the mouse will actually move in the browser.
103
+ * Moves the mouse from a starting point to an ending point in a series of steps.
104
+ * This uses the `@web/test-runner-commands` `sendMouse` API, which means
105
+ * the mouse will actually move in the browser running the tests.
51
106
  *
52
- * @param from The {x,y} of the starting point
53
- * @param to The {x,y} of the ending point
54
- * @param steps The number of steps to take while moving
107
+ * @param from The starting {x, y} coordinates.
108
+ * @param to The ending {x, y} coordinates.
109
+ * @param steps The number of intermediate steps to take during the move. Defaults to 10.
55
110
  */
56
111
  static async moveMouse(from: Point, to: Point, steps = 10): Promise<void> {
57
- const dx = to.x - to.x
58
- const dy = to.y - to.y
112
+ const dx = to.x - from.x
113
+ const dy = to.y - from.y
59
114
  const ix = Math.round(dx / steps)
60
115
  const iy = Math.round(dy / steps)
61
- let currentX = to.x
62
- let currentY = to.y
116
+ let currentX = from.x
117
+ let currentY = from.y
63
118
 
64
119
  await sendMouse({ type: 'move', position: [from.x, from.y] })
65
120
  // await executeServerCommand('take-screenshot', { name: 'move-start' });
@@ -77,11 +132,13 @@ export class UiMock {
77
132
  }
78
133
 
79
134
  /**
80
- * Performs a drag and drop in the browser using the Playwright API.
135
+ * Performs a drag-and-drop operation from a source element to a target element.
136
+ * It simulates moving to the source, pressing the mouse down, moving to the target,
137
+ * and releasing the mouse.
81
138
  *
82
- * @param source The source element to drag
83
- * @param target The target where to drop the `source`
84
- * @param steps The number of mouse moves when dragging the `sources`
139
+ * @param source The HTMLElement to drag.
140
+ * @param target The HTMLElement to drop onto.
141
+ * @param steps The number of mouse moves to simulate during the drag. Defaults to 10.
85
142
  */
86
143
  static async dragAndDrop(source: HTMLElement, target: HTMLElement, steps = 10): Promise<void> {
87
144
  const from = UiMock.getMiddleOfElement(source)
@@ -96,6 +153,19 @@ export class UiMock {
96
153
  // await executeServerCommand('take-screenshot', { name: `after-up` });
97
154
  }
98
155
 
156
+ /**
157
+ * Creates a `DragEvent` for simulating file drags (e.g., for a file drop zone).
158
+ *
159
+ * @param type The type of the drag event (e.g., 'dragenter', 'dragover', 'drop').
160
+ * @param opts Options, including an optional `File` object to include in the event.
161
+ * If no file is provided, a default 'test.txt' file is created.
162
+ * @returns A new `DragEvent` instance.
163
+ *
164
+ * @example
165
+ * const myFile = new File(['(⌐□_□)'], 'chucknorris.png', { type: 'image/png' });
166
+ * const dropEvent = UiMock.getFileDragEvent('drop', { file: myFile });
167
+ * dropZone.dispatchEvent(dropEvent);
168
+ */
99
169
  static getFileDragEvent(type: string, opts: { file?: File } = {}): DragEvent {
100
170
  let file: File
101
171
  if (opts.file) {