Socket
Socket
Sign inDemoInstall

@testing-library/dom

Package Overview
Dependencies
Maintainers
15
Versions
228
Alerts
File Explorer

Advanced tools

Socket logo

Install Socket

Detect and block malicious and high-risk dependencies

Install

@testing-library/dom - npm Package Compare versions

Comparing version 8.19.0 to 8.19.1

14

dist/config.js

@@ -9,5 +9,3 @@ "use strict";

exports.runWithExpensiveErrorDiagnosticsDisabled = runWithExpensiveErrorDiagnosticsDisabled;
var _prettyDom = require("./pretty-dom");
// It would be cleaner for this to live inside './queries', but

@@ -37,3 +35,2 @@ // other parts of the code assume that all exports from

throwSuggestions: false,
// called when getBy* queries fail. (message, container) => Error

@@ -46,7 +43,5 @@ getElementError(message, container) {

},
_disableExpensiveErrorDiagnostics: false,
computedStyleSupportsPseudoElements: false
};
function runWithExpensiveErrorDiagnosticsDisabled(callback) {

@@ -60,3 +55,2 @@ try {

}
function configure(newConfig) {

@@ -67,12 +61,12 @@ if (typeof newConfig === 'function') {

newConfig = newConfig(config);
} // Merge the incoming config delta
}
config = { ...config,
// Merge the incoming config delta
config = {
...config,
...newConfig
};
}
function getConfig() {
return config;
}

@@ -8,15 +8,12 @@ "use strict";

exports.test = void 0;
/**
* Source: https://github.com/facebook/jest/blob/e7bb6a1e26ffab90611b2593912df15b69315611/packages/pretty-format/src/plugins/DOMElement.ts
*/
/* eslint-disable -- trying to stay as close to the original as possible */
/* istanbul ignore file */
/* istanbul ignore file */
function escapeHTML(str) {
return str.replace(/</g, '&lt;').replace(/>/g, '&gt;');
} // Return empty string if keys is empty.
}
// Return empty string if keys is empty.
const printProps = (keys, props, config, indentation, depth, refs, printer) => {

@@ -28,3 +25,2 @@ const indentationNext = indentation + config.indent;

let printed = printer(value, config, indentationNext, depth, refs);
if (typeof value !== 'string') {

@@ -34,16 +30,14 @@ if (printed.indexOf('\n') !== -1) {

}
printed = '{' + printed + '}';
}
return config.spacingInner + indentation + colors.prop.open + key + colors.prop.close + '=' + colors.value.open + printed + colors.value.close;
}).join('');
}; // https://developer.mozilla.org/en-US/docs/Web/API/Node/nodeType#node_type_constants
};
// https://developer.mozilla.org/en-US/docs/Web/API/Node/nodeType#node_type_constants
const NodeTypeTextNode = 3;
const NodeTypeTextNode = 3; // Return empty string if children is empty.
// Return empty string if children is empty.
const printChildren = (children, config, indentation, depth, refs, printer) => children.map(child => {
const printedChild = typeof child === 'string' ? printText(child, config) : printer(child, config, indentation, depth, refs);
if (printedChild === '' && typeof child === 'object' && child !== null && child.nodeType !== NodeTypeTextNode) {

@@ -53,6 +47,4 @@ // A plugin serialized this Node to '' meaning we should ignore it.

}
return config.spacingOuter + indentation + printedChild;
}).join('');
const printText = (text, config) => {

@@ -62,12 +54,11 @@ const contentColor = config.colors.content;

};
const printComment = (comment, config) => {
const commentColor = config.colors.comment;
return commentColor.open + '<!--' + escapeHTML(comment) + '-->' + commentColor.close;
}; // Separate the functions to format props, children, and element,
};
// Separate the functions to format props, children, and element,
// so a plugin could override a particular function, if needed.
// Too bad, so sad: the traditional (but unnecessary) space
// in a self-closing tagColor requires a second test of printedProps.
const printElement = (type, printedProps, printedChildren, config, indentation) => {

@@ -77,3 +68,2 @@ const tagColor = config.colors.tag;

};
const printElementAsLeaf = (type, config) => {

@@ -83,3 +73,2 @@ const tagColor = config.colors.tag;

};
const ELEMENT_NODE = 1;

@@ -90,3 +79,2 @@ const TEXT_NODE = 3;

const ELEMENT_REGEXP = /^((HTML|SVG)\w*)?Element$/;
const testNode = val => {

@@ -101,23 +89,16 @@ const constructorName = val.constructor.name;

};
const test = val => {
var _val$constructor;
return (val == null ? void 0 : (_val$constructor = val.constructor) == null ? void 0 : _val$constructor.name) && testNode(val);
};
exports.test = test;
function nodeIsText(node) {
return node.nodeType === TEXT_NODE;
}
function nodeIsComment(node) {
return node.nodeType === COMMENT_NODE;
}
function nodeIsFragment(node) {
return node.nodeType === FRAGMENT_NODE;
}
function createDOMElementFilter(filterNode) {

@@ -127,3 +108,2 @@ return {

var _val$constructor2;
return (val == null ? void 0 : (_val$constructor2 = val.constructor) == null ? void 0 : _val$constructor2.name) && testNode(val);

@@ -135,13 +115,9 @@ },

}
if (nodeIsComment(node)) {
return printComment(node.data, config);
}
const type = nodeIsFragment(node) ? `DocumentFragment` : node.tagName.toLowerCase();
if (++depth > config.maxDepth) {
return printElementAsLeaf(type, config);
}
return printElement(type, printProps(nodeIsFragment(node) ? [] : Array.from(node.attributes).map(attr => attr.name).sort(), nodeIsFragment(node) ? {} : Array.from(node.attributes).reduce((props, attribute) => {

@@ -148,0 +124,0 @@ props[attribute.name] = attribute.value;

@@ -525,3 +525,3 @@ "use strict";

// TODO: load events can be UIEvent or Event depending on what generated them
// This is were this abstraction breaks down.
// This is where this abstraction breaks down.
// But the common targets are <img />, <script /> and window.

@@ -528,0 +528,0 @@ // Neither of these targets receive a UIEvent

@@ -8,9 +8,5 @@ "use strict";

exports.fireEvent = fireEvent;
var _config = require("./config");
var _helpers = require("./helpers");
var _eventMap = require("./event-map");
function fireEvent(element, event) {

@@ -21,11 +17,8 @@ return (0, _config.getConfig)().eventWrapper(() => {

}
if (!element) {
throw new Error(`Unable to fire a "${event.type}" event - please provide a DOM element.`);
}
return element.dispatchEvent(event);
});
}
function createEvent(eventName, node, init, {

@@ -38,4 +31,4 @@ EventType = 'Event',

}
const eventInit = { ...defaultInit,
const eventInit = {
...defaultInit,
...init

@@ -50,7 +43,5 @@ };

} = eventInit;
if (value !== undefined) {
setNativeValue(node, value);
}
if (files !== undefined) {

@@ -67,3 +58,2 @@ // input.files is a read-only property so this is not allowed:

}
Object.assign(node, targetProperties);

@@ -74,3 +64,2 @@ const window = (0, _helpers.getWindowFromNode)(node);

/* istanbul ignore else */
if (typeof EventConstructor === 'function') {

@@ -91,9 +80,8 @@ event = new EventConstructor(eventName, eventInit);

});
} // DataTransfer is not supported in jsdom: https://github.com/jsdom/jsdom/issues/1568
}
// DataTransfer is not supported in jsdom: https://github.com/jsdom/jsdom/issues/1568
const dataTransferProperties = ['dataTransfer', 'clipboardData'];
dataTransferProperties.forEach(dataTransferKey => {
const dataTransferValue = eventInit[dataTransferKey];
if (typeof dataTransferValue === 'object') {

@@ -119,3 +107,2 @@ /* istanbul ignore if */

}
Object.keys(_eventMap.eventMap).forEach(key => {

@@ -127,3 +114,2 @@ const {

const eventName = key.toLowerCase();
createEvent[key] = (node, init) => createEvent(eventName, node, init, {

@@ -133,7 +119,7 @@ EventType,

});
fireEvent[key] = (node, init) => fireEvent(node, createEvent[key](node, init));
});
fireEvent[key] = (node, init) => fireEvent(node, createEvent[key](node, init));
}); // function written after some investigation here:
// function written after some investigation here:
// https://github.com/facebook/react/issues/10135#issuecomment-401496776
function setNativeValue(element, value) {

@@ -147,3 +133,2 @@ const {

} = Object.getOwnPropertyDescriptor(prototype, 'value') || {};
if (prototypeValueSetter && valueSetter !== prototypeValueSetter) {

@@ -161,8 +146,7 @@ prototypeValueSetter.call(element, value);

}
Object.keys(_eventMap.eventAliasMap).forEach(aliasKey => {
const key = _eventMap.eventAliasMap[aliasKey];
fireEvent[aliasKey] = (...args) => fireEvent[key](...args);
});
/* eslint complexity:["error", 9] */

@@ -7,5 +7,3 @@ "use strict";

exports.getNodeText = getNodeText;
var _helpers = require("./helpers");
function getNodeText(node) {

@@ -15,4 +13,3 @@ if (node.matches('input[type=submit], input[type=button], input[type=reset]')) {

}
return Array.from(node.childNodes).filter(child => child.nodeType === _helpers.TEXT_NODE && Boolean(child.textContent)).map(c => c.textContent).join('');
}

@@ -7,9 +7,5 @@ "use strict";

exports.getQueriesForElement = getQueriesForElement;
var defaultQueries = _interopRequireWildcard(require("./queries"));
function _getRequireWildcardCache(nodeInterop) { if (typeof WeakMap !== "function") return null; var cacheBabelInterop = new WeakMap(); var cacheNodeInterop = new WeakMap(); return (_getRequireWildcardCache = function (nodeInterop) { return nodeInterop ? cacheNodeInterop : cacheBabelInterop; })(nodeInterop); }
function _interopRequireWildcard(obj, nodeInterop) { if (!nodeInterop && obj && obj.__esModule) { return obj; } if (obj === null || typeof obj !== "object" && typeof obj !== "function") { return { default: obj }; } var cache = _getRequireWildcardCache(nodeInterop); if (cache && cache.has(obj)) { return cache.get(obj); } var newObj = {}; var hasPropertyDescriptor = Object.defineProperty && Object.getOwnPropertyDescriptor; for (var key in obj) { if (key !== "default" && Object.prototype.hasOwnProperty.call(obj, key)) { var desc = hasPropertyDescriptor ? Object.getOwnPropertyDescriptor(obj, key) : null; if (desc && (desc.get || desc.set)) { Object.defineProperty(newObj, key, desc); } else { newObj[key] = obj[key]; } } } newObj.default = obj; if (cache) { cache.set(obj, newObj); } return newObj; }
/**

@@ -16,0 +12,0 @@ * @typedef {{[key: string]: Function}} FuncMap

@@ -11,3 +11,2 @@ "use strict";

let codeFrameColumns = null;
try {

@@ -18,6 +17,7 @@ const nodeRequire = module && module.require;

chalk = nodeRequire.call(module, 'chalk');
} catch {// We're in a browser environment
} // frame has the form "at myMethod (location/to/my/file.js:10:2)"
} catch {
// We're in a browser environment
}
// frame has the form "at myMethod (location/to/my/file.js:10:2)"
function getCodeFrame(frame) {

@@ -30,3 +30,2 @@ const locationStart = frame.indexOf('(') + 1;

let rawFileContents = '';
try {

@@ -37,3 +36,2 @@ rawFileContents = readFileSync(filename, 'utf-8');

}
const codeFrame = codeFrameColumns(rawFileContents, {

@@ -50,6 +48,4 @@ start: {

}
function getUserCodeFrame() {
// If we couldn't load dependencies, we can't generate the user trace
/* istanbul ignore next */

@@ -59,3 +55,2 @@ if (!readFileSync || !codeFrameColumns) {

}
const err = new Error();

@@ -62,0 +57,0 @@ const firstClientCodeFrame = err.stack.split('\n').slice(1) // Remove first line which has the form "Error: TypeError"

@@ -15,3 +15,2 @@ "use strict";

exports.TEXT_NODE = TEXT_NODE;
function jestFakeTimersAreEnabled() {

@@ -21,12 +20,12 @@ /* istanbul ignore else */

if (typeof jest !== 'undefined' && jest !== null) {
return (// legacy timers
setTimeout._isMockFunction === true || // modern timers
return (
// legacy timers
setTimeout._isMockFunction === true ||
// modern timers
Object.prototype.hasOwnProperty.call(setTimeout, 'clock')
);
} // istanbul ignore next
}
// istanbul ignore next
return false;
}
function getDocument() {

@@ -37,6 +36,4 @@ /* istanbul ignore if */

}
return window.document;
}
function getWindowFromNode(node) {

@@ -65,3 +62,2 @@ if (node.defaultView) {

}
function checkContainerType(container) {

@@ -71,3 +67,2 @@ if (!container || !(typeof container.querySelector === 'function') || !(typeof container.querySelectorAll === 'function')) {

}
function getTypeName(object) {

@@ -77,5 +72,4 @@ if (typeof object === 'object') {

}
return typeof object;
}
}

@@ -60,5 +60,3 @@ "use strict";

});
var _getQueriesForElement = require("./get-queries-for-element");
Object.keys(_getQueriesForElement).forEach(function (key) {

@@ -75,5 +73,3 @@ if (key === "default" || key === "__esModule") return;

});
var queries = _interopRequireWildcard(require("./queries"));
exports.queries = queries;

@@ -91,5 +87,3 @@ Object.keys(queries).forEach(function (key) {

});
var queryHelpers = _interopRequireWildcard(require("./query-helpers"));
exports.queryHelpers = queryHelpers;

@@ -107,5 +101,3 @@ Object.keys(queryHelpers).forEach(function (key) {

});
var _waitFor = require("./wait-for");
Object.keys(_waitFor).forEach(function (key) {

@@ -122,5 +114,3 @@ if (key === "default" || key === "__esModule") return;

});
var _waitForElementToBeRemoved = require("./wait-for-element-to-be-removed");
Object.keys(_waitForElementToBeRemoved).forEach(function (key) {

@@ -137,7 +127,4 @@ if (key === "default" || key === "__esModule") return;

});
var _matches = require("./matches");
var _getNodeText = require("./get-node-text");
Object.keys(_getNodeText).forEach(function (key) {

@@ -154,5 +141,3 @@ if (key === "default" || key === "__esModule") return;

});
var _events = require("./events");
Object.keys(_events).forEach(function (key) {

@@ -169,5 +154,3 @@ if (key === "default" || key === "__esModule") return;

});
var _screen = require("./screen");
Object.keys(_screen).forEach(function (key) {

@@ -184,7 +167,4 @@ if (key === "default" || key === "__esModule") return;

});
var _roleHelpers = require("./role-helpers");
var _prettyDom = require("./pretty-dom");
Object.keys(_prettyDom).forEach(function (key) {

@@ -201,7 +181,4 @@ if (key === "default" || key === "__esModule") return;

});
var _config = require("./config");
var _suggestions = require("./suggestions");
Object.keys(_suggestions).forEach(function (key) {

@@ -218,5 +195,3 @@ if (key === "default" || key === "__esModule") return;

});
function _getRequireWildcardCache(nodeInterop) { if (typeof WeakMap !== "function") return null; var cacheBabelInterop = new WeakMap(); var cacheNodeInterop = new WeakMap(); return (_getRequireWildcardCache = function (nodeInterop) { return nodeInterop ? cacheNodeInterop : cacheBabelInterop; })(nodeInterop); }
function _interopRequireWildcard(obj, nodeInterop) { if (!nodeInterop && obj && obj.__esModule) { return obj; } if (obj === null || typeof obj !== "object" && typeof obj !== "function") { return { default: obj }; } var cache = _getRequireWildcardCache(nodeInterop); if (cache && cache.has(obj)) { return cache.get(obj); } var newObj = {}; var hasPropertyDescriptor = Object.defineProperty && Object.getOwnPropertyDescriptor; for (var key in obj) { if (key !== "default" && Object.prototype.hasOwnProperty.call(obj, key)) { var desc = hasPropertyDescriptor ? Object.getOwnPropertyDescriptor(obj, key) : null; if (desc && (desc.get || desc.set)) { Object.defineProperty(newObj, key, desc); } else { newObj[key] = obj[key]; } } } newObj.default = obj; if (cache) { cache.set(obj, newObj); } return newObj; }

@@ -9,7 +9,4 @@ "use strict";

exports.getRealLabels = getRealLabels;
var _helpers = require("./helpers");
const labelledNodeNames = ['button', 'meter', 'output', 'progress', 'select', 'textarea', 'input'];
function getTextContent(node) {

@@ -19,10 +16,7 @@ if (labelledNodeNames.includes(node.nodeName.toLowerCase())) {

}
if (node.nodeType === _helpers.TEXT_NODE) return node.textContent;
return Array.from(node.childNodes).map(childNode => getTextContent(childNode)).join('');
}
function getLabelContent(element) {
let textContent;
if (element.tagName.toLowerCase() === 'label') {

@@ -33,7 +27,6 @@ textContent = getTextContent(element);

}
return textContent;
} // Based on https://github.com/eps1lon/dom-accessibility-api/pull/352
}
// Based on https://github.com/eps1lon/dom-accessibility-api/pull/352
function getRealLabels(element) {

@@ -43,6 +36,4 @@ // eslint-disable-next-line @typescript-eslint/no-unnecessary-condition -- types are not aware of older browsers that don't implement `labels`

var _labels;
return (_labels = element.labels) != null ? _labels : [];
}
if (!isLabelable(element)) return [];

@@ -52,7 +43,5 @@ const labels = element.ownerDocument.querySelectorAll('label');

}
function isLabelable(element) {
return /BUTTON|METER|OUTPUT|PROGRESS|SELECT|TEXTAREA/.test(element.tagName) || element.tagName === 'INPUT' && element.getAttribute('type') !== 'hidden';
}
function getLabels(container, element, {

@@ -59,0 +48,0 @@ selector = '*'

@@ -10,10 +10,9 @@ "use strict";

exports.matches = matches;
function assertNotNullOrUndefined(matcher) {
if (matcher === null || matcher === undefined) {
throw new Error( // eslint-disable-next-line @typescript-eslint/restrict-template-expressions -- implicitly converting `T` to `string`
throw new Error(
// eslint-disable-next-line @typescript-eslint/restrict-template-expressions -- implicitly converting `T` to `string`
`It looks like ${matcher} was passed instead of a matcher. Did you do something like getByText(${matcher})?`);
}
}
function fuzzyMatches(textToMatch, node, matcher, normalizer) {

@@ -23,6 +22,4 @@ if (typeof textToMatch !== 'string') {

}
assertNotNullOrUndefined(matcher);
const normalizedText = normalizer(textToMatch);
if (typeof matcher === 'string' || typeof matcher === 'number') {

@@ -36,3 +33,2 @@ return normalizedText.toLowerCase().includes(matcher.toString().toLowerCase());

}
function matches(textToMatch, node, matcher, normalizer) {

@@ -42,6 +38,4 @@ if (typeof textToMatch !== 'string') {

}
assertNotNullOrUndefined(matcher);
const normalizedText = normalizer(textToMatch);
if (matcher instanceof Function) {

@@ -55,3 +49,2 @@ return matcher(normalizedText, node);

}
function getDefaultNormalizer({

@@ -68,2 +61,3 @@ trim = true,

}
/**

@@ -79,3 +73,2 @@ * Constructs a normalizer to pass to functions in matches.js

function makeNormalizer({

@@ -93,3 +86,2 @@ trim,

}
if (typeof trim !== 'undefined' || typeof collapseWhitespace !== 'undefined') {

@@ -99,9 +91,6 @@ // They've also specified a value for trim or collapseWhitespace

}
return normalizer;
}
function matchRegExp(matcher, text) {
const match = matcher.test(text);
if (matcher.global && matcher.lastIndex !== 0) {

@@ -111,4 +100,3 @@ console.warn(`To match all elements we had to reset the lastIndex of the RegExp because the global flag is enabled. We encourage to remove the global flag from the RegExp.`);

}
return match;
}
"use strict";
var _interopRequireDefault = require("@babel/runtime/helpers/interopRequireDefault");
Object.defineProperty(exports, "__esModule", {

@@ -11,30 +10,19 @@ value: true

exports.prettyFormat = void 0;
var prettyFormat = _interopRequireWildcard(require("pretty-format"));
exports.prettyFormat = prettyFormat;
var _DOMElementFilter = _interopRequireDefault(require("./DOMElementFilter"));
var _getUserCodeFrame = require("./get-user-code-frame");
var _helpers = require("./helpers");
var _config = require("./config");
function _getRequireWildcardCache(nodeInterop) { if (typeof WeakMap !== "function") return null; var cacheBabelInterop = new WeakMap(); var cacheNodeInterop = new WeakMap(); return (_getRequireWildcardCache = function (nodeInterop) { return nodeInterop ? cacheNodeInterop : cacheBabelInterop; })(nodeInterop); }
function _interopRequireWildcard(obj, nodeInterop) { if (!nodeInterop && obj && obj.__esModule) { return obj; } if (obj === null || typeof obj !== "object" && typeof obj !== "function") { return { default: obj }; } var cache = _getRequireWildcardCache(nodeInterop); if (cache && cache.has(obj)) { return cache.get(obj); } var newObj = {}; var hasPropertyDescriptor = Object.defineProperty && Object.getOwnPropertyDescriptor; for (var key in obj) { if (key !== "default" && Object.prototype.hasOwnProperty.call(obj, key)) { var desc = hasPropertyDescriptor ? Object.getOwnPropertyDescriptor(obj, key) : null; if (desc && (desc.get || desc.set)) { Object.defineProperty(newObj, key, desc); } else { newObj[key] = obj[key]; } } } newObj.default = obj; if (cache) { cache.set(obj, newObj); } return newObj; }
const shouldHighlight = () => {
let colors;
try {
var _process, _process$env;
colors = JSON.parse((_process = process) == null ? void 0 : (_process$env = _process.env) == null ? void 0 : _process$env.COLORS);
} catch (e) {// If this throws, process?.env?.COLORS wasn't parsable. Since we only
} catch (e) {
// If this throws, process?.env?.COLORS wasn't parsable. Since we only
// care about `true` or `false`, we can safely ignore the error.
}
if (typeof colors === 'boolean') {

@@ -48,14 +36,14 @@ // If `colors` is set explicitly (both `true` and `false`), use that value.

};
const {
DOMCollection
} = prettyFormat.plugins; // https://developer.mozilla.org/en-US/docs/Web/API/Node/nodeType#node_type_constants
} = prettyFormat.plugins;
// https://developer.mozilla.org/en-US/docs/Web/API/Node/nodeType#node_type_constants
const ELEMENT_NODE = 1;
const COMMENT_NODE = 8; // https://github.com/facebook/jest/blob/615084195ae1ae61ddd56162c62bbdda17587569/packages/pretty-format/src/plugins/DOMElement.ts#L50
const COMMENT_NODE = 8;
// https://github.com/facebook/jest/blob/615084195ae1ae61ddd56162c62bbdda17587569/packages/pretty-format/src/plugins/DOMElement.ts#L50
function filterCommentsAndDefaultIgnoreTagsTags(value) {
return value.nodeType !== COMMENT_NODE && (value.nodeType !== ELEMENT_NODE || !value.matches((0, _config.getConfig)().defaultIgnore));
}
function prettyDOM(dom, maxLength, options = {}) {

@@ -65,17 +53,12 @@ if (!dom) {

}
if (typeof maxLength !== 'number') {
maxLength = typeof process !== 'undefined' && process.env.DEBUG_PRINT_LIMIT || 7000;
}
if (maxLength === 0) {
return '';
}
if (dom.documentElement) {
dom = dom.documentElement;
}
let domTypeName = typeof dom;
if (domTypeName === 'object') {

@@ -87,7 +70,5 @@ domTypeName = dom.constructor.name;

}
if (!('outerHTML' in dom)) {
throw new TypeError(`Expected an element or document but got ${domTypeName}`);
}
const {

@@ -105,6 +86,4 @@ filterNode = filterCommentsAndDefaultIgnoreTagsTags,

}
const logDOM = (...args) => {
const userCodeFrame = (0, _getUserCodeFrame.getUserCodeFrame)();
if (userCodeFrame) {

@@ -116,3 +95,2 @@ console.log(`${prettyDOM(...args)}\n\n${userCodeFrame}`);

};
exports.logDOM = logDOM;

@@ -6,5 +6,3 @@ "use strict";

});
var _matches = require("../matches");
Object.keys(_matches).forEach(function (key) {

@@ -20,5 +18,3 @@ if (key === "default" || key === "__esModule") return;

});
var _getNodeText = require("../get-node-text");
Object.keys(_getNodeText).forEach(function (key) {

@@ -34,5 +30,3 @@ if (key === "default" || key === "__esModule") return;

});
var _queryHelpers = require("../query-helpers");
Object.keys(_queryHelpers).forEach(function (key) {

@@ -48,5 +42,3 @@ if (key === "default" || key === "__esModule") return;

});
var _config = require("../config");
Object.keys(_config).forEach(function (key) {

@@ -53,0 +45,0 @@ if (key === "default" || key === "__esModule") return;

@@ -7,12 +7,7 @@ "use strict";

exports.queryByAltText = exports.queryAllByAltText = exports.getByAltText = exports.getAllByAltText = exports.findByAltText = exports.findAllByAltText = void 0;
var _queryHelpers = require("../query-helpers");
var _helpers = require("../helpers");
var _allUtils = require("./all-utils");
// Valid tags are img, input, area and custom elements
const VALID_TAG_REGEXP = /^(img|input|area|.+-.+)$/i;
const queryAllByAltText = (container, alt, options = {}) => {

@@ -22,7 +17,4 @@ (0, _helpers.checkContainerType)(container);

};
const getMultipleError = (c, alt) => `Found multiple elements with the alt text: ${alt}`;
const getMissingError = (c, alt) => `Unable to find an element with the alt text: ${alt}`;
const queryAllByAltTextWithSuggestions = (0, _queryHelpers.wrapAllByQueryWithSuggestion)(queryAllByAltText, queryAllByAltText.name, 'queryAll');

@@ -29,0 +21,0 @@ exports.queryAllByAltText = queryAllByAltTextWithSuggestions;

@@ -7,9 +7,5 @@ "use strict";

exports.queryByDisplayValue = exports.queryAllByDisplayValue = exports.getByDisplayValue = exports.getAllByDisplayValue = exports.findByDisplayValue = exports.findAllByDisplayValue = void 0;
var _queryHelpers = require("../query-helpers");
var _helpers = require("../helpers");
var _allUtils = require("./all-utils");
const queryAllByDisplayValue = (container, value, {

@@ -37,7 +33,4 @@ exact = true,

};
const getMultipleError = (c, value) => `Found multiple elements with the display value: ${value}.`;
const getMissingError = (c, value) => `Unable to find an element with the display value: ${value}.`;
const queryAllByDisplayValueWithSuggestions = (0, _queryHelpers.wrapAllByQueryWithSuggestion)(queryAllByDisplayValue, queryAllByDisplayValue.name, 'queryAll');

@@ -44,0 +37,0 @@ exports.queryAllByDisplayValue = queryAllByDisplayValueWithSuggestions;

@@ -6,5 +6,3 @@ "use strict";

});
var _labelText = require("./label-text");
Object.keys(_labelText).forEach(function (key) {

@@ -20,5 +18,3 @@ if (key === "default" || key === "__esModule") return;

});
var _placeholderText = require("./placeholder-text");
Object.keys(_placeholderText).forEach(function (key) {

@@ -34,5 +30,3 @@ if (key === "default" || key === "__esModule") return;

});
var _text = require("./text");
Object.keys(_text).forEach(function (key) {

@@ -48,5 +42,3 @@ if (key === "default" || key === "__esModule") return;

});
var _displayValue = require("./display-value");
Object.keys(_displayValue).forEach(function (key) {

@@ -62,5 +54,3 @@ if (key === "default" || key === "__esModule") return;

});
var _altText = require("./alt-text");
Object.keys(_altText).forEach(function (key) {

@@ -76,5 +66,3 @@ if (key === "default" || key === "__esModule") return;

});
var _title = require("./title");
Object.keys(_title).forEach(function (key) {

@@ -90,5 +78,3 @@ if (key === "default" || key === "__esModule") return;

});
var _role = require("./role");
Object.keys(_role).forEach(function (key) {

@@ -104,5 +90,3 @@ if (key === "default" || key === "__esModule") return;

});
var _testId = require("./test-id");
Object.keys(_testId).forEach(function (key) {

@@ -109,0 +93,0 @@ if (key === "default" || key === "__esModule") return;

@@ -7,11 +7,6 @@ "use strict";

exports.queryByLabelText = exports.queryAllByLabelText = exports.getByLabelText = exports.getAllByLabelText = exports.findByLabelText = exports.findAllByLabelText = void 0;
var _config = require("../config");
var _helpers = require("../helpers");
var _labelHelpers = require("../label-helpers");
var _allUtils = require("./all-utils");
function queryAllLabels(container) {

@@ -27,3 +22,2 @@ return Array.from(container.querySelectorAll('label,input')).map(node => {

}
const queryAllLabelsByText = (container, text, {

@@ -49,3 +43,2 @@ exact = true,

};
const queryAllByLabelText = (container, text, {

@@ -76,3 +69,2 @@ selector = '*',

if (matcher(labelsValue.join(' '), labelledElement, text, matchNormalizer)) labelledElements.push(labelledElement);
if (labelsValue.length > 1) {

@@ -83,3 +75,2 @@ labelsValue.forEach((labelValue, index) => {

labelsFiltered.splice(index, 1);
if (labelsFiltered.length > 1) {

@@ -90,3 +81,2 @@ if (matcher(labelsFiltered.join(' '), labelledElement, text, matchNormalizer)) labelledElements.push(labelledElement);

}
return labelledElements;

@@ -98,3 +88,5 @@ }, []).concat((0, _allUtils.queryAllByAttribute)('aria-label', container, text, {

return Array.from(new Set(matchingLabelledElements)).filter(element => element.matches(selector));
}; // the getAll* query would normally look like this:
};
// the getAll* query would normally look like this:
// const getAllByLabelText = makeGetAllQuery(

@@ -106,13 +98,8 @@ // queryAllByLabelText,

// so we're writing this one out by hand.
const getAllByLabelText = (container, text, ...rest) => {
const els = queryAllByLabelText(container, text, ...rest);
if (!els.length) {
const labels = queryAllLabelsByText(container, text, ...rest);
if (labels.length) {
const tagNames = labels.map(label => getTagNameOfElementAssociatedWithLabelViaFor(container, label)).filter(tagName => !!tagName);
if (tagNames.length) {

@@ -127,20 +114,15 @@ throw (0, _config.getConfig)().getElementError(tagNames.map(tagName => `Found a label with the text of: ${text}, however the element associated with this label (<${tagName} />) is non-labellable [https://html.spec.whatwg.org/multipage/forms.html#category-label]. If you really need to label a <${tagName} />, you can use aria-label or aria-labelledby instead.`).join('\n\n'), container);

}
return els;
};
function getTagNameOfElementAssociatedWithLabelViaFor(container, label) {
const htmlFor = label.getAttribute('for');
if (!htmlFor) {
return null;
}
const element = container.querySelector(`[id="${htmlFor}"]`);
return element ? element.tagName.toLowerCase() : null;
} // the reason mentioned above is the same reason we're not using buildQueries
}
// the reason mentioned above is the same reason we're not using buildQueries
const getMultipleError = (c, text) => `Found multiple elements with the text of: ${text}`;
const queryByLabelText = (0, _allUtils.wrapSingleQueryWithSuggestion)((0, _allUtils.makeSingleQuery)(queryAllByLabelText, getMultipleError), queryAllByLabelText.name, 'query');

@@ -147,0 +129,0 @@ exports.queryByLabelText = queryByLabelText;

@@ -7,9 +7,5 @@ "use strict";

exports.queryByPlaceholderText = exports.queryAllByPlaceholderText = exports.getByPlaceholderText = exports.getAllByPlaceholderText = exports.findByPlaceholderText = exports.findAllByPlaceholderText = void 0;
var _queryHelpers = require("../query-helpers");
var _helpers = require("../helpers");
var _allUtils = require("./all-utils");
const queryAllByPlaceholderText = (...args) => {

@@ -19,7 +15,4 @@ (0, _helpers.checkContainerType)(args[0]);

};
const getMultipleError = (c, text) => `Found multiple elements with the placeholder text of: ${text}`;
const getMissingError = (c, text) => `Unable to find an element with the placeholder text of: ${text}`;
const queryAllByPlaceholderTextWithSuggestions = (0, _queryHelpers.wrapAllByQueryWithSuggestion)(queryAllByPlaceholderText, queryAllByPlaceholderText.name, 'queryAll');

@@ -26,0 +19,0 @@ exports.queryAllByPlaceholderText = queryAllByPlaceholderTextWithSuggestions;

@@ -7,15 +7,8 @@ "use strict";

exports.queryByRole = exports.queryAllByRole = exports.getByRole = exports.getAllByRole = exports.findByRole = exports.findAllByRole = void 0;
var _domAccessibilityApi = require("dom-accessibility-api");
var _ariaQuery = require("aria-query");
var _roleHelpers = require("../role-helpers");
var _queryHelpers = require("../query-helpers");
var _helpers = require("../helpers");
var _allUtils = require("./all-utils");
function queryAllByRole(container, role, {

@@ -44,6 +37,4 @@ exact = true,

});
if (selected !== undefined) {
var _allRoles$get;
// guard against unknown roles

@@ -54,6 +45,4 @@ if (((_allRoles$get = _ariaQuery.roles.get(role)) == null ? void 0 : _allRoles$get.props['aria-selected']) === undefined) {

}
if (checked !== undefined) {
var _allRoles$get2;
// guard against unknown roles

@@ -64,6 +53,4 @@ if (((_allRoles$get2 = _ariaQuery.roles.get(role)) == null ? void 0 : _allRoles$get2.props['aria-checked']) === undefined) {

}
if (pressed !== undefined) {
var _allRoles$get3;
// guard against unknown roles

@@ -74,6 +61,4 @@ if (((_allRoles$get3 = _ariaQuery.roles.get(role)) == null ? void 0 : _allRoles$get3.props['aria-pressed']) === undefined) {

}
if (current !== undefined) {
var _allRoles$get4;
/* istanbul ignore next */

@@ -87,3 +72,2 @@ // guard against unknown roles

}
if (level !== undefined) {

@@ -95,6 +79,4 @@ // guard against using `level` option with any role other than `heading`

}
if (expanded !== undefined) {
var _allRoles$get5;
// guard against unknown roles

@@ -105,5 +87,3 @@ if (((_allRoles$get5 = _ariaQuery.roles.get(role)) == null ? void 0 : _allRoles$get5.props['aria-expanded']) === undefined) {

}
const subtreeIsInaccessibleCache = new WeakMap();
function cachedIsSubtreeInaccessible(element) {

@@ -113,27 +93,21 @@ if (!subtreeIsInaccessibleCache.has(element)) {

}
return subtreeIsInaccessibleCache.get(element);
}
return Array.from(container.querySelectorAll( // Only query elements that can be matched by the following filters
return Array.from(container.querySelectorAll(
// Only query elements that can be matched by the following filters
makeRoleSelector(role, exact, normalizer ? matchNormalizer : undefined))).filter(node => {
const isRoleSpecifiedExplicitly = node.hasAttribute('role');
if (isRoleSpecifiedExplicitly) {
const roleValue = node.getAttribute('role');
if (queryFallbacks) {
return roleValue.split(' ').filter(Boolean).some(text => matcher(text, node, role, matchNormalizer));
} // if a custom normalizer is passed then let normalizer handle the role value
}
// if a custom normalizer is passed then let normalizer handle the role value
if (normalizer) {
return matcher(roleValue, node, role, matchNormalizer);
} // other wise only send the first word to match
}
// other wise only send the first word to match
const [firstWord] = roleValue.split(' ');
return matcher(firstWord, node, role, matchNormalizer);
}
const implicitRoles = (0, _roleHelpers.getImplicitAriaRoles)(node);

@@ -145,24 +119,18 @@ return implicitRoles.some(implicitRole => matcher(implicitRole, node, role, matchNormalizer));

}
if (checked !== undefined) {
return checked === (0, _roleHelpers.computeAriaChecked)(element);
}
if (pressed !== undefined) {
return pressed === (0, _roleHelpers.computeAriaPressed)(element);
}
if (current !== undefined) {
return current === (0, _roleHelpers.computeAriaCurrent)(element);
}
if (expanded !== undefined) {
return expanded === (0, _roleHelpers.computeAriaExpanded)(element);
}
if (level !== undefined) {
return level === (0, _roleHelpers.computeHeadingLevel)(element);
} // don't care if aria attributes are unspecified
}
// don't care if aria attributes are unspecified
return true;

@@ -174,3 +142,2 @@ }).filter(element => {

}
return (0, _allUtils.matches)((0, _domAccessibilityApi.computeAccessibleName)(element, {

@@ -184,3 +151,2 @@ computedStyleSupportsPseudoElements: (0, _allUtils.getConfig)().computedStyleSupportsPseudoElements

}
return (0, _allUtils.matches)((0, _domAccessibilityApi.computeAccessibleDescription)(element, {

@@ -195,6 +161,4 @@ computedStyleSupportsPseudoElements: (0, _allUtils.getConfig)().computedStyleSupportsPseudoElements

}
function makeRoleSelector(role, exact, customNormalizer) {
var _roleElements$get;
if (typeof role !== 'string') {

@@ -204,3 +168,2 @@ // For non-string role parameters we can not determine the implicitRoleSelectors.

}
const explicitRoleSelector = exact && !customNormalizer ? `*[role~="${role}"]` : '*[role]';

@@ -210,12 +173,11 @@ const roleRelations = (_roleElements$get = _ariaQuery.roleElements.get(role)) != null ? _roleElements$get : new Set();

name
}) => name)); // Current transpilation config sometimes assumes `...` is always applied to arrays.
}) => name));
// Current transpilation config sometimes assumes `...` is always applied to arrays.
// `...` is equivalent to `Array.prototype.concat` for arrays.
// If you replace this code with `[explicitRoleSelector, ...implicitRoleSelectors]`, make sure every transpilation target retains the `...` in favor of `Array.prototype.concat`.
return [explicitRoleSelector].concat(Array.from(implicitRoleSelectors)).join(',');
}
const getNameHint = name => {
let nameHint = '';
if (name === undefined) {

@@ -228,6 +190,4 @@ nameHint = '';

}
return nameHint;
};
const getMultipleError = (c, role, {

@@ -238,3 +198,2 @@ name

};
const getMissingError = (container, role, {

@@ -248,3 +207,2 @@ hidden = (0, _allUtils.getConfig)().defaultHidden,

}
let roles = '';

@@ -258,3 +216,2 @@ Array.from(container.children).forEach(childElement => {

let roleMessage;
if (roles.length === 0) {

@@ -273,5 +230,3 @@ if (hidden === false) {

}
let nameHint = '';
if (name === undefined) {

@@ -284,5 +239,3 @@ nameHint = '';

}
let descriptionHint = '';
if (description === undefined) {

@@ -295,3 +248,2 @@ descriptionHint = '';

}
return `

@@ -302,3 +254,2 @@ Unable to find an ${hidden === false ? 'accessible ' : ''}element with the role "${role}"${nameHint}${descriptionHint}

};
const queryAllByRoleWithSuggestions = (0, _queryHelpers.wrapAllByQueryWithSuggestion)(queryAllByRole, queryAllByRole.name, 'queryAll');

@@ -305,0 +256,0 @@ exports.queryAllByRole = queryAllByRoleWithSuggestions;

@@ -7,11 +7,6 @@ "use strict";

exports.queryByTestId = exports.queryAllByTestId = exports.getByTestId = exports.getAllByTestId = exports.findByTestId = exports.findAllByTestId = void 0;
var _helpers = require("../helpers");
var _queryHelpers = require("../query-helpers");
var _allUtils = require("./all-utils");
const getTestIdAttribute = () => (0, _allUtils.getConfig)().testIdAttribute;
const queryAllByTestId = (...args) => {

@@ -21,7 +16,4 @@ (0, _helpers.checkContainerType)(args[0]);

};
const getMultipleError = (c, id) => `Found multiple elements by: [${getTestIdAttribute()}="${id}"]`;
const getMissingError = (c, id) => `Unable to find an element by: [${getTestIdAttribute()}="${id}"]`;
const queryAllByTestIdWithSuggestions = (0, _queryHelpers.wrapAllByQueryWithSuggestion)(queryAllByTestId, queryAllByTestId.name, 'queryAll');

@@ -28,0 +20,0 @@ exports.queryAllByTestId = queryAllByTestIdWithSuggestions;

@@ -7,9 +7,5 @@ "use strict";

exports.queryByText = exports.queryAllByText = exports.getByText = exports.getAllByText = exports.findByText = exports.findAllByText = void 0;
var _queryHelpers = require("../query-helpers");
var _helpers = require("../helpers");
var _allUtils = require("./all-utils");
const queryAllByText = (container, text, {

@@ -31,13 +27,10 @@ selector = '*',

let baseArray = [];
if (typeof container.matches === 'function' && container.matches(selector)) {
baseArray = [container];
}
return [...baseArray, ...Array.from(container.querySelectorAll(selector))] // TODO: `matches` according lib.dom.d.ts can get only `string` but according our code it can handle also boolean :)
return [...baseArray, ...Array.from(container.querySelectorAll(selector))]
// TODO: `matches` according lib.dom.d.ts can get only `string` but according our code it can handle also boolean :)
.filter(node => !ignore || !node.matches(ignore)).filter(node => matcher((0, _allUtils.getNodeText)(node), node, text, matchNormalizer));
};
const getMultipleError = (c, text) => `Found multiple elements with the text: ${text}`;
const getMissingError = (c, text, options = {}) => {

@@ -60,3 +53,2 @@ const {

};
const queryAllByTextWithSuggestions = (0, _queryHelpers.wrapAllByQueryWithSuggestion)(queryAllByText, queryAllByText.name, 'queryAll');

@@ -63,0 +55,0 @@ exports.queryAllByText = queryAllByTextWithSuggestions;

@@ -7,15 +7,9 @@ "use strict";

exports.queryByTitle = exports.queryAllByTitle = exports.getByTitle = exports.getAllByTitle = exports.findByTitle = exports.findAllByTitle = void 0;
var _queryHelpers = require("../query-helpers");
var _helpers = require("../helpers");
var _allUtils = require("./all-utils");
const isSvgTitle = node => {
var _node$parentElement;
return node.tagName.toLowerCase() === 'title' && ((_node$parentElement = node.parentElement) == null ? void 0 : _node$parentElement.tagName.toLowerCase()) === 'svg';
};
const queryAllByTitle = (container, text, {

@@ -36,7 +30,4 @@ exact = true,

};
const getMultipleError = (c, title) => `Found multiple elements with the title: ${title}.`;
const getMissingError = (c, title) => `Unable to find an element with the title: ${title}.`;
const queryAllByTitleWithSuggestions = (0, _queryHelpers.wrapAllByQueryWithSuggestion)(queryAllByTitle, queryAllByTitle.name, 'queryAll');

@@ -43,0 +34,0 @@ exports.queryAllByTitle = queryAllByTitleWithSuggestions;

@@ -15,19 +15,12 @@ "use strict";

exports.wrapSingleQueryWithSuggestion = exports.wrapAllByQueryWithSuggestion = void 0;
var _suggestions = require("./suggestions");
var _matches = require("./matches");
var _waitFor = require("./wait-for");
var _config = require("./config");
function getElementError(message, container) {
return (0, _config.getConfig)().getElementError(message, container);
}
function getMultipleElementsFoundError(message, container) {
return getElementError(`${message}\n\n(If this is intentional, then use the \`*AllBy*\` variant of the query (like \`queryAllByText\`, \`getAllByText\`, or \`findAllByText\`)).`, container);
}
function queryAllByAttribute(attribute, container, text, {

@@ -47,20 +40,16 @@ exact = true,

}
function queryByAttribute(attribute, container, text, options) {
const els = queryAllByAttribute(attribute, container, text, options);
if (els.length > 1) {
throw getMultipleElementsFoundError(`Found multiple elements by [${attribute}=${text}]`, container);
}
return els[0] || null;
}
return els[0] || null;
} // this accepts a query function and returns a function which throws an error
// this accepts a query function and returns a function which throws an error
// if more than one elements is returned, otherwise it returns the first
// element or null
function makeSingleQuery(allQuery, getMultipleError) {
return (container, ...args) => {
const els = allQuery(container, ...args);
if (els.length > 1) {

@@ -74,7 +63,5 @@ const elementStrings = els.map(element => getElementError(null, element).message).join('\n\n');

}
return els[0] || null;
};
}
function getSuggestionError(suggestion, container) {

@@ -84,20 +71,18 @@ return (0, _config.getConfig)().getElementError(`A better query is available, try this:

`, container);
} // this accepts a query function and returns a function which throws an error
}
// this accepts a query function and returns a function which throws an error
// if an empty list of elements is returned
function makeGetAllQuery(allQuery, getMissingError) {
return (container, ...args) => {
const els = allQuery(container, ...args);
if (!els.length) {
throw (0, _config.getConfig)().getElementError(getMissingError(container, ...args), container);
}
return els;
};
} // this accepts a getter query function and returns a function which calls
}
// this accepts a getter query function and returns a function which calls
// waitFor and passing a function which invokes the getter.
function makeFindQuery(getter) {

@@ -113,3 +98,2 @@ return (container, text, options, waitForOptions) => {

}
const wrapSingleQueryWithSuggestion = (query, queryAllByName, variant) => (container, ...args) => {

@@ -120,6 +104,4 @@ const element = query(container, ...args);

} = {}] = args.slice(-1);
if (element && suggest) {
const suggestion = (0, _suggestions.getSuggestedQuery)(element, variant);
if (suggestion && !queryAllByName.endsWith(suggestion.queryName)) {

@@ -129,8 +111,5 @@ throw getSuggestionError(suggestion.toString(), container);

}
return element;
};
exports.wrapSingleQueryWithSuggestion = wrapSingleQueryWithSuggestion;
const wrapAllByQueryWithSuggestion = (query, queryAllByName, variant) => (container, ...args) => {

@@ -141,3 +120,2 @@ const els = query(container, ...args);

} = {}] = args.slice(-1);
if (els.length && suggest) {

@@ -148,8 +126,8 @@ // get a unique list of all suggestion messages. We are only going to make a suggestion if

var _getSuggestedQuery;
return (_getSuggestedQuery = (0, _suggestions.getSuggestedQuery)(element, variant)) == null ? void 0 : _getSuggestedQuery.toString();
}))];
if ( // only want to suggest if all the els have the same suggestion.
uniqueSuggestionMessages.length === 1 && !queryAllByName.endsWith( // eslint-disable-next-line @typescript-eslint/no-non-null-assertion -- TODO: Can this be null at runtime?
if (
// only want to suggest if all the els have the same suggestion.
uniqueSuggestionMessages.length === 1 && !queryAllByName.endsWith(
// eslint-disable-next-line @typescript-eslint/no-non-null-assertion -- TODO: Can this be null at runtime?
(0, _suggestions.getSuggestedQuery)(els[0], variant).queryName)) {

@@ -159,11 +137,9 @@ throw getSuggestionError(uniqueSuggestionMessages[0], container);

}
return els;
};
return els;
}; // TODO: This deviates from the published declarations
// TODO: This deviates from the published declarations
// However, the implementation always required a dyadic (after `container`) not variadic `queryAllBy` considering the implementation of `makeFindQuery`
// This is at least statically true and can be verified by accepting `QueryMethod<Arguments, HTMLElement[]>`
exports.wrapAllByQueryWithSuggestion = wrapAllByQueryWithSuggestion;
function buildQueries(queryAllBy, getMultipleError, getMissingError) {

@@ -170,0 +146,0 @@ const queryBy = wrapSingleQueryWithSuggestion(makeSingleQuery(queryAllBy, getMultipleError), queryAllBy.name, 'query');

@@ -18,12 +18,8 @@ "use strict";

exports.prettyRoles = prettyRoles;
var _ariaQuery = require("aria-query");
var _domAccessibilityApi = require("dom-accessibility-api");
var _prettyDom = require("./pretty-dom");
var _config = require("./config");
const elementRoleList = buildElementRoleList(_ariaQuery.elementRoles);
const elementRoleList = buildElementRoleList(_ariaQuery.elementRoles);
/**

@@ -33,3 +29,2 @@ * @param {Element} element -

*/
function isSubtreeInaccessible(element) {

@@ -39,15 +34,12 @@ if (element.hidden === true) {

}
if (element.getAttribute('aria-hidden') === 'true') {
return true;
}
const window = element.ownerDocument.defaultView;
if (window.getComputedStyle(element).display === 'none') {
return true;
}
return false;
}
/**

@@ -67,4 +59,2 @@ * Partial implementation https://www.w3.org/TR/wai-aria-1.2/#tree_exclusion

*/
function isInaccessible(element, options = {}) {

@@ -74,10 +64,8 @@ const {

} = options;
const window = element.ownerDocument.defaultView; // since visibility is inherited we can exit early
const window = element.ownerDocument.defaultView;
// since visibility is inherited we can exit early
if (window.getComputedStyle(element).visibility === 'hidden') {
return true;
}
let currentElement = element;
while (currentElement) {

@@ -87,9 +75,6 @@ if (isSubtreeInaccessibleImpl(currentElement)) {

}
currentElement = currentElement.parentElement;
}
return false;
}
function getImplicitAriaRoles(currentNode) {

@@ -106,6 +91,4 @@ // eslint bug here:

}
return [];
}
function buildElementRoleList(elementRolesMap) {

@@ -122,3 +105,2 @@ function makeElementSelector({

const shouldNotExist = constraints.indexOf('undefined') !== -1;
if (shouldNotExist) {

@@ -133,3 +115,2 @@ return `:not([${attributeName}])`;

}
function getSelectorSpecificity({

@@ -140,3 +121,2 @@ attributes = []

}
function bySelectorSpecificity({

@@ -149,10 +129,9 @@ specificity: leftSpecificity

}
function match(element) {
let {
attributes = []
} = element; // https://github.com/testing-library/dom-testing-library/issues/814
} = element;
// https://github.com/testing-library/dom-testing-library/issues/814
const typeTextIndex = attributes.findIndex(attribute => attribute.value && attribute.name === 'type' && attribute.value === 'text');
if (typeTextIndex >= 0) {

@@ -162,4 +141,4 @@ // not using splice to not mutate the attributes array

}
const selector = makeElementSelector({ ...element,
const selector = makeElementSelector({
...element,
attributes

@@ -171,10 +150,9 @@ });

}
return node.matches(selector);
};
}
let result = [];
let result = []; // eslint bug here:
// eslint bug here:
// eslint-disable-next-line no-unused-vars
for (const [element, roles] of elementRolesMap.entries()) {

@@ -187,6 +165,4 @@ result = [...result, {

}
return result.sort(bySelectorSpecificity);
}
function getRoles(container, {

@@ -198,8 +174,7 @@ hidden = false

}
return flattenDOM(container).filter(element => {
return hidden === false ? isInaccessible(element) === false : true;
}).reduce((acc, node) => {
let roles = []; // TODO: This violates html-aria which does not allow any role on every element
let roles = [];
// TODO: This violates html-aria which does not allow any role on every element
if (node.hasAttribute('role')) {

@@ -210,6 +185,7 @@ roles = node.getAttribute('role').split(' ').slice(0, 1);

}
return roles.reduce((rolesAcc, role) => Array.isArray(rolesAcc[role]) ? { ...rolesAcc,
return roles.reduce((rolesAcc, role) => Array.isArray(rolesAcc[role]) ? {
...rolesAcc,
[role]: [...rolesAcc[role], node]
} : { ...rolesAcc,
} : {
...rolesAcc,
[role]: [node]

@@ -219,3 +195,2 @@ }, acc);

}
function prettyRoles(dom, {

@@ -227,4 +202,4 @@ hidden,

hidden
}); // We prefer to skip generic role, we don't recommend it
});
// We prefer to skip generic role, we don't recommend it
return Object.entries(roles).filter(([role]) => role !== 'generic').map(([role, elements]) => {

@@ -237,3 +212,2 @@ const delimiterBar = '-'.repeat(50);

const domString = (0, _prettyDom.prettyDOM)(el.cloneNode(false));
if (includeDescription) {

@@ -245,3 +219,2 @@ const descriptionString = `Description "${(0, _domAccessibilityApi.computeAccessibleDescription)(el, {

}
return `${nameString}${domString}`;

@@ -252,3 +225,2 @@ }).join('\n\n');

}
const logRoles = (dom, {

@@ -259,2 +231,3 @@ hidden = false

}));
/**

@@ -264,6 +237,3 @@ * @param {Element} element -

*/
exports.logRoles = logRoles;
function computeAriaSelected(element) {

@@ -274,7 +244,8 @@ // implicit value from html-aam mappings: https://www.w3.org/TR/html-aam-1.0/#html-attribute-state-and-property-mappings

return element.selected;
} // explicit value
}
// explicit value
return checkBooleanAttribute(element, 'aria-selected');
}
/**

@@ -284,4 +255,2 @@ * @param {Element} element -

*/
function computeAriaChecked(element) {

@@ -294,10 +263,10 @@ // implicit value from html-aam mappings: https://www.w3.org/TR/html-aam-1.0/#html-attribute-state-and-property-mappings

}
if ('checked' in element) {
return element.checked;
} // explicit value
}
// explicit value
return checkBooleanAttribute(element, 'aria-checked');
}
/**

@@ -307,4 +276,2 @@ * @param {Element} element -

*/
function computeAriaPressed(element) {

@@ -314,2 +281,3 @@ // https://www.w3.org/TR/wai-aria-1.1/#aria-pressed

}
/**

@@ -319,10 +287,8 @@ * @param {Element} element -

*/
function computeAriaCurrent(element) {
var _ref, _checkBooleanAttribut;
// https://www.w3.org/TR/wai-aria-1.1/#aria-current
return (_ref = (_checkBooleanAttribut = checkBooleanAttribute(element, 'aria-current')) != null ? _checkBooleanAttribut : element.getAttribute('aria-current')) != null ? _ref : false;
}
/**

@@ -332,4 +298,2 @@ * @param {Element} element -

*/
function computeAriaExpanded(element) {

@@ -339,16 +303,13 @@ // https://www.w3.org/TR/wai-aria-1.1/#aria-expanded

}
function checkBooleanAttribute(element, attribute) {
const attributeValue = element.getAttribute(attribute);
if (attributeValue === 'true') {
return true;
}
if (attributeValue === 'false') {
return false;
}
return undefined;
}
/**

@@ -358,4 +319,2 @@ * @param {Element} element -

*/
function computeHeadingLevel(element) {

@@ -371,7 +330,7 @@ // https://w3c.github.io/html-aam/#el-h1-h6

H6: 6
}; // explicit aria-level value
};
// explicit aria-level value
// https://www.w3.org/TR/wai-aria-1.2/#aria-level
const ariaLevelAttribute = element.getAttribute('aria-level') && Number(element.getAttribute('aria-level'));
return ariaLevelAttribute || implicitHeadingLevels[element.tagName];
}
"use strict";
var _interopRequireDefault = require("@babel/runtime/helpers/interopRequireDefault");
Object.defineProperty(exports, "__esModule", {

@@ -9,19 +8,12 @@ value: true

exports.screen = void 0;
var _lzString = _interopRequireDefault(require("lz-string"));
var _getQueriesForElement = require("./get-queries-for-element");
var _helpers = require("./helpers");
var _prettyDom = require("./pretty-dom");
var queries = _interopRequireWildcard(require("./queries"));
function _getRequireWildcardCache(nodeInterop) { if (typeof WeakMap !== "function") return null; var cacheBabelInterop = new WeakMap(); var cacheNodeInterop = new WeakMap(); return (_getRequireWildcardCache = function (nodeInterop) { return nodeInterop ? cacheNodeInterop : cacheBabelInterop; })(nodeInterop); }
function _interopRequireWildcard(obj, nodeInterop) { if (!nodeInterop && obj && obj.__esModule) { return obj; } if (obj === null || typeof obj !== "object" && typeof obj !== "function") { return { default: obj }; } var cache = _getRequireWildcardCache(nodeInterop); if (cache && cache.has(obj)) { return cache.get(obj); } var newObj = {}; var hasPropertyDescriptor = Object.defineProperty && Object.getOwnPropertyDescriptor; for (var key in obj) { if (key !== "default" && Object.prototype.hasOwnProperty.call(obj, key)) { var desc = hasPropertyDescriptor ? Object.getOwnPropertyDescriptor(obj, key) : null; if (desc && (desc.get || desc.set)) { Object.defineProperty(newObj, key, desc); } else { newObj[key] = obj[key]; } } } newObj.default = obj; if (cache) { cache.set(obj, newObj); } return newObj; }
// WARNING: `lz-string` only has a default export but statically we assume named exports are allowd
// TODO: Statically verify we don't rely on NodeJS implicit named imports.
function unindent(string) {

@@ -32,13 +24,9 @@ // remove white spaces first, to save a few bytes.

}
function encode(value) {
return _lzString.default.compressToEncodedURIComponent(unindent(value));
}
function getPlaygroundUrl(markup) {
return `https://testing-playground.com/#markup=${encode(markup)}`;
}
const debug = (element, maxLength, options) => Array.isArray(element) ? element.forEach(el => (0, _prettyDom.logDOM)(el, maxLength, options)) : (0, _prettyDom.logDOM)(element, maxLength, options);
const logTestingPlaygroundURL = (element = (0, _helpers.getDocument)().body) => {

@@ -49,5 +37,4 @@ // eslint-disable-next-line @typescript-eslint/no-unnecessary-condition

return;
} // eslint-disable-next-line @typescript-eslint/no-unnecessary-condition
}
// eslint-disable-next-line @typescript-eslint/no-unnecessary-condition
if (!element.innerHTML) {

@@ -57,3 +44,2 @@ console.log(`The provided element doesn't have any children.`);

}
const playgroundUrl = getPlaygroundUrl(element.innerHTML);

@@ -63,3 +49,2 @@ console.log(`Open this URL in your browser\n\n${playgroundUrl}`);

};
const initialValue = {

@@ -77,5 +62,4 @@ debug,

};
return helpers;
}, initialValue);
exports.screen = screen;

@@ -7,17 +7,9 @@ "use strict";

exports.getSuggestedQuery = getSuggestedQuery;
var _domAccessibilityApi = require("dom-accessibility-api");
var _matches = require("./matches");
var _getNodeText = require("./get-node-text");
var _config = require("./config");
var _roleHelpers = require("./role-helpers");
var _labelHelpers = require("./label-helpers");
const normalize = (0, _matches.getDefaultNormalizer)();
function escapeRegExp(string) {

@@ -30,3 +22,2 @@ return string.replace(/[.*+\-?^${}()|[\]\\]/g, '\\$&'); // $& means the whole matched string

}
function makeSuggestion(queryName, element, content, {

@@ -39,7 +30,5 @@ variant,

const queryArgs = [['Role', 'TestId'].includes(queryName) ? content : getRegExpMatcher(content)];
if (name) {
queryOptions.name = getRegExpMatcher(name);
}
if (queryName === 'Role' && (0, _roleHelpers.isInaccessible)(element)) {

@@ -51,7 +40,5 @@ queryOptions.hidden = true;

}
if (Object.keys(queryOptions).length > 0) {
queryArgs.push(queryOptions);
}
const queryMethod = `${variant}By${queryName}`;

@@ -64,3 +51,2 @@ return {

warning,
toString() {

@@ -70,3 +56,2 @@ if (warning) {

}
let [text, options] = queryArgs;

@@ -77,21 +62,16 @@ text = typeof text === 'string' ? `'${text}'` : text;

}
};
}
function canSuggest(currentMethod, requestedMethod, data) {
return data && (!requestedMethod || requestedMethod.toLowerCase() === currentMethod.toLowerCase());
}
function getSuggestedQuery(element, variant = 'get', method) {
var _element$getAttribute, _getImplicitAriaRoles;
// don't create suggestions for script and style elements
if (element.matches((0, _config.getConfig)().defaultIgnore)) {
return undefined;
} //We prefer to suggest something else if the role is generic
}
//We prefer to suggest something else if the role is generic
const role = (_element$getAttribute = element.getAttribute('role')) != null ? _element$getAttribute : (_getImplicitAriaRoles = (0, _roleHelpers.getImplicitAriaRoles)(element)) == null ? void 0 : _getImplicitAriaRoles[0];
if (role !== 'generic' && canSuggest('Role', method, role)) {

@@ -105,5 +85,3 @@ return makeSuggestion('Role', element, role, {

}
const labelText = (0, _labelHelpers.getLabels)(document, element).map(label => label.content).join(' ');
if (canSuggest('LabelText', method, labelText)) {

@@ -114,5 +92,3 @@ return makeSuggestion('LabelText', element, labelText, {

}
const placeholderText = element.getAttribute('placeholder');
if (canSuggest('PlaceholderText', method, placeholderText)) {

@@ -123,5 +99,3 @@ return makeSuggestion('PlaceholderText', element, placeholderText, {

}
const textContent = normalize((0, _getNodeText.getNodeText)(element));
if (canSuggest('Text', method, textContent)) {

@@ -132,3 +106,2 @@ return makeSuggestion('Text', element, textContent, {

}
if (canSuggest('DisplayValue', method, element.value)) {

@@ -139,5 +112,3 @@ return makeSuggestion('DisplayValue', element, normalize(element.value), {

}
const alt = element.getAttribute('alt');
if (canSuggest('AltText', method, alt)) {

@@ -148,5 +119,3 @@ return makeSuggestion('AltText', element, alt, {

}
const title = element.getAttribute('title');
if (canSuggest('Title', method, title)) {

@@ -157,5 +126,3 @@ return makeSuggestion('Title', element, title, {

}
const testId = element.getAttribute((0, _config.getConfig)().testIdAttribute);
if (canSuggest('TestId', method, testId)) {

@@ -166,4 +133,3 @@ return makeSuggestion('TestId', element, testId, {

}
return undefined;
}

@@ -7,9 +7,7 @@ "use strict";

exports.waitForElementToBeRemoved = waitForElementToBeRemoved;
var _waitFor = require("./wait-for");
const isRemoved = result => !result || Array.isArray(result) && !result.length;
const isRemoved = result => !result || Array.isArray(result) && !result.length; // Check if the element is not present.
// Check if the element is not present.
// As the name implies, waitForElementToBeRemoved should check `present` --> `removed`
function initialCheck(elements) {

@@ -20,7 +18,5 @@ if (isRemoved(elements)) {

}
async function waitForElementToBeRemoved(callback, options) {
// created here so we get a nice stacktrace
const timeoutError = new Error('Timed out in waitForElementToBeRemoved.');
if (typeof callback !== 'function') {

@@ -32,15 +28,10 @@ initialCheck(callback);

if (parent === null) return () => null;
while (parent.parentElement) parent = parent.parentElement;
return () => parent.contains(element) ? element : null;
});
callback = () => getRemainingElements.map(c => c()).filter(Boolean);
}
initialCheck(callback());
return (0, _waitFor.waitFor)(() => {
let result;
try {

@@ -52,13 +43,11 @@ result = callback();

}
throw error;
}
if (!isRemoved(result)) {
throw timeoutError;
}
return undefined;
}, options);
}
/*

@@ -65,0 +54,0 @@ eslint

@@ -7,7 +7,4 @@ "use strict";

exports.waitFor = waitForWrapper;
var _helpers = require("./helpers");
var _config = require("./config");
// This is so the stack trace the developer sees is one that's

@@ -18,3 +15,2 @@ // closer to their code (because async stack traces are hard to follow).

}
function waitFor(callback, {

@@ -40,3 +36,2 @@ container = (0, _helpers.getDocument)(),

}
return new Promise(async (resolve, reject) => {

@@ -48,3 +43,2 @@ let lastError, intervalId, observer;

const usingJestFakeTimers = (0, _helpers.jestFakeTimersAreEnabled)();
if (usingJestFakeTimers) {

@@ -54,3 +48,4 @@ const {

} = (0, _config.getConfig)();
checkCallback(); // this is a dangerous rule to disable because it could lead to an
checkCallback();
// this is a dangerous rule to disable because it could lead to an
// infinite loop. However, eslint isn't smart enough to know that we're

@@ -60,3 +55,2 @@ // setting finished inside `onDone` which will be called when we're done

// eslint-disable-next-line no-unmodified-loop-condition
while (!finished) {

@@ -68,3 +62,4 @@ if (!(0, _helpers.jestFakeTimersAreEnabled)()) {

return;
} // we *could* (maybe should?) use `advanceTimersToNextTimer` but it's
}
// we *could* (maybe should?) use `advanceTimersToNextTimer` but it's
// possible that could make this loop go on forever if someone is using

@@ -74,16 +69,16 @@ // third party code that's setting up recursive timers so rapidly that

// by an interval instead. (We have a test for this case).
advanceTimersWrapper(() => {
jest.advanceTimersByTime(interval);
}); // It's really important that checkCallback is run *before* we flush
});
// It's really important that checkCallback is run *before* we flush
// in-flight promises. To be honest, I'm not sure why, and I can't quite
// think of a way to reproduce the problem in a test, but I spent
// an entire day banging my head against a wall on this.
checkCallback();
if (finished) {
break;
} // In this rare case, we *need* to wait for in-flight promises
}
// In this rare case, we *need* to wait for in-flight promises
// to resolve before continuing. We don't need to take advantage

@@ -93,4 +88,2 @@ // of parallelization so we're fine.

// eslint-disable-next-line no-await-in-loop
await advanceTimersWrapper(async () => {

@@ -110,3 +103,2 @@ await new Promise(r => {

}
intervalId = setInterval(checkRealTimersCallback, interval);

@@ -120,7 +112,5 @@ const {

}
function onDone(error, result) {
finished = true;
clearTimeout(overallTimeoutTimer);
if (!usingJestFakeTimers) {

@@ -130,3 +120,2 @@ clearInterval(intervalId);

}
if (error) {

@@ -138,3 +127,2 @@ reject(error);

}
function checkRealTimersCallback() {

@@ -149,9 +137,6 @@ if ((0, _helpers.jestFakeTimersAreEnabled)()) {

}
function checkCallback() {
if (promiseStatus === 'pending') return;
try {
const result = (0, _config.runWithExpensiveErrorDiagnosticsDisabled)(callback);
if (typeof (result == null ? void 0 : result.then) === 'function') {

@@ -168,4 +153,4 @@ promiseStatus = 'pending';

onDone(null, result);
} // If `callback` throws, wait for the next mutation, interval, or timeout.
}
// If `callback` throws, wait for the next mutation, interval, or timeout.
} catch (error) {

@@ -176,9 +161,6 @@ // Save the most recent callback error to reject the promise with it in the event of a timeout

}
function handleTimeout() {
let error;
if (lastError) {
error = lastError;
if (!showOriginalStackTrace && error.name === 'TestingLibraryElementError') {

@@ -189,3 +171,2 @@ copyStackTrace(error, stackTraceError);

error = new Error('Timed out in waitFor.');
if (!showOriginalStackTrace) {

@@ -195,3 +176,2 @@ copyStackTrace(error, stackTraceError);

}
onDone(onTimeout(error), null);

@@ -201,3 +181,2 @@ }

}
function waitForWrapper(callback, options) {

@@ -212,2 +191,3 @@ // create the error here so its stack trace is as close to the

}
/*

@@ -214,0 +194,0 @@ eslint

{
"name": "@testing-library/dom",
"version": "8.19.0",
"version": "8.19.1",
"description": "Simple and complete DOM testing utilities that encourage good testing practices.",

@@ -64,3 +64,3 @@ "main": "dist/index.js",

"@babel/runtime": "^7.12.5",
"@types/aria-query": "^4.2.0",
"@types/aria-query": "^5.0.1",
"aria-query": "^5.0.0",

@@ -67,0 +67,0 @@ "chalk": "^4.1.0",

Sorry, the diff of this file is too big to display

Sorry, the diff of this file is too big to display

Sorry, the diff of this file is too big to display

Sorry, the diff of this file is not supported yet

Sorry, the diff of this file is too big to display

Sorry, the diff of this file is not supported yet

Sorry, the diff of this file is too big to display

SocketSocket SOC 2 Logo

Product

  • Package Alerts
  • Integrations
  • Docs
  • Pricing
  • FAQ
  • Roadmap
  • Changelog

Packages

npm

Stay in touch

Get open source security insights delivered straight into your inbox.


  • Terms
  • Privacy
  • Security

Made with ⚡️ by Socket Inc