testcafe-selector-generator
Version:
46 lines (34 loc) • 1.48 kB
JavaScript
import TESTCAFE_CORE from '../deps/testcafe-core';
import { BaseCreator } from './base-creator';
import { RULE_TYPE } from '../rules/rule-type';
import { SelectorDescriptor } from '../selector-descriptor';
import { escapeIdValue, escapeValueForSelectorWithRegExp } from './utils/escape';
import { getRegExpAttributesDescriptor } from './utils/attr-utils';
const { domUtils } = TESTCAFE_CORE;
const ASP_AUTOGENERATED_ID_PART_RE = /_ctl\d+|ctl\d+_|^ctl\d+$/g;
export class IdSelectorCreator extends BaseCreator {
constructor () {
super(RULE_TYPE.byId);
this.idAttr = null;
}
_init () {
this.idAttr = this.element.getAttribute('id');
}
_shouldCreate () {
return !!this.idAttr;
}
_getDescriptor () {
if (ASP_AUTOGENERATED_ID_PART_RE.test(this.idAttr)) {
let idRegExp = escapeValueForSelectorWithRegExp(this.idAttr);
idRegExp = idRegExp.replace(ASP_AUTOGENERATED_ID_PART_RE, substr => substr.replace(/\d+/, '\\d+'));
const tagName = domUtils.getTagName(this.element);
const filterValue = { attrName: 'id', attrValueRe: new RegExp(idRegExp) };
return getRegExpAttributesDescriptor(RULE_TYPE.byId, this.element, tagName, filterValue);
}
return new SelectorDescriptor({
ruleType: RULE_TYPE.byId,
element: this.element,
cssSelector: '#' + escapeIdValue(this.idAttr),
});
}
}