cypress-plus
Version:
A bunch of useful Cypress commands with full TypeScript support.
678 lines • 27.3 kB
JavaScript
;
Object.defineProperty(exports, "__esModule", { value: true });
exports.Actor = exports.Question = exports.Task = exports.Interaction = exports.UseCypress = exports.Ability = void 0;
function logCommand({ options, originalOptions }) {
if (options.log) {
options.logger({
name: options.description,
message: options.customLogMessage,
consoleProps: () => originalOptions,
});
}
}
function logCommandCheck({ result, options, originalOptions }) {
if (!options.log || !options.verbose)
return;
const message = [result];
if (options.customLogCheckMessage) {
message.unshift(options.customLogCheckMessage);
}
options.logger({
name: options.description,
message,
consoleProps: () => originalOptions,
});
}
function polling(subject, checkFunction, originalOptions = {}) {
if (!(checkFunction instanceof Function)) {
throw new Error("'checkFunction' parameter should be a function. Found: " + checkFunction);
}
const defaultOptions = {
interval: 200,
timeout: 5000,
retries: 25,
errorMessage: "Timed out retrying.",
description: "polling",
log: true,
customLogMessage: undefined,
logger: Cypress.log,
verbose: false,
customLogCheckMessage: undefined,
postFailureAction: undefined,
mode: "timeout",
ignoreFailureException: false,
};
const options = Object.assign(Object.assign({}, defaultOptions), originalOptions);
options.customLogMessage = [options.customLogMessage, originalOptions].filter(Boolean);
let retries = 0;
if (options.mode == "timeout") {
retries = Math.floor(options.timeout / options.interval);
options.errorMessage = "Timed out retrying.";
}
else {
retries = options.retries;
options.errorMessage = "Retried too many times.";
}
let currentWaitTime;
let waitTime = 0;
if (Array.isArray(options.interval)) {
waitTime = options.interval.reverse();
}
else {
waitTime = options.interval;
}
if (Array.isArray(options.interval)) {
if (options.interval.length > 1) {
currentWaitTime = waitTime.pop();
}
else {
currentWaitTime = waitTime[0];
}
}
else {
currentWaitTime = waitTime;
}
logCommand({ options, originalOptions });
const check = (result) => {
logCommandCheck({ result, options, originalOptions });
if (Array.isArray(options.interval)) {
if (options.interval.length > 1) {
currentWaitTime = waitTime.pop();
}
else {
currentWaitTime = waitTime[0];
}
}
else {
currentWaitTime = waitTime;
}
if (result) {
return result;
}
if (retries < 1) {
const msg = options.errorMessage instanceof Function ? options.errorMessage(result, options) : options.errorMessage;
if (options.postFailureAction && options.postFailureAction instanceof Function) {
const fnResult = options.postFailureAction();
if (fnResult === true || fnResult === false) {
return fnResult;
}
}
if (!options.ignoreFailureException && !options.postFailureAction)
throw new Error(msg);
return;
}
if (currentWaitTime) {
cy.wait(currentWaitTime, { log: false }).then(() => {
retries--;
return resolveValue();
});
}
};
const resolveValue = () => {
const result = checkFunction(subject);
const isAPromise = Boolean(result && result.then);
if (isAPromise) {
return result.then(check);
}
else {
return check(result);
}
};
return resolveValue();
}
Cypress.Commands.add("polling", { prevSubject: "optional" }, polling);
Cypress.Commands.add("clickOnDataCy", (selector, options) => {
return cy.get(`[data-cy="${selector}"]`, options).click(options);
});
Cypress.Commands.add("clickOnDataCyAdv", (selector, moreSelectors, options) => {
return cy.getByDataCyAdv(selector, moreSelectors, options).click(options);
});
Cypress.Commands.add("waitForUrlAndVisibleDataCy", (url, selector, timeout) => {
if (url && selector) {
cy.visit(url, { timeout: timeout || 5000 });
return cy.get(`[data-cy="${selector}"]`, { timeout: timeout || 5000 }).should("be.visible");
}
});
Cypress.Commands.add("waitForUrlAndVisible", (url, selector, timeout) => {
if (url && selector) {
cy.visit(url, { timeout: timeout || 5000 });
return cy.get(selector, { timeout: timeout || 5000 }).should("be.visible");
}
});
Cypress.Commands.add("rightClickOnDataCy", (selector, options) => {
return cy.get(`[data-cy="${selector}"]`, options).rightclick(options);
});
Cypress.Commands.add("getByDataCy", (selector, options) => {
return cy.get(`[data-cy="${selector}"]`, options);
});
Cypress.Commands.add("getByDataCyStartsWith", (selector, options) => {
return cy.get(`[data-cy^="${selector}"]`, options);
});
Cypress.Commands.add("getByDataCyEndsWith", (selector, options) => {
return cy.get(`[data-cy$="${selector}"]`, options);
});
Cypress.Commands.add("getByDataCyContains", (selector, options) => {
return cy.get(`[data-cy*="${selector}"]`, options);
});
Cypress.Commands.add("getByData", (dataName, selector, options) => {
return cy.get(`[data-${dataName}="${selector}"]`, options);
});
Cypress.Commands.add("getByDataStartsWith", (dataName, selector, options) => {
return cy.get(`[data-${dataName}^="${selector}"]`, options);
});
Cypress.Commands.add("getByDataEndsWith", (dataName, selector, options) => {
return cy.get(`[data-${dataName}$="${selector}"]`, options);
});
Cypress.Commands.add("getByDataContains", (dataName, selector, options) => {
return cy.get(`[data-${dataName}*="${selector}"]`, options);
});
Cypress.Commands.add("getByDataAdv", (dataName, selector, moreSelectors, options) => {
moreSelectors = moreSelectors !== null && moreSelectors !== void 0 ? moreSelectors : "";
return cy.get(`[data-${dataName}="${selector}"] ${moreSelectors}`.trim(), options);
});
Cypress.Commands.add("getByDataCyAdv", (selector, moreSelectors, options) => {
moreSelectors = moreSelectors !== null && moreSelectors !== void 0 ? moreSelectors : "";
return cy.get(`[data-cy="${selector}"] ${moreSelectors}`.trim(), options);
});
Cypress.Commands.add("await", (promise, throwException, wait) => {
return cy.then(() => {
return cy.wrap(null, { log: false }).then(() => {
if (wait && wait > 0) {
cy.wait(wait);
}
if (throwException) {
return new Cypress.Promise((resolve, reject) => {
return promise.then(resolve, reject);
});
}
else {
return new Cypress.Promise((resolve, reject) => {
return promise.catch(resolve).then(resolve, reject);
});
}
});
});
});
Cypress.Commands.add("awaitFor", (promise, throwException, wait) => {
return cy.then(() => {
return cy.wrap(null, { log: false }).then(() => {
if (wait && wait > 0) {
cy.wait(wait);
}
if (throwException) {
return new Cypress.Promise((resolve, reject) => {
return promise.then(resolve, reject);
});
}
else {
return new Cypress.Promise((resolve, reject) => {
return promise.catch(resolve).then(resolve, reject);
});
}
});
});
});
Cypress.Commands.add("justWrap", (action, wait, options) => {
if (!options) {
options = { log: false };
}
;
return cy.wrap(null, options).then(() => {
if (wait && wait > 0) {
cy.wait(wait);
}
return action();
});
});
Cypress.Commands.add("waitForUrlToChange", (currentUrl, timeout) => {
if (!timeout || timeout <= 0)
timeout = 5000;
return cy.polling(() => {
return cy.url().then(url => {
return url != currentUrl;
});
}, { mode: "timeout", timeout: timeout, interval: 100 }).then(() => {
return cy.url().should("not.eq", currentUrl);
});
});
Cypress.Commands.add("assertElementsCount", (selector, count, lengthComparison, options) => {
if (count <= 0)
count = 0;
switch (lengthComparison) {
case "equal":
return cy.get(selector, options).should("have.length", count);
case "above":
return cy.get(selector, options).should("have.length.above", count);
case "below":
return cy.get(selector, options).should("have.length.below", count);
case "atLeast":
return cy.get(selector, options).should("have.length.at.least", count);
case "atMost":
return cy.get(selector, options).should("have.length.at.most", count);
}
});
Cypress.Commands.add("getCount", (selector, options) => {
return cy.get(selector, options).then($elements => {
const countOfElements = $elements.length;
return cy.wrap(countOfElements, { log: false });
});
});
Cypress.Commands.add("getByAriaLabel", (ariaLabel, options) => {
return cy.get(`[aria-label="${ariaLabel}"]`, options);
});
Cypress.Commands.add("getByTitle", (title, options) => {
return cy.get(`[title="${title}"]`, options);
});
Cypress.Commands.add("getByAlt", (alt, options) => {
return cy.get(`[alt="${alt}"]`, options);
});
Cypress.Commands.add("getByPlaceholder", (placeholder, options) => {
return cy.get(`[placeholder="${placeholder}"]`, options);
});
Cypress.Commands.add("getByValue", (value, options) => {
return cy.get(`[value="${value}"]`, options);
});
Cypress.Commands.add("waitAndClick", (selector, timeout) => {
if (!timeout || timeout <= 0)
timeout = 5000;
return cy.get(selector, { timeout: timeout }).click();
});
Cypress.Commands.add("getByText", (text, timeout) => {
return cy.contains(text, { matchCase: false, includeShadowDom: true, timeout: timeout || 5000 });
});
Cypress.Commands.add("getByExactText", (text, timeout) => {
return cy.contains(text, { matchCase: true, includeShadowDom: true, timeout: timeout || 5000 });
});
Cypress.Commands.add("justType", (selector, text, pressEnter = false, options) => {
if (pressEnter)
return cy.get(selector, options).type("{selectall}" + text + "{enter}");
return cy.get(selector, options).type("{selectall}" + text);
});
Cypress.Commands.add("waitForType", (selector, text, timeout, pressEnter = false, options) => {
if (!timeout || timeout <= 0)
timeout = 5000;
cy.wait(timeout);
if (pressEnter)
return cy.get(selector, options).type("{selectall}" + text + "{enter}");
return cy.get(selector, options).type("{selectall}" + text);
});
Cypress.Commands.add("waitForTypeByDataCy", (selector, text, timeout, pressEnter = false, options) => {
if (!timeout || timeout <= 0)
timeout = 5000;
cy.wait(timeout);
if (pressEnter)
return cy.get(`[data-cy="${selector}"]`, options).type("{selectall}" + text + "{enter}");
return cy.get(`[data-cy="${selector}"]`, options).type("{selectall}" + text);
});
Cypress.Commands.add("clearAndType", (selector, text, pressEnter = false, options) => {
if (pressEnter)
return cy.get(selector, options).clear().type("{selectall}" + text + "{enter}");
return cy.get(selector, options).clear().type("{selectall}" + text);
});
Cypress.Commands.add("clearAndTypeByDataCy", (selector, text, pressEnter = false, options) => {
if (pressEnter)
return cy.get(`[data-cy="${selector}"]`, options).clear().type("{selectall}" + text + "{enter}");
return cy.get(`[data-cy="${selector}"]`, options).clear().type("{selectall}" + text);
});
Cypress.Commands.add("typeByDataCy", (selector, text, pressEnter = false, options) => {
if (pressEnter)
return cy.get(`[data-cy="${selector}"]`, options).type("{selectall}" + text + "{enter}");
return cy.get(`[data-cy="${selector}"]`, options).type("{selectall}" + text);
});
Cypress.Commands.add("waitForClearAndType", (selector, text, timeout, pressEnter = false, options) => {
if (!timeout || timeout <= 0)
timeout = 5000;
cy.wait(timeout);
if (pressEnter)
return cy.get(selector, options).clear().type("{selectall}" + text + "{enter}");
return cy.get(selector, options).clear().type("{selectall}" + text);
});
Cypress.Commands.add("waitForClearAndTypeByDataCy", (selector, text, timeout, pressEnter = false, options) => {
if (!timeout || timeout <= 0)
timeout = 5000;
cy.wait(timeout);
if (pressEnter)
return cy.get(`[data-cy="${selector}"]`, options).clear().type("{selectall}" + text + "{enter}");
return cy.get(`[data-cy="${selector}"]`, options).clear().type("{selectall}" + text);
});
Cypress.Commands.add("selectFromDropdown", (selector, value, options) => {
return cy.get(selector, options).select(value);
});
Cypress.Commands.add("hover", (selector, options) => {
return cy.get(selector, options).trigger("mouseover");
});
Cypress.Commands.add("waitForElement", (selector, timeout) => {
return cy.get(selector, { timeout: timeout || 5000 });
});
Cypress.Commands.add("waitForElementDataCy", (selector, timeout) => {
return cy.get(`[data-cy="${selector}"]`, { timeout: timeout || 5000 });
});
Cypress.Commands.add("waitForElementDataCyAdv", (selector, moreSelectors, timeout) => {
moreSelectors = moreSelectors !== null && moreSelectors !== void 0 ? moreSelectors : "";
return cy.get(`[data-cy="${selector}"] ${moreSelectors}`.trim(), { timeout: timeout || 5000 });
});
Cypress.Commands.add("getInputValue", (selector, options) => {
return cy.get(selector, options).then(($input) => {
return cy.wrap($input.val(), { log: false });
});
});
Cypress.Commands.add("getParent", (selector, options) => {
return cy.get(selector, options).parent();
});
Cypress.Commands.add("getSibling", (selector, nth, options) => {
return cy.get(selector, options).siblings(":nth-child(" + nth + ")");
});
Cypress.Commands.add("getNthChild", (selector, nth, options) => {
return cy.get(selector, options).children().eq(nth);
});
Cypress.Commands.add("checkCheckbox", (selector, options) => {
return cy.get(selector, options).check();
});
Cypress.Commands.add("uncheckCheckbox", (selector, options) => {
return cy.get(selector, options).uncheck();
});
Cypress.Commands.add("getByClass", (className, options) => {
return cy.get(`.${className}`, options);
});
Cypress.Commands.add("getByClassStartsWith", (className, options) => {
return cy.get(`[class^="${className}"]`, options);
});
Cypress.Commands.add("getByClassEndsWith", (className, options) => {
return cy.get(`[class$="${className}"]`, options);
});
Cypress.Commands.add("getByClassContains", (className, options) => {
return cy.get(`[class*="${className}"]`, options);
});
Cypress.Commands.add("clickButton", (buttonText, options) => {
return cy.get(`button:contains("${buttonText}")`, options).click();
});
Cypress.Commands.add("clickLink", (linkText, options) => {
return cy.get(`link:contains("${linkText}")`, options).click();
});
Cypress.Commands.add("getByRole", (role, options) => {
return cy.get(`[role=${role}]`, options);
});
Cypress.Commands.add("getByName", (name, options) => {
return cy.get(`[name=${name}]`, options);
});
Cypress.Commands.add("getByHref", (href, options) => {
return cy.get(`a[href='${href}']`, options);
});
Cypress.Commands.add("getFirst", (selector, options) => {
return cy.get(selector, options).first();
});
Cypress.Commands.add("getLast", (selector, options) => {
return cy.get(selector, options).last();
});
Cypress.Commands.add("getFirstNth", (selector, nth, options) => {
return cy.get(selector, options).first().nextAll().eq(nth);
});
Cypress.Commands.add("getLastNth", (selector, nth, options) => {
return cy.get(selector, options).last().prevAll().eq(nth);
});
Cypress.Commands.add("getByAriaDescribedBy", (ariaDescribedBy, options) => {
return cy.get(`[aria-describedby='${ariaDescribedBy}']`, options);
});
Cypress.Commands.add("getByAriaControls", (ariaControls, options) => {
return cy.get(`[aria-controls='${ariaControls}']`, options);
});
Cypress.Commands.add("getByAriaCurrent", (ariaCurrent, options) => {
return cy.get(`[aria-current='${ariaCurrent}']`, options);
});
Cypress.Commands.add("waitForInvisible", (selector, timeout) => {
if (!timeout || timeout <= 0)
timeout = 5000;
return cy.get(selector, { timeout: timeout || 5000 }).should("not.be.visible");
});
Cypress.Commands.add("waitForVisible", (selector, timeout) => {
if (!timeout || timeout <= 0)
timeout = 5000;
return cy.get(selector, { timeout: timeout || 5000 }).should("be.visible");
});
Cypress.Commands.add("waitForInvisibleDataCy", (selector, timeout) => {
if (!timeout || timeout <= 0)
timeout = 5000;
return cy.get(`[data-cy="${selector}"]`, { timeout: timeout || 5000 }).should("not.be.visible");
});
Cypress.Commands.add("waitForVisibleDataCy", (selector, timeout) => {
if (!timeout || timeout <= 0)
timeout = 5000;
return cy.get(`[data-cy="${selector}"]`, { timeout: timeout || 5000 }).should("be.visible");
});
Cypress.Commands.add("waitForExist", (selector, timeout) => {
if (!timeout || timeout <= 0)
timeout = 5000;
return cy.get(selector, { timeout: timeout || 5000 }).should("exist");
});
Cypress.Commands.add("waitForNotExist", (selector, timeout) => {
if (!timeout || timeout <= 0)
timeout = 5000;
return cy.get(selector, { timeout: timeout || 5000 }).should("not.exist");
});
Cypress.Commands.add("waitForExistDataCy", (selector, timeout) => {
if (!timeout || timeout <= 0)
timeout = 5000;
return cy.get(`[data-cy="${selector}"]`, { timeout: timeout || 5000 }).should("exist");
});
Cypress.Commands.add("waitForNotExistDataCy", (selector, timeout) => {
if (!timeout || timeout <= 0)
timeout = 5000;
return cy.get(`[data-cy="${selector}"]`, { timeout: timeout || 5000 }).should("not.exist");
});
Cypress.Commands.add("goBack", () => {
return cy.go("back");
});
Cypress.Commands.add("goForward", () => {
return cy.go("forward");
});
Cypress.Commands.add("clearStoragesAndCookies", () => {
return cy.window().then((win) => {
win.sessionStorage.clear();
cy.clearCookies();
cy.clearLocalStorage();
});
});
Cypress.Commands.add("getByAttribute", (attrName, attrValue, options) => {
return cy.get(`[${attrName}="${attrValue}"]`, options);
});
Cypress.Commands.add("getByAttributeStartsWith", (attrName, attrValue, options) => {
return cy.get(`[${attrName}^="${attrValue}"]`, options);
});
Cypress.Commands.add("getByAttributeEndsWith", (attrName, attrValue, options) => {
return cy.get(`[${attrName}$="${attrValue}"]`, options);
});
Cypress.Commands.add("getByAttributeContains", (attrName, attrValue, options) => {
return cy.get(`[${attrName}*="${attrValue}"]`, options);
});
Cypress.Commands.add("getAttribute", (selector, attribute, options) => {
return cy.get(selector, options).then($el => {
return cy.wrap($el.attr(attribute), { log: false });
});
});
Cypress.Commands.add("getAttributeDataCy", (selector, attribute, options) => {
return cy.get(`[data-cy="${selector}"]`, options).then($el => {
return cy.wrap($el.attr(attribute), { log: false });
});
});
Cypress.Commands.add("getAttributeDataCyAdv", (selector, attribute, moreSelectors, options) => {
moreSelectors = moreSelectors !== null && moreSelectors !== void 0 ? moreSelectors : "";
return cy.get(`[data-cy="${selector}"] ${moreSelectors}`.trim(), options).then($el => {
return cy.wrap($el.attr(attribute), { log: false });
});
});
Cypress.Commands.add("getParentIf", (selector, condition, options) => {
return cy.get(selector, options).parents().each($el => {
if (condition($el))
return cy.wrap($el, { log: false });
});
});
Cypress.Commands.add("getParentsIf", (selector, condition, options) => {
const result = [];
cy.get(selector, options).parents().each($el => {
if (condition($el))
result.push($el);
});
return cy.wrap(result, { log: false });
});
Cypress.Commands.add("getChildIf", (selector, condition, options) => {
return cy.get(selector, options).children().each($el => {
if (condition($el))
return cy.wrap($el, { log: false });
});
});
Cypress.Commands.add("getChildrenIf", (selector, condition, options) => {
const result = [];
cy.get(selector, options).children().each($el => {
if (condition($el))
result.push($el);
});
return cy.wrap(result, { log: false });
});
Cypress.Commands.add("iterateChildren", (selector, callback, options) => {
return cy.get(selector, options).find("*").each(($el) => {
callback($el);
});
});
Cypress.Commands.add("iterateChildrenIf", (selector, condition, callback, options) => {
return cy.get(selector, options).find("*").each(($el) => {
if (condition($el))
callback($el);
});
});
Cypress.Commands.add("scrollToElement", (selector, position, options) => {
position = position || "center";
options = options || { ensureScrollable: false };
return cy.get(selector).scrollTo(position, options);
});
Cypress.Commands.add("scrollToElementByDataCy", (selector, position, options) => {
position = position || "center";
options = options || { ensureScrollable: false };
return cy.get(`[data-cy="${selector}"]`).scrollTo(position, options);
});
Cypress.Commands.add("isEmpty", (selector, options) => {
return cy.get(selector, options).should('be.empty');
});
Cypress.Commands.add("isNotEmpty", (selector, options) => {
return cy.get(selector, options).should('not.be.empty');
});
Cypress.Commands.add("hasValue", (selector, value, options) => {
return cy.get(selector, options).should('have.value', value);
});
Cypress.Commands.add("doesNotHaveValue", (selector, value, options) => {
return cy.get(selector, options).should('have.value', value);
});
Cypress.Commands.add("hasClass", (selector, value, options) => {
return cy.get(selector, options).should('have.class', value);
});
Cypress.Commands.add("doesNotHaveClass", (selector, value, options) => {
return cy.get(selector, options).should('not.have.class', value);
});
Cypress.Commands.add("isVisible", (selector, options) => {
return cy.get(selector, options).should('be.visible');
});
Cypress.Commands.add("isNotVisible", (selector, options) => {
return cy.get(selector, options).should('not.be.visible');
});
Cypress.Commands.add("checkURL", (url) => {
return cy.url().should('include', url);
});
Cypress.Commands.add("invokeText", (selector, options) => {
return cy.get(selector, options).invoke('text').then(value => {
return cy.wrap(value);
});
});
Cypress.Commands.add("invokeTextByDataCy", (selector, options) => {
return cy.get(`[data-cy="${selector}"]`, options).invoke('text').then(value => {
return cy.wrap(value);
});
});
Cypress.Commands.add("hasAttribute", (selector, attribute, value, options) => {
return cy.get(selector, options).should('have.attr', attribute, value);
});
Cypress.Commands.add("doesNotHaveAttribute", (selector, attribute, value, options) => {
return cy.get(selector, options).should('not.have.attr', attribute, value);
});
class Ability {
}
exports.Ability = Ability;
class UseCypress extends Ability {
can() {
return cy;
}
}
exports.UseCypress = UseCypress;
class Interaction {
}
exports.Interaction = Interaction;
class Task {
constructor(interactions) {
this.interactions = interactions;
}
getInteractions() {
return this.interactions;
}
attemptInteractionsAs(actor) {
for (const interaction of this.getInteractions()) {
interaction.attemptAs(actor);
}
}
attemptInteractionAs(actor, interactionClass) {
var _a;
const matchingInteractions = (_a = this.interactions) === null || _a === void 0 ? void 0 : _a.filter((a) => a instanceof interactionClass);
if (matchingInteractions.length === 0) {
throw new Error(`Interaction with name of '${interactionClass.name}' not found.`);
}
return matchingInteractions[0].attemptAs(actor);
}
}
exports.Task = Task;
class Question {
}
exports.Question = Question;
class Actor {
constructor(abilities) {
this.abilities = abilities;
}
useAbility(abilityClass) {
var _a;
const matchingAbilities = (_a = this.abilities) === null || _a === void 0 ? void 0 : _a.filter((a) => a instanceof abilityClass);
if (matchingAbilities.length === 0) {
throw new Error(`Actor does not have ability with name of '${abilityClass.name}'.`);
}
return matchingAbilities[0].can();
}
performs(taskOrInteraction) {
if (taskOrInteraction instanceof Task) {
return taskOrInteraction.performAs(this);
}
if (taskOrInteraction instanceof Interaction) {
return taskOrInteraction.attemptAs(this);
}
if (Array.isArray(taskOrInteraction) &&
taskOrInteraction.length > 0 &&
taskOrInteraction[0] instanceof Task) {
for (const interaction of taskOrInteraction) {
interaction.performAs(this);
}
return;
}
if (Array.isArray(taskOrInteraction) &&
taskOrInteraction.length > 0 &&
taskOrInteraction[0] instanceof Interaction) {
for (const interaction of taskOrInteraction) {
interaction.attemptAs(this);
}
return;
}
}
asserts(question, assert) {
question.askAs(this).then((answer) => {
assert(answer);
});
}
asksAbout(question) {
return question.askAs(this);
}
}
exports.Actor = Actor;
//# sourceMappingURL=index.js.map