expect-webdriverio
Version:
WebdriverIO Assertion Library
80 lines (79 loc) • 2.81 kB
JavaScript
import { printDiffOrStringify, printExpected, printReceived } from 'jest-matcher-utils';
import { equals } from '../jasmineUtils.js';
const EXPECTED_LABEL = 'Expected';
const RECEIVED_LABEL = 'Received';
const NOT_SUFFIX = ' [not]';
const NOT_EXPECTED_LABEL = EXPECTED_LABEL + NOT_SUFFIX;
export const getSelector = (el) => {
let result = typeof el.selector === 'string' ? el.selector : '<fn>';
if (Array.isArray(el) && el.props.length > 0) {
result += ', <props>';
}
return result;
};
export const getSelectors = (el) => {
const selectors = [];
let parent;
if (Array.isArray(el)) {
selectors.push(`${el.foundWith}(\`${getSelector(el)}\`)`);
parent = el.parent;
}
else {
parent = el;
}
while (parent && 'selector' in parent) {
const selector = getSelector(parent);
const index = parent.index ? `[${parent.index}]` : '';
selectors.push(`${parent.index ? '$' : ''}$(\`${selector}\`)${index}`);
parent = parent.parent;
}
return selectors.reverse().join('.');
};
export const not = (isNot) => {
return `${isNot ? 'not ' : ''}`;
};
export const enhanceError = (subject, expected, actual, context, verb, expectation, arg2 = '', { message = '', containing = false }) => {
const { isNot = false } = context;
subject = typeof subject === 'string' ? subject : getSelectors(subject);
let contain = '';
if (containing) {
contain = ' containing';
}
if (verb) {
verb += ' ';
}
let diffString = isNot && equals(actual, expected)
? `${EXPECTED_LABEL}: ${printExpected(expected)}\n${RECEIVED_LABEL}: ${printReceived(actual)}`
: printDiffOrStringify(expected, actual, EXPECTED_LABEL, RECEIVED_LABEL, true);
if (isNot) {
diffString = diffString
.replace(EXPECTED_LABEL, NOT_EXPECTED_LABEL)
.replace(RECEIVED_LABEL, RECEIVED_LABEL + ' '.repeat(NOT_SUFFIX.length));
}
if (message) {
message += '\n';
}
if (arg2) {
arg2 = ` ${arg2}`;
}
const msg = `${message}Expect ${subject} ${not(isNot)}to ${verb}${expectation}${arg2}${contain}\n\n${diffString}`;
return msg;
};
export const enhanceErrorBe = (subject, pass, context, verb, expectation, options) => {
return enhanceError(subject, not(context.isNot) + expectation, not(!pass) + expectation, context, verb, expectation, '', options);
};
export const numberError = (options = {}) => {
if (typeof options.eq === 'number') {
return options.eq;
}
if (options.gte && options.lte) {
return `>= ${options.gte} && <= ${options.lte}`;
}
if (options.gte) {
return `>= ${options.gte}`;
}
if (options.lte) {
return ` <= ${options.lte}`;
}
return 'no params';
};