@clarity-js/testing 0.0.0-stage → 1.0.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.
- package/README.md +39 -2
- package/index.d.ts +74 -0
- package/index.js +78 -0
- package/loader.js +20 -0
- package/package.json +24 -4
- package/queries.js +220 -0
- package/register.js +6 -0
- package/setup.js +11 -0
- package/user.js +162 -0
package/README.md
CHANGED
|
@@ -1,3 +1,40 @@
|
|
|
1
|
-
#
|
|
1
|
+
# @clarity-js/testing
|
|
2
2
|
|
|
3
|
-
|
|
3
|
+
Test [Clarity.js](https://clarity-js.com) components the way people use them: render a component into a
|
|
4
|
+
document, find things by role and name, by label, by text; click and type the way a person does; wait for what
|
|
5
|
+
comes later. Built on Clarity's own test kit, `@ozsarman/clarityjs/test`.
|
|
6
|
+
|
|
7
|
+
```sh
|
|
8
|
+
npm install --save-dev @clarity-js/testing jsdom
|
|
9
|
+
```
|
|
10
|
+
|
|
11
|
+
```js
|
|
12
|
+
// counter.test.js — node --import @clarity-js/testing/register --test
|
|
13
|
+
import test from 'node:test'
|
|
14
|
+
import assert from 'node:assert/strict'
|
|
15
|
+
import { render, screen, user } from '@clarity-js/testing'
|
|
16
|
+
import { Counter } from './Counter.clarity'
|
|
17
|
+
|
|
18
|
+
test('counts', async () => {
|
|
19
|
+
render(Counter, { start: 2 })
|
|
20
|
+
await user.click(screen.getByRole('button', { name: 'Add one' }))
|
|
21
|
+
assert.equal(screen.getByRole('status').textContent, '3')
|
|
22
|
+
})
|
|
23
|
+
```
|
|
24
|
+
|
|
25
|
+
- **`.clarity` files in Node.** `node --import @clarity-js/testing/register` compiles them as they are
|
|
26
|
+
imported (stylesheets and pictures they import become empty modules), installs jsdom when there is no
|
|
27
|
+
document yet, and cleans up after each test. Vitest with Clarity's Vite plugin needs no register:
|
|
28
|
+
`import '@clarity-js/testing/setup'` there gives the document and the cleanup. `compileComponent(source)`
|
|
29
|
+
compiles a small component inside the test.
|
|
30
|
+
- **Queries** in the manner of Testing Library, on `screen`, on what `render` returns, or `within(element)`:
|
|
31
|
+
`getBy`, `queryBy`, `getAllBy`, `queryAllBy`, `findBy`, `findAllBy` × `Role` (with `name`, `level`,
|
|
32
|
+
`checked`, `pressed`, `expanded`), `Text`, `LabelText`, `PlaceholderText`, `DisplayValue`, `AltText`,
|
|
33
|
+
`Title`, `TestId`. A query that finds nothing lists what has a role on the page.
|
|
34
|
+
- **`user`**: `click`, `dblClick`, `hover`, `type` (with `{Enter}`, `{Backspace}`, `{Tab}`…), `clear`,
|
|
35
|
+
`selectOptions`, `keyboard`, `tab`, `upload`. Each step lets the signals settle. Enter in a field presses
|
|
36
|
+
the form's submit button, Space on a button clicks it, disabled controls ignore a click.
|
|
37
|
+
- **`fireEvent`** for single low-level events, `waitFor`, `waitForElementToBeRemoved`, `prettyDOM`, and the
|
|
38
|
+
core kit's `act`, `spySignal`, `mockSignal`, `mockComponent`, snapshots.
|
|
39
|
+
|
|
40
|
+
Docs: <https://clarity-js.com/docs/packages#testing>. MIT.
|
package/index.d.ts
ADDED
|
@@ -0,0 +1,74 @@
|
|
|
1
|
+
// @clarity-js/testing — types
|
|
2
|
+
type Matcher = string | RegExp | ((text: string, element: Element) => boolean)
|
|
3
|
+
interface TextOptions { exact?: boolean; normalize?: boolean }
|
|
4
|
+
interface RoleOptions extends TextOptions { name?: Matcher; hidden?: boolean; level?: number; checked?: boolean; selected?: boolean; pressed?: boolean; expanded?: boolean }
|
|
5
|
+
interface WaitOptions { timeout?: number; interval?: number }
|
|
6
|
+
|
|
7
|
+
type Kinds = {
|
|
8
|
+
Role: [role: string, options?: RoleOptions]
|
|
9
|
+
Text: [text: Matcher, options?: TextOptions & { selector?: string; ignore?: string }]
|
|
10
|
+
LabelText: [text: Matcher, options?: TextOptions]
|
|
11
|
+
PlaceholderText: [text: Matcher, options?: TextOptions]
|
|
12
|
+
DisplayValue: [value: Matcher, options?: TextOptions]
|
|
13
|
+
AltText: [text: Matcher, options?: TextOptions]
|
|
14
|
+
Title: [text: Matcher, options?: TextOptions]
|
|
15
|
+
TestId: [id: Matcher, options?: TextOptions]
|
|
16
|
+
}
|
|
17
|
+
export type Queries = {
|
|
18
|
+
[K in keyof Kinds as `getBy${K}`]: (...args: Kinds[K]) => HTMLElement } & {
|
|
19
|
+
[K in keyof Kinds as `queryBy${K}`]: (...args: Kinds[K]) => HTMLElement | null } & {
|
|
20
|
+
[K in keyof Kinds as `getAllBy${K}`]: (...args: Kinds[K]) => HTMLElement[] } & {
|
|
21
|
+
[K in keyof Kinds as `queryAllBy${K}`]: (...args: Kinds[K]) => HTMLElement[] } & {
|
|
22
|
+
[K in keyof Kinds as `findBy${K}`]: (a: Kinds[K][0], b?: Kinds[K][1], wait?: WaitOptions) => Promise<HTMLElement> } & {
|
|
23
|
+
[K in keyof Kinds as `findAllBy${K}`]: (a: Kinds[K][0], b?: Kinds[K][1], wait?: WaitOptions) => Promise<HTMLElement[]> }
|
|
24
|
+
|
|
25
|
+
export interface RenderResult extends Queries {
|
|
26
|
+
container: HTMLElement
|
|
27
|
+
element: Node
|
|
28
|
+
unmount(): void
|
|
29
|
+
rerender(props?: Record<string, any>): RenderResult
|
|
30
|
+
debug(element?: Element): void
|
|
31
|
+
}
|
|
32
|
+
export function render(component: (props?: any) => any, props?: Record<string, any>, options?: { container?: HTMLElement }): RenderResult
|
|
33
|
+
export function cleanup(): void
|
|
34
|
+
export const screen: Queries & { debug(element?: Element): void }
|
|
35
|
+
export function within(element: Element): Queries
|
|
36
|
+
export function queriesFor(element: Element): Queries
|
|
37
|
+
export function waitFor<T>(callback: () => T | Promise<T>, options?: WaitOptions): Promise<T>
|
|
38
|
+
export function waitForElementToBeRemoved(callback: () => Element | Element[] | null, options?: WaitOptions): Promise<void>
|
|
39
|
+
export function configure(options: { asyncTimeout?: number; interval?: number }): void
|
|
40
|
+
export function getConfig(): { asyncTimeout: number; interval: number }
|
|
41
|
+
export function prettyDOM(element?: Element, max?: number): string
|
|
42
|
+
export function roleOf(element: Element): string | null
|
|
43
|
+
export function nameOf(element: Element): string
|
|
44
|
+
|
|
45
|
+
export interface User {
|
|
46
|
+
click(element: Element): Promise<void>
|
|
47
|
+
dblClick(element: Element): Promise<void>
|
|
48
|
+
hover(element: Element): Promise<void>
|
|
49
|
+
unhover(element: Element): Promise<void>
|
|
50
|
+
/** Keys in braces: {Enter}, {Backspace}, {Tab}, {Escape}, {ArrowLeft}… */
|
|
51
|
+
type(element: Element, text: string, options?: { click?: boolean }): Promise<void>
|
|
52
|
+
clear(element: Element): Promise<void>
|
|
53
|
+
selectOptions(select: Element, values: string | string[]): Promise<void>
|
|
54
|
+
keyboard(text: string): Promise<void>
|
|
55
|
+
tab(options?: { shift?: boolean }): Promise<void>
|
|
56
|
+
upload(input: Element, files: File | File[]): Promise<void>
|
|
57
|
+
}
|
|
58
|
+
export const user: User
|
|
59
|
+
export const userEvent: User
|
|
60
|
+
export const fireEvent: ((element: Element, event: Event) => boolean) & Record<'click' | 'dblClick' | 'mouseDown' | 'mouseUp' | 'mouseEnter' | 'mouseLeave' | 'pointerDown' | 'pointerUp' | 'focus' | 'blur' | 'keyDown' | 'keyUp' | 'input' | 'change' | 'submit' | 'reset' | 'scroll', (element: Element, init?: Record<string, any> & { target?: Record<string, any> }) => boolean>
|
|
61
|
+
|
|
62
|
+
export function compileComponent(source: string, options?: { filename?: string }): Promise<Record<string, any>>
|
|
63
|
+
export function setupDOM(html?: string, options?: Record<string, any>): Promise<void>
|
|
64
|
+
export function act(fn: () => any): Promise<void>
|
|
65
|
+
export function spySignal<T>(signal: { get(): T }): { values: T[]; stop(): void; [k: string]: any }
|
|
66
|
+
export function mockSignal<T>(initial: T): any
|
|
67
|
+
export function mockComponent(component: Function, implementation: Function): void
|
|
68
|
+
export function getMockedComponent(component: Function): Function | undefined
|
|
69
|
+
export function clearComponentMocks(): void
|
|
70
|
+
export function toMatchSnapshot(element: Element, name: string, options?: Record<string, any>): any
|
|
71
|
+
export function updateSnapshot(name: string, testFile?: string): void
|
|
72
|
+
export function pruneSnapshots(testFile?: string): void
|
|
73
|
+
export function toHTML(element: Element): string
|
|
74
|
+
export function getText(element: Element): string
|
package/index.js
ADDED
|
@@ -0,0 +1,78 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* @clarity-js/testing — test Clarity components the way people use them.
|
|
3
|
+
*
|
|
4
|
+
* Built on Clarity's own test kit (`@ozsarman/clarityjs/test`): render a component into a document, find
|
|
5
|
+
* things by role and name, by label, by text, act the way a person does (`user.click`, `user.type`), and wait
|
|
6
|
+
* for what comes later. In Node, `import '@clarity-js/testing/setup'` gives the tests a document (jsdom) and
|
|
7
|
+
* `node --import @clarity-js/testing/register` lets them import `.clarity` files directly.
|
|
8
|
+
*
|
|
9
|
+
* import '@clarity-js/testing/setup'
|
|
10
|
+
* import { render, screen, user } from '@clarity-js/testing'
|
|
11
|
+
* import { Counter } from './Counter.clarity'
|
|
12
|
+
*
|
|
13
|
+
* test('counts', async () => {
|
|
14
|
+
* render(Counter)
|
|
15
|
+
* await user.click(screen.getByRole('button', { name: 'Add one' }))
|
|
16
|
+
* assert.equal(screen.getByRole('status').textContent, '1')
|
|
17
|
+
* })
|
|
18
|
+
*/
|
|
19
|
+
|
|
20
|
+
import * as kit from '@ozsarman/clarityjs/test'
|
|
21
|
+
import { queriesFor, prettyDOM } from './queries.js'
|
|
22
|
+
|
|
23
|
+
export { queriesFor, within, screen, waitFor, waitForElementToBeRemoved, configure, getConfig, prettyDOM, roleOf, nameOf } from './queries.js'
|
|
24
|
+
export { user, fireEvent } from './user.js'
|
|
25
|
+
export { user as userEvent } from './user.js'
|
|
26
|
+
export const { setupDOM, act, spySignal, mockSignal, mockComponent, getMockedComponent, clearComponentMocks, toMatchSnapshot, updateSnapshot, pruneSnapshots, toHTML, getText } = kit
|
|
27
|
+
|
|
28
|
+
const mounted = new Set()
|
|
29
|
+
|
|
30
|
+
/**
|
|
31
|
+
* Render a component into the document and return the queries for it.
|
|
32
|
+
* @returns the queries (getByRole, …) bound to its container, plus container, element, unmount, rerender, debug
|
|
33
|
+
*/
|
|
34
|
+
export function render(Component, props = {}, options = {}) {
|
|
35
|
+
if (typeof document === 'undefined') {
|
|
36
|
+
throw new Error("[testing] there is no document: import '@clarity-js/testing/setup' first (or run in a browser, happy-dom or jsdom)")
|
|
37
|
+
}
|
|
38
|
+
const result = kit.render(Component, props, options)
|
|
39
|
+
const entry = { unmount: result.unmount }
|
|
40
|
+
mounted.add(entry)
|
|
41
|
+
const unmount = () => { if (mounted.delete(entry)) result.unmount() }
|
|
42
|
+
return {
|
|
43
|
+
container: result.container,
|
|
44
|
+
element: result.element,
|
|
45
|
+
unmount,
|
|
46
|
+
rerender(nextProps = props) {
|
|
47
|
+
unmount()
|
|
48
|
+
return render(Component, nextProps, { ...options, container: undefined })
|
|
49
|
+
},
|
|
50
|
+
debug(el = result.container) { console.log(prettyDOM(el)) },
|
|
51
|
+
...queriesFor(result.container),
|
|
52
|
+
}
|
|
53
|
+
}
|
|
54
|
+
|
|
55
|
+
/** Unmount everything rendered (afterEach). */
|
|
56
|
+
export function cleanup() {
|
|
57
|
+
for (const entry of [...mounted]) { mounted.delete(entry); try { entry.unmount() } catch { /* already gone */ } }
|
|
58
|
+
kit.cleanup()
|
|
59
|
+
}
|
|
60
|
+
|
|
61
|
+
/**
|
|
62
|
+
* Compile `.clarity` source in the test itself and import it — for a test of one small component.
|
|
63
|
+
* const { Hello } = await compileComponent(`component Hello(name) { render { <p>Hello { name }</p> } }`)
|
|
64
|
+
*/
|
|
65
|
+
export async function compileComponent(source, { filename = 'inline.clarity' } = {}) {
|
|
66
|
+
const { compile } = await import('@ozsarman/clarityjs')
|
|
67
|
+
const out = compile(source, { filename, runtimePath: '@ozsarman/clarityjs/runtime' })
|
|
68
|
+
const code = out.code ?? out
|
|
69
|
+
const url = 'data:text/javascript;base64,' + Buffer.from(rewriteForData(code)).toString('base64')
|
|
70
|
+
return import(url)
|
|
71
|
+
}
|
|
72
|
+
|
|
73
|
+
// A data: module cannot resolve bare names; point them at the packages this one can see.
|
|
74
|
+
function rewriteForData(code) {
|
|
75
|
+
return code.replace(/from\s+(['"])(@[^'"]+|[^./'"][^'"]*)\1/g, (m, q, spec) => {
|
|
76
|
+
try { return `from ${q}${import.meta.resolve(spec)}${q}` } catch { return m }
|
|
77
|
+
})
|
|
78
|
+
}
|
package/loader.js
ADDED
|
@@ -0,0 +1,20 @@
|
|
|
1
|
+
// Module hooks for Node: .clarity files are compiled as they are imported; stylesheets and pictures that a
|
|
2
|
+
// component imports become empty modules (there is nothing to paint in a test).
|
|
3
|
+
import { readFile } from 'node:fs/promises'
|
|
4
|
+
import { fileURLToPath } from 'node:url'
|
|
5
|
+
|
|
6
|
+
let compile
|
|
7
|
+
const ASSET = /\.(css|scss|sass|less|png|jpe?g|gif|webp|avif|svg|woff2?|ttf|otf|mp3|wav|ogg|glb|gltf|hdr|ktx2)(\?.*)?$/i
|
|
8
|
+
|
|
9
|
+
export async function load(url, context, next) {
|
|
10
|
+
if (url.endsWith('.clarity')) {
|
|
11
|
+
compile ??= (await import('@ozsarman/clarityjs')).compile
|
|
12
|
+
const source = await readFile(fileURLToPath(url), 'utf8')
|
|
13
|
+
const out = compile(source, { filename: fileURLToPath(url), runtimePath: '@ozsarman/clarityjs/runtime' })
|
|
14
|
+
return { format: 'module', source: out.code ?? out, shortCircuit: true }
|
|
15
|
+
}
|
|
16
|
+
if (ASSET.test(url) && url.startsWith('file:')) {
|
|
17
|
+
return { format: 'module', source: 'export default ' + JSON.stringify(url) + ';', shortCircuit: true }
|
|
18
|
+
}
|
|
19
|
+
return next(url, context)
|
|
20
|
+
}
|
package/package.json
CHANGED
|
@@ -1,6 +1,26 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@clarity-js/testing",
|
|
3
|
-
"version": "
|
|
4
|
-
"
|
|
5
|
-
"
|
|
6
|
-
|
|
3
|
+
"version": "1.0.1",
|
|
4
|
+
"description": "Test Clarity.js components the way people use them: render into a document, find things by role, name, label and text, click and type like a person, wait for what comes later. Import .clarity files straight into Node's test runner.",
|
|
5
|
+
"type": "module",
|
|
6
|
+
"main": "./index.js",
|
|
7
|
+
"module": "./index.js",
|
|
8
|
+
"types": "./index.d.ts",
|
|
9
|
+
"exports": {
|
|
10
|
+
".": { "types": "./index.d.ts", "import": "./index.js", "default": "./index.js" },
|
|
11
|
+
"./setup": { "types": "./index.d.ts", "import": "./setup.js", "default": "./setup.js" },
|
|
12
|
+
"./register": "./register.js",
|
|
13
|
+
"./loader": "./loader.js",
|
|
14
|
+
"./package.json": "./package.json"
|
|
15
|
+
},
|
|
16
|
+
"files": ["index.js", "queries.js", "user.js", "setup.js", "register.js", "loader.js", "index.d.ts", "README.md"],
|
|
17
|
+
"sideEffects": ["./setup.js", "./register.js"],
|
|
18
|
+
"keywords": ["clarity", "@ozsarman/clarityjs", "testing", "testing-library", "user-event", "jsdom", "node-test", "vitest"],
|
|
19
|
+
"author": "Özdemir Şarman",
|
|
20
|
+
"license": "MIT",
|
|
21
|
+
"peerDependencies": { "@ozsarman/clarityjs": ">=1.10.0", "jsdom": ">=22.0.0" },
|
|
22
|
+
"peerDependenciesMeta": { "jsdom": { "optional": true } },
|
|
23
|
+
"homepage": "https://clarity-js.com/docs/packages#testing",
|
|
24
|
+
"repository": { "type": "git", "url": "git+https://github.com/ozdemirsarman/clarity.js.git", "directory": "packages/clarity-testing" },
|
|
25
|
+
"engines": { "node": ">=20.6.0" }
|
|
26
|
+
}
|
package/queries.js
ADDED
|
@@ -0,0 +1,220 @@
|
|
|
1
|
+
// Queries in the manner of Testing Library: find what a person finds — by role and accessible name, by
|
|
2
|
+
// label, by text — and fail with a message that shows what was there instead.
|
|
3
|
+
|
|
4
|
+
const IMPLICIT = {
|
|
5
|
+
a: (el) => (el.hasAttribute('href') ? 'link' : null),
|
|
6
|
+
area: (el) => (el.hasAttribute('href') ? 'link' : null),
|
|
7
|
+
article: () => 'article', aside: () => 'complementary', button: () => 'button', dialog: () => 'dialog',
|
|
8
|
+
details: () => 'group', fieldset: () => 'group', figure: () => 'figure', footer: () => 'contentinfo',
|
|
9
|
+
form: () => 'form', h1: () => 'heading', h2: () => 'heading', h3: () => 'heading', h4: () => 'heading',
|
|
10
|
+
h5: () => 'heading', h6: () => 'heading', header: () => 'banner', hr: () => 'separator', img: (el) => (el.getAttribute('alt') === '' ? 'presentation' : 'img'),
|
|
11
|
+
li: () => 'listitem', main: () => 'main', math: () => 'math', menu: () => 'list', nav: () => 'navigation', ol: () => 'list',
|
|
12
|
+
optgroup: () => 'group', option: () => 'option', output: () => 'status', progress: () => 'progressbar',
|
|
13
|
+
section: (el) => (el.hasAttribute('aria-label') || el.hasAttribute('aria-labelledby') ? 'region' : null),
|
|
14
|
+
select: (el) => (el.multiple || Number(el.getAttribute('size')) > 1 ? 'listbox' : 'combobox'),
|
|
15
|
+
summary: () => 'button', table: () => 'table', tbody: () => 'rowgroup', thead: () => 'rowgroup', tfoot: () => 'rowgroup',
|
|
16
|
+
td: () => 'cell', th: (el) => (el.getAttribute('scope') === 'row' ? 'rowheader' : 'columnheader'), tr: () => 'row',
|
|
17
|
+
textarea: () => 'textbox', ul: () => 'list', meter: () => 'meter',
|
|
18
|
+
input: (el) => {
|
|
19
|
+
const type = (el.getAttribute('type') || 'text').toLowerCase()
|
|
20
|
+
if (type === 'checkbox') return 'checkbox'
|
|
21
|
+
if (type === 'radio') return 'radio'
|
|
22
|
+
if (type === 'range') return 'slider'
|
|
23
|
+
if (type === 'number') return 'spinbutton'
|
|
24
|
+
if (type === 'search') return el.hasAttribute('list') ? 'combobox' : 'searchbox'
|
|
25
|
+
if (['button', 'submit', 'reset', 'image'].includes(type)) return 'button'
|
|
26
|
+
if (type === 'hidden') return null
|
|
27
|
+
return el.hasAttribute('list') ? 'combobox' : 'textbox'
|
|
28
|
+
},
|
|
29
|
+
}
|
|
30
|
+
|
|
31
|
+
/** The element's role: its role attribute, or the one its tag implies. */
|
|
32
|
+
export function roleOf(el) {
|
|
33
|
+
const explicit = el.getAttribute?.('role')
|
|
34
|
+
if (explicit) return explicit.trim().split(/\s+/)[0]
|
|
35
|
+
const f = IMPLICIT[el.localName]
|
|
36
|
+
return f ? f(el) : null
|
|
37
|
+
}
|
|
38
|
+
|
|
39
|
+
function isHidden(el) {
|
|
40
|
+
for (let n = el; n && n.nodeType === 1; n = n.parentElement) {
|
|
41
|
+
if (n.hidden || n.getAttribute('aria-hidden') === 'true') return true
|
|
42
|
+
const style = n.ownerDocument?.defaultView?.getComputedStyle?.(n)
|
|
43
|
+
if (style && (style.display === 'none' || style.visibility === 'hidden')) return true
|
|
44
|
+
}
|
|
45
|
+
return false
|
|
46
|
+
}
|
|
47
|
+
|
|
48
|
+
function textOf(el) { return (el.textContent ?? '').replace(/\s+/g, ' ').trim() }
|
|
49
|
+
|
|
50
|
+
/** The accessible name, by the rules that matter in tests: aria-labelledby, aria-label, label, alt, title, text. */
|
|
51
|
+
export function nameOf(el) {
|
|
52
|
+
const doc = el.ownerDocument
|
|
53
|
+
const by = el.getAttribute('aria-labelledby')
|
|
54
|
+
if (by) return by.split(/\s+/).map((id) => doc.getElementById(id)).filter(Boolean).map(textOf).join(' ').trim()
|
|
55
|
+
const label = el.getAttribute('aria-label')
|
|
56
|
+
if (label?.trim()) return label.trim()
|
|
57
|
+
if (['input', 'select', 'textarea', 'meter', 'progress', 'output'].includes(el.localName)) {
|
|
58
|
+
const labels = el.labels ? [...el.labels] : (el.id ? [...doc.querySelectorAll(`label[for="${CSS.escape?.(el.id) ?? el.id}"]`)] : [])
|
|
59
|
+
if (!labels.length) { const wrap = el.closest('label'); if (wrap) labels.push(wrap) }
|
|
60
|
+
if (labels.length) return labels.map((l) => textOf(l)).join(' ').trim()
|
|
61
|
+
const type = (el.getAttribute('type') || '').toLowerCase()
|
|
62
|
+
if (['button', 'submit', 'reset'].includes(type)) return el.value || { submit: 'Submit', reset: 'Reset' }[type] || ''
|
|
63
|
+
if (type === 'image') return el.getAttribute('alt') || ''
|
|
64
|
+
return el.getAttribute('title') || el.getAttribute('placeholder') || ''
|
|
65
|
+
}
|
|
66
|
+
if (el.localName === 'img' || el.localName === 'area') return el.getAttribute('alt') || el.getAttribute('title') || ''
|
|
67
|
+
if (el.localName === 'fieldset') { const legend = el.querySelector(':scope > legend'); if (legend) return textOf(legend) }
|
|
68
|
+
if (el.localName === 'table') { const caption = el.querySelector(':scope > caption'); if (caption) return textOf(caption) }
|
|
69
|
+
const role = roleOf(el)
|
|
70
|
+
const fromContent = ['button', 'link', 'heading', 'tab', 'menuitem', 'option', 'cell', 'columnheader', 'rowheader', 'row', 'listitem', 'checkbox', 'radio', 'switch', 'treeitem', 'tooltip']
|
|
71
|
+
if (fromContent.includes(role) || !role) return textOf(el) || el.getAttribute('title') || ''
|
|
72
|
+
return el.getAttribute('title') || ''
|
|
73
|
+
}
|
|
74
|
+
|
|
75
|
+
function matcher(expected, { exact = true, normalize = true } = {}) {
|
|
76
|
+
const norm = (s) => (normalize ? String(s ?? '').replace(/\s+/g, ' ').trim() : String(s ?? ''))
|
|
77
|
+
if (expected instanceof RegExp) return (s) => expected.test(norm(s))
|
|
78
|
+
if (typeof expected === 'function') return (s, el) => expected(norm(s), el)
|
|
79
|
+
const want = norm(expected)
|
|
80
|
+
return exact ? (s) => norm(s) === want : (s) => norm(s).toLowerCase().includes(want.toLowerCase())
|
|
81
|
+
}
|
|
82
|
+
|
|
83
|
+
const all = (root) => [...root.querySelectorAll('*')]
|
|
84
|
+
|
|
85
|
+
const FINDERS = {
|
|
86
|
+
Role(root, role, { name, hidden = false, level, checked, selected, pressed, expanded, ...rest } = {}) {
|
|
87
|
+
const nameOk = name === undefined ? () => true : matcher(name, rest)
|
|
88
|
+
return all(root).filter((el) => {
|
|
89
|
+
if (roleOf(el) !== role) return false
|
|
90
|
+
if (!hidden && isHidden(el)) return false
|
|
91
|
+
if (level !== undefined && Number(el.getAttribute('aria-level') ?? el.localName.slice(1)) !== level) return false
|
|
92
|
+
if (checked !== undefined && (el.checked ?? el.getAttribute('aria-checked') === 'true') !== checked) return false
|
|
93
|
+
if (selected !== undefined && (el.selected ?? el.getAttribute('aria-selected') === 'true') !== selected) return false
|
|
94
|
+
if (pressed !== undefined && (el.getAttribute('aria-pressed') === 'true') !== pressed) return false
|
|
95
|
+
if (expanded !== undefined && (el.getAttribute('aria-expanded') === 'true') !== expanded) return false
|
|
96
|
+
return nameOk(nameOf(el), el)
|
|
97
|
+
})
|
|
98
|
+
},
|
|
99
|
+
Text(root, text, { selector = '*', ignore = 'script, style', ...rest } = {}) {
|
|
100
|
+
const ok = matcher(text, rest)
|
|
101
|
+
// the elements whose own text (their text nodes) matches — not every ancestor of them
|
|
102
|
+
return all(root).filter((el) => el.matches(selector) && !el.matches(ignore) &&
|
|
103
|
+
ok([...el.childNodes].filter((n) => n.nodeType === 3).map((n) => n.textContent).join(''), el))
|
|
104
|
+
},
|
|
105
|
+
LabelText(root, text, opts = {}) {
|
|
106
|
+
const ok = matcher(text, opts)
|
|
107
|
+
const found = new Set()
|
|
108
|
+
for (const label of root.querySelectorAll('label')) {
|
|
109
|
+
if (!ok(textOf(label), label)) continue
|
|
110
|
+
const control = label.control ?? (label.htmlFor ? label.ownerDocument.getElementById(label.htmlFor) : label.querySelector('input, select, textarea, button, meter, output, progress'))
|
|
111
|
+
if (control) found.add(control)
|
|
112
|
+
}
|
|
113
|
+
for (const el of root.querySelectorAll('[aria-label], [aria-labelledby]')) if (ok(nameOf(el), el)) found.add(el)
|
|
114
|
+
return [...found]
|
|
115
|
+
},
|
|
116
|
+
PlaceholderText(root, text, opts) { const ok = matcher(text, opts); return [...root.querySelectorAll('[placeholder]')].filter((el) => ok(el.getAttribute('placeholder'), el)) },
|
|
117
|
+
DisplayValue(root, value, opts) {
|
|
118
|
+
const ok = matcher(value, opts)
|
|
119
|
+
return [...root.querySelectorAll('input, select, textarea')].filter((el) =>
|
|
120
|
+
el.localName === 'select' ? [...el.selectedOptions].some((o) => ok(o.textContent, el)) : ok(el.value, el))
|
|
121
|
+
},
|
|
122
|
+
AltText(root, text, opts) { const ok = matcher(text, opts); return [...root.querySelectorAll('[alt]')].filter((el) => ok(el.getAttribute('alt'), el)) },
|
|
123
|
+
Title(root, text, opts) { const ok = matcher(text, opts); return [...root.querySelectorAll('[title], svg > title')].filter((el) => ok(el.localName === 'title' ? el.textContent : el.getAttribute('title'), el)) },
|
|
124
|
+
TestId(root, id, opts) { const ok = matcher(id, opts); return [...root.querySelectorAll('[data-testid]')].filter((el) => ok(el.getAttribute('data-testid'), el)) },
|
|
125
|
+
}
|
|
126
|
+
|
|
127
|
+
let config = { asyncTimeout: 1000, interval: 20 }
|
|
128
|
+
/** configure({ asyncTimeout, interval }) for the findBy* queries and waitFor. */
|
|
129
|
+
export function configure(next) { config = { ...config, ...next } }
|
|
130
|
+
export function getConfig() { return config }
|
|
131
|
+
|
|
132
|
+
function describeWhatIsThere(root) {
|
|
133
|
+
const roles = new Map()
|
|
134
|
+
for (const el of all(root)) {
|
|
135
|
+
if (isHidden(el)) continue
|
|
136
|
+
const role = roleOf(el)
|
|
137
|
+
if (!role || ['generic', 'presentation', 'none'].includes(role)) continue
|
|
138
|
+
if (!roles.has(role)) roles.set(role, [])
|
|
139
|
+
roles.get(role).push(nameOf(el))
|
|
140
|
+
}
|
|
141
|
+
if (!roles.size) return ' (nothing with a role)'
|
|
142
|
+
return [...roles].map(([role, names]) => ` ${role}: ${names.slice(0, 6).map((n) => JSON.stringify(n)).join(', ')}${names.length > 6 ? ', …' : ''}`).join('\n')
|
|
143
|
+
}
|
|
144
|
+
|
|
145
|
+
function failure(kind, what, opts, root, many) {
|
|
146
|
+
const options = opts && Object.keys(opts).length ? ' ' + JSON.stringify(opts, (k, v) => (v instanceof RegExp ? String(v) : v)) : ''
|
|
147
|
+
const message = many
|
|
148
|
+
? `Found ${many} elements by ${kind} ${JSON.stringify(String(what))}${options}, expected one. Use getAllBy${kind} for many.`
|
|
149
|
+
: `Found no element by ${kind} ${JSON.stringify(String(what))}${options}.\nThis is what has a role here:\n${describeWhatIsThere(root)}`
|
|
150
|
+
const err = new Error(message)
|
|
151
|
+
err.name = 'TestingError'
|
|
152
|
+
return err
|
|
153
|
+
}
|
|
154
|
+
|
|
155
|
+
export async function waitFor(callback, { timeout = config.asyncTimeout, interval = config.interval } = {}) {
|
|
156
|
+
const start = Date.now()
|
|
157
|
+
let last
|
|
158
|
+
for (;;) {
|
|
159
|
+
try { return await callback() } catch (err) { last = err }
|
|
160
|
+
if (Date.now() - start >= timeout) {
|
|
161
|
+
last.message = `waitFor gave up after ${timeout} ms.\n${last.message}`
|
|
162
|
+
throw last
|
|
163
|
+
}
|
|
164
|
+
await new Promise((r) => setTimeout(r, interval))
|
|
165
|
+
}
|
|
166
|
+
}
|
|
167
|
+
|
|
168
|
+
/** Resolves once `callback` throws or finds nothing: the element has gone. */
|
|
169
|
+
export async function waitForElementToBeRemoved(callback, options) {
|
|
170
|
+
const present = () => { try { const r = callback(); return Array.isArray(r) ? r.length > 0 : !!r } catch { return false } }
|
|
171
|
+
if (!present()) throw new Error('waitForElementToBeRemoved: the element is not there to begin with')
|
|
172
|
+
return waitFor(() => { if (present()) throw new Error('The element is still there') }, options)
|
|
173
|
+
}
|
|
174
|
+
|
|
175
|
+
/** Every query, bound to a root element: getBy*, queryBy*, getAllBy*, queryAllBy*, findBy*, findAllBy*. */
|
|
176
|
+
export function queriesFor(root) {
|
|
177
|
+
const q = {}
|
|
178
|
+
for (const [kind, find] of Object.entries(FINDERS)) {
|
|
179
|
+
q['queryAllBy' + kind] = (what, opts) => find(root, what, opts)
|
|
180
|
+
q['getAllBy' + kind] = (what, opts) => { const r = find(root, what, opts); if (!r.length) throw failure(kind, what, opts, root); return r }
|
|
181
|
+
q['queryBy' + kind] = (what, opts) => { const r = find(root, what, opts); if (r.length > 1) throw failure(kind, what, opts, root, r.length); return r[0] ?? null }
|
|
182
|
+
q['getBy' + kind] = (what, opts) => { const r = find(root, what, opts); if (r.length !== 1) throw failure(kind, what, opts, root, r.length > 1 ? r.length : 0); return r[0] }
|
|
183
|
+
q['findBy' + kind] = (what, opts, waitOpts) => waitFor(() => q['getBy' + kind](what, opts), waitOpts)
|
|
184
|
+
q['findAllBy' + kind] = (what, opts, waitOpts) => waitFor(() => q['getAllBy' + kind](what, opts), waitOpts)
|
|
185
|
+
}
|
|
186
|
+
q.getByPlaceholder = q.getByPlaceholderText // 0.x name
|
|
187
|
+
q.queryByPlaceholder = q.queryByPlaceholderText
|
|
188
|
+
return q
|
|
189
|
+
}
|
|
190
|
+
|
|
191
|
+
/** Queries limited to one element: within(dialog).getByRole('button', { name: 'Close' }). */
|
|
192
|
+
export const within = (el) => queriesFor(el)
|
|
193
|
+
|
|
194
|
+
/** Queries on the whole document. */
|
|
195
|
+
export const screen = new Proxy({}, {
|
|
196
|
+
get(_, key) {
|
|
197
|
+
if (key === 'debug') return (el = document.body) => console.log(prettyDOM(el))
|
|
198
|
+
const q = queriesFor(document.body)
|
|
199
|
+
if (key in q) return q[key]
|
|
200
|
+
return undefined
|
|
201
|
+
},
|
|
202
|
+
})
|
|
203
|
+
|
|
204
|
+
/** The element's markup, indented, for a failing test's log. */
|
|
205
|
+
export function prettyDOM(el = document.body, max = 7000) {
|
|
206
|
+
const lines = []
|
|
207
|
+
const walk = (n, depth) => {
|
|
208
|
+
const pad = ' '.repeat(depth)
|
|
209
|
+
if (n.nodeType === 3) { const t = n.textContent.trim(); if (t) lines.push(pad + t); return }
|
|
210
|
+
if (n.nodeType !== 1) return
|
|
211
|
+
const attrs = [...n.attributes].map((a) => ` ${a.name}="${a.value}"`).join('')
|
|
212
|
+
if (!n.childNodes.length) { lines.push(`${pad}<${n.localName}${attrs} />`); return }
|
|
213
|
+
lines.push(`${pad}<${n.localName}${attrs}>`)
|
|
214
|
+
for (const c of n.childNodes) walk(c, depth + 1)
|
|
215
|
+
lines.push(`${pad}</${n.localName}>`)
|
|
216
|
+
}
|
|
217
|
+
walk(el, 0)
|
|
218
|
+
const out = lines.join('\n')
|
|
219
|
+
return out.length > max ? out.slice(0, max) + '\n…' : out
|
|
220
|
+
}
|
package/register.js
ADDED
|
@@ -0,0 +1,6 @@
|
|
|
1
|
+
// node --import @clarity-js/testing/register --test
|
|
2
|
+
// Lets Node import .clarity files (each is compiled by Clarity's own compiler as it is loaded), and gives the
|
|
3
|
+
// tests a document (jsdom) with cleanup after each test — everything `node --test` needs.
|
|
4
|
+
import { register } from 'node:module'
|
|
5
|
+
register('./loader.js', import.meta.url)
|
|
6
|
+
await import('./setup.js')
|
package/setup.js
ADDED
|
@@ -0,0 +1,11 @@
|
|
|
1
|
+
// import '@clarity-js/testing/setup' — a document for the tests (jsdom, if there is none yet), and cleanup
|
|
2
|
+
// after each test: with the runner's global afterEach (Vitest with globals, Jest), or node:test's under
|
|
3
|
+
// `node --test`.
|
|
4
|
+
import { setupDOM, cleanup } from './index.js'
|
|
5
|
+
|
|
6
|
+
if (typeof document === 'undefined') await setupDOM()
|
|
7
|
+
if (typeof globalThis.afterEach === 'function') globalThis.afterEach(cleanup)
|
|
8
|
+
else if (typeof process !== 'undefined' && process.env?.NODE_TEST_CONTEXT) {
|
|
9
|
+
const { afterEach } = await import('node:test')
|
|
10
|
+
afterEach(cleanup)
|
|
11
|
+
}
|
package/user.js
ADDED
|
@@ -0,0 +1,162 @@
|
|
|
1
|
+
// Events the way a person makes them: a click is a pointer down, a focus, a pointer up and a click; typing
|
|
2
|
+
// is a key down, an input and a key up for every character. After each step the signals settle.
|
|
3
|
+
|
|
4
|
+
const settle = () => new Promise((r) => setTimeout(r, 0))
|
|
5
|
+
const win = (el) => el.ownerDocument.defaultView
|
|
6
|
+
|
|
7
|
+
function fire(el, type, Ctor = 'Event', init = {}) {
|
|
8
|
+
const C = win(el)[Ctor] ?? win(el).Event
|
|
9
|
+
const event = new C(type, { bubbles: true, cancelable: true, composed: true, ...init })
|
|
10
|
+
return el.dispatchEvent(event)
|
|
11
|
+
}
|
|
12
|
+
|
|
13
|
+
const FOCUSABLE = 'a[href], area[href], button, input:not([type=hidden]), select, textarea, summary, iframe, [tabindex], [contenteditable=""], [contenteditable=true]'
|
|
14
|
+
function isDisabled(el) { return !!el.closest?.('[disabled], fieldset[disabled]') && el.matches?.('button, input, select, textarea, fieldset *') }
|
|
15
|
+
function focusable(el) { return el.matches?.(FOCUSABLE) && !isDisabled(el) && el.getAttribute('tabindex') !== '-1' }
|
|
16
|
+
|
|
17
|
+
function focus(el) {
|
|
18
|
+
const doc = el.ownerDocument
|
|
19
|
+
const target = focusable(el) ? el : el.closest?.(FOCUSABLE)
|
|
20
|
+
if (!target || doc.activeElement === target) return
|
|
21
|
+
const previous = doc.activeElement
|
|
22
|
+
if (previous && previous !== doc.body) { previous.blur?.(); }
|
|
23
|
+
target.focus?.()
|
|
24
|
+
}
|
|
25
|
+
|
|
26
|
+
function setValue(el, value) {
|
|
27
|
+
// bypass a framework's own setter, the way a browser does when a person types
|
|
28
|
+
const proto = Object.getPrototypeOf(el)
|
|
29
|
+
const desc = Object.getOwnPropertyDescriptor(proto, 'value')
|
|
30
|
+
if (desc?.set) desc.set.call(el, value); else el.value = value
|
|
31
|
+
}
|
|
32
|
+
|
|
33
|
+
const KEYS = { Enter: '\n', Tab: '\t', Space: ' ', Escape: '', Backspace: '', Delete: '', ArrowLeft: '', ArrowRight: '', ArrowUp: '', ArrowDown: '', Home: '', End: '', PageUp: '', PageDown: '' }
|
|
34
|
+
|
|
35
|
+
function parseKeys(text) {
|
|
36
|
+
const out = []
|
|
37
|
+
for (let i = 0; i < text.length; i++) {
|
|
38
|
+
if (text[i] === '{' && text[i + 1] !== '{') {
|
|
39
|
+
const end = text.indexOf('}', i)
|
|
40
|
+
if (end > i) { out.push({ key: text.slice(i + 1, end) }); i = end; continue }
|
|
41
|
+
}
|
|
42
|
+
if (text[i] === '{' && text[i + 1] === '{') i++
|
|
43
|
+
out.push({ key: text[i], char: text[i] })
|
|
44
|
+
}
|
|
45
|
+
return out
|
|
46
|
+
}
|
|
47
|
+
|
|
48
|
+
function isTextField(el) {
|
|
49
|
+
return el.localName === 'textarea' || (el.localName === 'input' && !['checkbox', 'radio', 'button', 'submit', 'reset', 'range', 'color', 'file', 'image'].includes((el.type || 'text').toLowerCase())) || el.isContentEditable
|
|
50
|
+
}
|
|
51
|
+
|
|
52
|
+
async function press(el, { key, char }) {
|
|
53
|
+
const code = key.length === 1 ? (/\d/.test(key) ? 'Digit' + key : /[a-z]/i.test(key) ? 'Key' + key.toUpperCase() : key) : key
|
|
54
|
+
const go = fire(el, 'keydown', 'KeyboardEvent', { key, code })
|
|
55
|
+
if (go && char !== undefined) fire(el, 'keypress', 'KeyboardEvent', { key, code, charCode: char.charCodeAt(0) })
|
|
56
|
+
if (go) {
|
|
57
|
+
if (char !== undefined && isTextField(el) && !el.readOnly) {
|
|
58
|
+
if (el.isContentEditable) el.textContent += char
|
|
59
|
+
else setValue(el, (el.value ?? '') + char)
|
|
60
|
+
fire(el, 'input', 'InputEvent', { data: char, inputType: 'insertText' })
|
|
61
|
+
} else if (key === 'Backspace' && isTextField(el) && !el.readOnly) {
|
|
62
|
+
setValue(el, String(el.value ?? '').slice(0, -1))
|
|
63
|
+
fire(el, 'input', 'InputEvent', { inputType: 'deleteContentBackward' })
|
|
64
|
+
} else if (key === 'Enter') {
|
|
65
|
+
if (el.localName === 'input' && el.form) {
|
|
66
|
+
const submitter = el.form.querySelector('button:not([type]), button[type=submit], input[type=submit]')
|
|
67
|
+
if (submitter && !isDisabled(submitter)) await click(submitter)
|
|
68
|
+
else el.form.requestSubmit?.() ?? fire(el.form, 'submit')
|
|
69
|
+
} else if (el.localName === 'button' || el.localName === 'a') await click(el)
|
|
70
|
+
else if (el.localName === 'textarea') { setValue(el, el.value + '\n'); fire(el, 'input', 'InputEvent', { data: '\n', inputType: 'insertLineBreak' }) }
|
|
71
|
+
} else if (key === ' ' && (el.localName === 'button' || (el.localName === 'input' && ['checkbox', 'radio', 'button', 'submit'].includes(el.type)))) {
|
|
72
|
+
await click(el)
|
|
73
|
+
} else if (key === 'Tab') {
|
|
74
|
+
tab(el.ownerDocument)
|
|
75
|
+
}
|
|
76
|
+
}
|
|
77
|
+
fire(el, 'keyup', 'KeyboardEvent', { key, code })
|
|
78
|
+
}
|
|
79
|
+
|
|
80
|
+
function tabbables(doc) {
|
|
81
|
+
return [...doc.querySelectorAll(FOCUSABLE)].filter((el) => focusable(el) && Number(el.getAttribute('tabindex') ?? 0) >= 0 && !el.closest('[hidden], [inert]'))
|
|
82
|
+
}
|
|
83
|
+
|
|
84
|
+
function tab(doc, { shift = false } = {}) {
|
|
85
|
+
const list = tabbables(doc)
|
|
86
|
+
if (!list.length) return
|
|
87
|
+
const i = list.indexOf(doc.activeElement)
|
|
88
|
+
const next = shift ? list[(i <= 0 ? list.length : i) - 1] : list[(i + 1) % list.length]
|
|
89
|
+
focus(next)
|
|
90
|
+
}
|
|
91
|
+
|
|
92
|
+
async function click(el, { button = 0 } = {}) {
|
|
93
|
+
if (!el) throw new Error('user.click: no element')
|
|
94
|
+
if (isDisabled(el)) return
|
|
95
|
+
fire(el, 'pointerdown', 'PointerEvent', { button, pointerType: 'mouse' })
|
|
96
|
+
fire(el, 'mousedown', 'MouseEvent', { button })
|
|
97
|
+
focus(el)
|
|
98
|
+
fire(el, 'pointerup', 'PointerEvent', { button, pointerType: 'mouse' })
|
|
99
|
+
fire(el, 'mouseup', 'MouseEvent', { button })
|
|
100
|
+
el.click ? el.click() : fire(el, 'click', 'MouseEvent', { button })
|
|
101
|
+
await settle()
|
|
102
|
+
}
|
|
103
|
+
|
|
104
|
+
export const user = {
|
|
105
|
+
click,
|
|
106
|
+
async dblClick(el) { await click(el); await click(el); fire(el, 'dblclick', 'MouseEvent'); await settle() },
|
|
107
|
+
async hover(el) { for (const t of ['pointerover', 'pointerenter', 'mouseover', 'mouseenter']) fire(el, t, t.startsWith('pointer') ? 'PointerEvent' : 'MouseEvent', { bubbles: !t.endsWith('enter') }); await settle() },
|
|
108
|
+
async unhover(el) { for (const t of ['pointerout', 'pointerleave', 'mouseout', 'mouseleave']) fire(el, t, t.startsWith('pointer') ? 'PointerEvent' : 'MouseEvent', { bubbles: !t.endsWith('leave') }); await settle() },
|
|
109
|
+
/** Click into the field, then type: `{Enter}`, `{Backspace}`, `{Tab}` and other keys in braces. */
|
|
110
|
+
async type(el, text, { click: first = true } = {}) {
|
|
111
|
+
if (isDisabled(el)) return
|
|
112
|
+
if (first) await click(el); else focus(el)
|
|
113
|
+
for (const k of parseKeys(String(text))) { await press(el.ownerDocument.activeElement ?? el, k); }
|
|
114
|
+
await settle()
|
|
115
|
+
},
|
|
116
|
+
async clear(el) {
|
|
117
|
+
focus(el)
|
|
118
|
+
setValue(el, '')
|
|
119
|
+
fire(el, 'input', 'InputEvent', { inputType: 'deleteContentBackward' })
|
|
120
|
+
await settle()
|
|
121
|
+
},
|
|
122
|
+
/** Choose options of a select by value or by label. */
|
|
123
|
+
async selectOptions(select, values) {
|
|
124
|
+
const wanted = [].concat(values)
|
|
125
|
+
focus(select)
|
|
126
|
+
for (const option of select.options) {
|
|
127
|
+
const hit = wanted.includes(option.value) || wanted.includes(option.textContent.trim()) || wanted.includes(option)
|
|
128
|
+
if (select.multiple) option.selected = hit ? true : option.selected
|
|
129
|
+
else if (hit) option.selected = true
|
|
130
|
+
}
|
|
131
|
+
fire(select, 'input'); fire(select, 'change')
|
|
132
|
+
await settle()
|
|
133
|
+
},
|
|
134
|
+
/** Keys on the focused element: user.keyboard('{Escape}'). */
|
|
135
|
+
async keyboard(text) {
|
|
136
|
+
const doc = globalThis.document
|
|
137
|
+
for (const k of parseKeys(String(text))) await press(doc.activeElement ?? doc.body, k)
|
|
138
|
+
await settle()
|
|
139
|
+
},
|
|
140
|
+
async tab({ shift = false } = {}) { tab(globalThis.document, { shift }); await settle() },
|
|
141
|
+
async upload(input, files) {
|
|
142
|
+
const list = [].concat(files)
|
|
143
|
+
Object.defineProperty(input, 'files', { value: Object.assign(list, { item: (i) => list[i] }), configurable: true })
|
|
144
|
+
fire(input, 'input'); fire(input, 'change')
|
|
145
|
+
await settle()
|
|
146
|
+
},
|
|
147
|
+
}
|
|
148
|
+
|
|
149
|
+
/** Low-level events: fireEvent.click(el), fireEvent.input(el, { target: { value: 'x' } }), fireEvent(el, event). */
|
|
150
|
+
export const fireEvent = Object.assign(
|
|
151
|
+
(el, event) => el.dispatchEvent(event),
|
|
152
|
+
Object.fromEntries([
|
|
153
|
+
['click', 'MouseEvent'], ['dblClick', 'MouseEvent', 'dblclick'], ['mouseDown', 'MouseEvent', 'mousedown'], ['mouseUp', 'MouseEvent', 'mouseup'],
|
|
154
|
+
['mouseEnter', 'MouseEvent', 'mouseenter'], ['mouseLeave', 'MouseEvent', 'mouseleave'], ['pointerDown', 'PointerEvent', 'pointerdown'], ['pointerUp', 'PointerEvent', 'pointerup'],
|
|
155
|
+
['focus', 'FocusEvent'], ['blur', 'FocusEvent'], ['keyDown', 'KeyboardEvent', 'keydown'], ['keyUp', 'KeyboardEvent', 'keyup'],
|
|
156
|
+
['input', 'InputEvent'], ['change', 'Event'], ['submit', 'Event'], ['reset', 'Event'], ['scroll', 'Event'],
|
|
157
|
+
].map(([name, Ctor, type = name]) => [name, (el, init = {}) => {
|
|
158
|
+
if (init.target) for (const [k, v] of Object.entries(init.target)) { if (k === 'value') setValue(el, v); else el[k] = v }
|
|
159
|
+
const { target, ...rest } = init
|
|
160
|
+
return fire(el, type, Ctor, rest)
|
|
161
|
+
}])),
|
|
162
|
+
)
|