Skip to content

Commit 5a50b27

Browse files
authored
Make frontend unit test code could know it is in testing (#32656)
See the comment of isInFrontendUnitTest
1 parent 846f618 commit 5a50b27

File tree

2 files changed

+10
-3
lines changed

2 files changed

+10
-3
lines changed

web_src/js/utils/dom.ts

+4-3
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,7 @@
11
import {debounce} from 'throttle-debounce';
22
import type {Promisable} from 'type-fest';
33
import type $ from 'jquery';
4+
import {isInFrontendUnitTest} from './testhelper.ts';
45

56
type ArrayLikeIterable<T> = ArrayLike<T> & Iterable<T>; // for NodeListOf and Array
67
type ElementArg = Element | string | ArrayLikeIterable<Element> | ReturnType<typeof $>;
@@ -76,8 +77,8 @@ export function queryElemSiblings<T extends Element>(el: Element, selector = '*'
7677

7778
// it works like jQuery.children: only the direct children are selected
7879
export function queryElemChildren<T extends Element>(parent: Element | ParentNode, selector = '*', fn?: ElementsCallback<T>): ArrayLikeIterable<T> {
79-
if (window.vitest) {
80-
// bypass the vitest bug: it doesn't support ":scope >"
80+
if (isInFrontendUnitTest()) {
81+
// https://github.com/capricorn86/happy-dom/issues/1620 : ":scope" doesn't work
8182
const selected = Array.from<T>(parent.children as any).filter((child) => child.matches(selector));
8283
return applyElemsCallback<T>(selected, fn);
8384
}
@@ -357,6 +358,6 @@ export function addDelegatedEventListener<T extends HTMLElement, E extends Event
357358
parent.addEventListener(type, (e: Event) => {
358359
const elem = (e.target as HTMLElement).closest(selector);
359360
if (!elem) return;
360-
listener(elem as T, e);
361+
listener(elem as T, e as E);
361362
}, options);
362363
}

web_src/js/utils/testhelper.ts

+6
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,6 @@
1+
// there could be different "testing" concepts, for example: backend's "setting.IsInTesting"
2+
// even if backend is in testing mode, frontend could be complied in production mode
3+
// so this function only checks if the frontend is in unit testing mode (usually from *.test.ts files)
4+
export function isInFrontendUnitTest() {
5+
return process.env.TEST === 'true';
6+
}

0 commit comments

Comments
 (0)