create-locator
Version:
Creates HTML element locators for tests 📌
66 lines (65 loc) • 2.42 kB
JavaScript
;
exports.getCssSelectorFromAttributesChain = undefined;
/**
* Get CSS selector string from attributes chain.
* This function is convenient to use inside `mapAttributesChain` function.
*/
const getCssSelectorFromAttributesChain = exports.getCssSelectorFromAttributesChain = (attributesChain) => {
const cssSelectors = attributesChain.map(getCssSelectorFromAttributes).filter(Boolean);
if (cssSelectors.length === 0) {
return '*';
}
return cssSelectors.join(' ');
};
/**
* Get CSS selector string from attributes object.
*/
const getCssSelectorFromAttributes = (attributes) => {
const attributeCssSelectors = [];
for (const attributeName of Object.keys(attributes)) {
const attributeValue = attributes[attributeName];
const cssSelector = getAttributeCssSelector(attributeName, attributeValue);
attributeCssSelectors.push(cssSelector);
}
return attributeCssSelectors.join('');
};
/**
* Get CSS selector string for single attribute.
*/
const getAttributeCssSelector = (attributeName, attributeValue) => {
const valueParts = attributeValue.split(starsRegexp);
if (valueParts.length === 1) {
return attributeSelectors.exact(attributeName, attributeValue);
}
const lastPart = valueParts[valueParts.length - 1];
const startsWithStar = valueParts[0] === '';
const endsWithStar = lastPart === '';
if (startsWithStar && endsWithStar && valueParts.length === 2) {
return attributeSelectors.any(attributeName);
}
const cssSelectors = [];
if (!startsWithStar) {
cssSelectors.push(attributeSelectors.startsWith(attributeName, valueParts[0]));
}
for (let index = 1; index < valueParts.length - 1; index += 1) {
cssSelectors.push(attributeSelectors.contains(attributeName, valueParts[index]));
}
if (!endsWithStar) {
cssSelectors.push(attributeSelectors.endsWith(attributeName, lastPart));
}
return cssSelectors.join('');
};
/**
* Attribute CSS selectors by attribute value inclusion type.
*/
const attributeSelectors = {
any: (name) => `[${name}]`,
contains: (name, value) => `[${name}*="${value}"]`,
endsWith: (name, value) => `[${name}$="${value}"]`,
exact: (name, value) => `[${name}="${value}"]`,
startsWith: (name, value) => `[${name}^="${value}"]`,
};
/**
* Regexp to split a string by stars.
*/
const starsRegexp = /\*+/;