From 5a50b271e71b5e8bb7bdef149e07dcd2b0db3e3a Mon Sep 17 00:00:00 2001 From: wxiaoguang Date: Thu, 28 Nov 2024 01:40:32 +0800 Subject: [PATCH] Make frontend unit test code could know it is in testing (#32656) See the comment of isInFrontendUnitTest --- web_src/js/utils/dom.ts | 7 ++++--- web_src/js/utils/testhelper.ts | 6 ++++++ 2 files changed, 10 insertions(+), 3 deletions(-) create mode 100644 web_src/js/utils/testhelper.ts diff --git a/web_src/js/utils/dom.ts b/web_src/js/utils/dom.ts index 06c5e8b486..6e830b9817 100644 --- a/web_src/js/utils/dom.ts +++ b/web_src/js/utils/dom.ts @@ -1,6 +1,7 @@ import {debounce} from 'throttle-debounce'; import type {Promisable} from 'type-fest'; import type $ from 'jquery'; +import {isInFrontendUnitTest} from './testhelper.ts'; type ArrayLikeIterable = ArrayLike & Iterable; // for NodeListOf and Array type ElementArg = Element | string | ArrayLikeIterable | ReturnType; @@ -76,8 +77,8 @@ export function queryElemSiblings(el: Element, selector = '*' // it works like jQuery.children: only the direct children are selected export function queryElemChildren(parent: Element | ParentNode, selector = '*', fn?: ElementsCallback): ArrayLikeIterable { - if (window.vitest) { - // bypass the vitest bug: it doesn't support ":scope >" + if (isInFrontendUnitTest()) { + // https://github.com/capricorn86/happy-dom/issues/1620 : ":scope" doesn't work const selected = Array.from(parent.children as any).filter((child) => child.matches(selector)); return applyElemsCallback(selected, fn); } @@ -357,6 +358,6 @@ export function addDelegatedEventListener { const elem = (e.target as HTMLElement).closest(selector); if (!elem) return; - listener(elem as T, e); + listener(elem as T, e as E); }, options); } diff --git a/web_src/js/utils/testhelper.ts b/web_src/js/utils/testhelper.ts new file mode 100644 index 0000000000..e91cf85e86 --- /dev/null +++ b/web_src/js/utils/testhelper.ts @@ -0,0 +1,6 @@ +// there could be different "testing" concepts, for example: backend's "setting.IsInTesting" +// even if backend is in testing mode, frontend could be complied in production mode +// so this function only checks if the frontend is in unit testing mode (usually from *.test.ts files) +export function isInFrontendUnitTest() { + return process.env.TEST === 'true'; +}