-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathbaseQueries.ts
95 lines (86 loc) · 2.27 KB
/
baseQueries.ts
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
import {
waitFor,
getElementError,
waitForOptions,
} from '@testing-library/react';
import type Query from './queries/Query';
function getMultipleElementsFoundError(
container: HTMLElement,
query: Query,
): Error {
return getElementError(
[
`Found multiple elements ${query.description}.`,
query.multipleErrorDetail,
'\n\n(If this is intentional, then use `getAllBy`, `queryAllBy` or `findAllBy`).',
]
.filter((p) => p)
.join(' '),
container,
);
}
function getNoElementFoundError(container: HTMLElement, query: Query): Error {
return getElementError(
[
`Unable to find any element ${query.description}.`,
query.missingErrorDetail,
]
.filter((p) => p)
.join(' '),
container,
);
}
function elementListToArray(
elements: NodeListOf<HTMLElement> | HTMLElement[],
): HTMLElement[] {
if (!elements) {
return [];
}
if (Array.isArray(elements)) {
return elements;
}
return Array.from(elements);
}
export const queryAllBy = (
container: HTMLElement,
query: Query,
): HTMLElement[] => elementListToArray(query.queryAll(container));
export const queryBy = (
container: HTMLElement,
query: Query,
): HTMLElement | null => {
const elements = queryAllBy(container, query);
if (elements.length > 1) {
throw getMultipleElementsFoundError(container, query);
}
return elements[0] || null;
};
export const getAllBy = (
container: HTMLElement,
query: Query,
): HTMLElement[] => {
const fn = query.getAll || query.queryAll;
const elements = elementListToArray(fn(container));
if (!elements.length) {
throw getNoElementFoundError(container, query);
}
return elements;
};
export const getBy = (container: HTMLElement, query: Query): HTMLElement => {
const elements = getAllBy(container, query);
if (elements.length > 1) {
throw getMultipleElementsFoundError(container, query);
}
return elements[0]!;
};
export const findAllBy = (
container: HTMLElement,
query: Query,
waitOptions?: waitForOptions,
): Promise<HTMLElement[]> =>
waitFor(() => getAllBy(container, query), waitOptions);
export const findBy = (
container: HTMLElement,
query: Query,
waitOptions?: waitForOptions,
): Promise<HTMLElement> => waitFor(() => getBy(container, query), waitOptions);