Skip to content

Commit b565a1e

Browse files
committed
add test
1 parent 216a875 commit b565a1e

File tree

2 files changed

+10
-6
lines changed

2 files changed

+10
-6
lines changed

web_src/js/utils/dom.test.ts

+8-1
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,4 @@
1-
import {createElementFromAttrs, createElementFromHTML} from './dom.ts';
1+
import {createElementFromAttrs, createElementFromHTML, querySingleVisibleElem} from './dom.ts';
22

33
test('createElementFromHTML', () => {
44
expect(createElementFromHTML('<a>foo<span>bar</span></a>').outerHTML).toEqual('<a>foo<span>bar</span></a>');
@@ -16,3 +16,10 @@ test('createElementFromAttrs', () => {
1616
}, 'txt', createElementFromHTML('<span>inner</span>'));
1717
expect(el.outerHTML).toEqual('<button id="the-id" class="cls-1 cls-2" disabled="" tabindex="0" data-foo="the-data">txt<span>inner</span></button>');
1818
});
19+
20+
test('querySingleVisibleElem', () => {
21+
let el = createElementFromHTML('<div><span>foo</span></div>');
22+
expect(querySingleVisibleElem(el, 'span').textContent).toEqual('foo');
23+
el = createElementFromHTML('<div><span>foo</span><span>bar</span></div>');
24+
expect(() => querySingleVisibleElem(el, 'span')).toThrowError('Expected exactly one visible element');
25+
});

web_src/js/utils/dom.ts

+2-5
Original file line numberDiff line numberDiff line change
@@ -333,10 +333,7 @@ export function animateOnce(el: Element, animationClassName: string): Promise<vo
333333

334334
export function querySingleVisibleElem<T extends HTMLElement>(parent: Element, selector: string) : T|null {
335335
const elems = parent.querySelectorAll<HTMLElement>(selector);
336-
const candidates = [];
337-
for (const button of elems) {
338-
if (isElemVisible(button)) candidates.push(button);
339-
}
340-
if (candidates.length > 1) throw new Error('multiple primary buttons found, only one could be defined');
336+
const candidates = Array.from(elems).filter(isElemVisible);
337+
if (candidates.length > 1) throw new Error(`Expected exactly one visible element matching selector "${selector}", but found ${candidates.length}`);
341338
return candidates.length ? candidates[0] as T : null;
342339
}

0 commit comments

Comments
 (0)