UNPKG

create-locator

Version:

Creates HTML element locators for tests 📌

62 lines (61 loc) • 2.32 kB
import { createSimpleLocator } from './index.js'; /** * Creates locator utils for tests (`locator`, `selector` and `testId` functions). */ export const createTestLocator = ({ attributesOptions, createLocatorByCssSelector, supportWildcardsInCssSelectors, }) => { const { getTestId, locator: createAttributes } = createSimpleLocator({ attributesOptions, isProduction: false, }); const getSelector = (...args) => { const attributes = createAttributes(...args); return Object.keys(attributes) .map((name) => getAttributeCss(name, attributes[name], supportWildcardsInCssSelectors)) .join(''); }; const locator = (...args) => createLocatorByCssSelector(getSelector(...args)); return { getSelector, getTestId, locator }; }; /** * Get CSS selector string for single attribute. */ const getAttributeCss = (name, value, supportWildcardsInCssSelectors) => { 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 = []; 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) => `[${name}]`, contains: (name, value) => `[${name}*="${value}"]`, endsWith: (name, value) => `[${name}$="${value}"]`, exact: (name, value) => `[${name}="${value}"]`, startsWith: (name, value) => `[${name}^="${value}"]`, }; /** * Regex to split a string by asterisks. */ const asterisksRegex = /\*+/;