-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathcreateTestLocator.ts
90 lines (71 loc) · 2.53 KB
/
createTestLocator.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
import {createSimpleLocator} from './index.js';
import type {CreateTestLocatorOptions, LocatorFunction, LocatorKit} from './types';
/**
* Creates locator utils for tests (`locator`, `selector` and `testId` functions).
*/
export const createTestLocator = <Locator>({
attributesOptions,
createLocatorByCssSelector,
supportWildcardsInCssSelectors,
}: CreateTestLocatorOptions<Locator>): LocatorKit<Locator> => {
const {getTestId, locator: createAttributes} = createSimpleLocator({
attributesOptions,
isProduction: false,
});
const getSelector: LocatorFunction<string> = (...args) => {
const attributes = createAttributes(...(args as [string]));
return Object.keys(attributes)
.map((name) => getAttributeCss(name, attributes[name]!, supportWildcardsInCssSelectors))
.join('');
};
const locator: LocatorFunction<Locator> = (...args) =>
createLocatorByCssSelector(getSelector(...(args as [string])));
return {getSelector, getTestId, locator};
};
/**
* Get CSS selector string for single attribute.
*/
const getAttributeCss = (
name: string,
value: string,
supportWildcardsInCssSelectors: boolean,
): string => {
if (!supportWildcardsInCssSelectors) {
return attributeSelectors.exact(name, value);
}
const valueParts = value.split(asterisksRegex);
if (valueParts.length === 1) {
return attributeSelectors.exact(name, value);
}
const lastPart = valueParts[valueParts.length - 1]!;
const startsWithAsterisk = valueParts[0] === '';
const endsWithAsterisk = lastPart === '';
if (startsWithAsterisk && endsWithAsterisk && valueParts.length === 2) {
return attributeSelectors.any(name);
}
const cssParts: string[] = [];
if (!startsWithAsterisk) {
cssParts.push(attributeSelectors.startsWith(name, valueParts[0]!));
}
for (let index = 1; index < valueParts.length - 1; index += 1) {
cssParts.push(attributeSelectors.contains(name, valueParts[index]!));
}
if (!endsWithAsterisk) {
cssParts.push(attributeSelectors.endsWith(name, lastPart));
}
return cssParts.join('');
};
/**
* Attribute CSS selectors by attribute value inclusion type.
*/
const attributeSelectors = {
any: (name: string) => `[${name}]`,
contains: (name: string, value: string) => `[${name}*="${value}"]`,
endsWith: (name: string, value: string) => `[${name}$="${value}"]`,
exact: (name: string, value: string) => `[${name}="${value}"]`,
startsWith: (name: string, value: string) => `[${name}^="${value}"]`,
};
/**
* Regex to split a string by asterisks.
*/
const asterisksRegex = /\*+/;