From b6eb19798283fcaa32281246bf47c6827775df55 Mon Sep 17 00:00:00 2001 From: nichoth Date: Fri, 27 Sep 2024 12:30:05 -0700 Subject: [PATCH] better click function --- src/index.ts | 33 ++++++++++++++++++++------------- test/index.ts | 2 +- 2 files changed, 21 insertions(+), 14 deletions(-) diff --git a/src/index.ts b/src/index.ts index 6c25cfd..5b3d92e 100644 --- a/src/index.ts +++ b/src/index.ts @@ -277,19 +277,26 @@ export function waitFor ( } /** - * Click the given element. - * - * @param {Element} element - */ -export function click (element:Element) { - event({ - event: new window.MouseEvent('click', { - bubbles: true, - cancelable: true, - button: 0 - }), - element - }) + * Dispatch the `click`` method on an element specified by selector. + * + * @param {string|HTMLElement|Element} selector - A CSS selector string, or + * an instance of an HTMLElement. + * @returns {Promise} + * + * @example + * ```js + * await t.click('.class button', 'Click a button') + * ``` + */ +export async function click (selector:HTMLElement|Element|string):Promise { + const el = toElement(selector) as HTMLElement + + if (globalThis.HTMLElement && !(el instanceof globalThis.HTMLElement)) { + throw new Error('selector needs to be instance of HTMLElement or resolve to one') + } + + el!.click() + await requestAnimationFrame() } /** diff --git a/test/index.ts b/test/index.ts index 8d48420..87fe288 100644 --- a/test/index.ts +++ b/test/index.ts @@ -48,7 +48,7 @@ test('call waitFor with a string', async t => { test('dom.click', async t => { const p = await dom.waitFor({ selector: 'p' }) - dom.click(p as HTMLElement) + await dom.click(p as HTMLElement) t.ok('does not throw') })