diff --git a/src/config.ts b/src/config.ts index d37e46d0..8ff2675a 100644 --- a/src/config.ts +++ b/src/config.ts @@ -53,7 +53,7 @@ export function runWithExpensiveErrorDiagnosticsDisabled( } } -export function configure(newConfig: Partial | ConfigFn) { +export function configure(newConfig: ConfigFn | Partial) { if (typeof newConfig === 'function') { // Pass the existing config out to the provided function // and accept a delta in return diff --git a/src/get-node-text.js b/src/get-node-text.ts similarity index 75% rename from src/get-node-text.js rename to src/get-node-text.ts index 54b29b7c..fe718e0d 100644 --- a/src/get-node-text.js +++ b/src/get-node-text.ts @@ -1,8 +1,8 @@ import {TEXT_NODE} from './helpers' -function getNodeText(node) { +function getNodeText(node: HTMLElement): string { if (node.matches('input[type=submit], input[type=button]')) { - return node.value + return (node as HTMLInputElement).value } return Array.from(node.childNodes) diff --git a/src/label-helpers.ts b/src/label-helpers.ts index e8010a1b..720e9202 100644 --- a/src/label-helpers.ts +++ b/src/label-helpers.ts @@ -1,3 +1,4 @@ +import {Nullish} from '../types' import {TEXT_NODE} from './helpers' const labelledNodeNames = [ @@ -11,7 +12,7 @@ const labelledNodeNames = [ ] function getTextContent( - node: Node | Element | HTMLInputElement, + node: Element | HTMLInputElement | Node, ): string | null { if (labelledNodeNames.includes(node.nodeName.toLowerCase())) { return '' @@ -24,7 +25,7 @@ function getTextContent( .join('') } -function getLabelContent(element: Element): string | null { +function getLabelContent(element: Element): Nullish { let textContent: string | null if (element.tagName.toLowerCase() === 'label') { textContent = getTextContent(element) @@ -58,12 +59,14 @@ function getLabels( container: Element, element: Element, {selector = '*'} = {}, -) { +): {content: Nullish; formControl: Nullish}[] { const ariaLabelledBy = element.getAttribute('aria-labelledby') const labelsId = ariaLabelledBy ? ariaLabelledBy.split(' ') : [] return labelsId.length ? labelsId.map(labelId => { - const labellingElement = container.querySelector(`[id="${labelId}"]`) + const labellingElement = container.querySelector( + `[id="${labelId}"]`, + ) return labellingElement ? {content: getLabelContent(labellingElement), formControl: null} : {content: '', formControl: null} @@ -73,7 +76,7 @@ function getLabels( const formControlSelector = 'button, input, meter, output, progress, select, textarea' const labelledFormControl = Array.from( - label.querySelectorAll(formControlSelector), + label.querySelectorAll(formControlSelector), ).filter(formControlElement => formControlElement.matches(selector))[0] return {content: textToMatch, formControl: labelledFormControl} }) diff --git a/src/queries/all-utils.js b/src/queries/all-utils.ts similarity index 100% rename from src/queries/all-utils.js rename to src/queries/all-utils.ts diff --git a/src/queries/alt-text.js b/src/queries/alt-text.ts similarity index 76% rename from src/queries/alt-text.js rename to src/queries/alt-text.ts index a31c5164..6be73277 100644 --- a/src/queries/alt-text.js +++ b/src/queries/alt-text.ts @@ -1,23 +1,26 @@ import {wrapAllByQueryWithSuggestion} from '../query-helpers' import {checkContainerType} from '../helpers' +import {AllByBoundAttribute, GetErrorFunction} from '../../types' import {matches, fuzzyMatches, makeNormalizer, buildQueries} from './all-utils' -function queryAllByAltText( +const queryAllByAltText: AllByBoundAttribute = ( container, alt, {exact = true, collapseWhitespace, trim, normalizer} = {}, -) { +) => { checkContainerType(container) const matcher = exact ? matches : fuzzyMatches const matchNormalizer = makeNormalizer({collapseWhitespace, trim, normalizer}) - return Array.from(container.querySelectorAll('img,input,area')).filter(node => + return Array.from( + container.querySelectorAll('img,input,area'), + ).filter(node => matcher(node.getAttribute('alt'), node, alt, matchNormalizer), ) } -const getMultipleError = (c, alt) => +const getMultipleError: GetErrorFunction = (c, alt) => `Found multiple elements with the alt text: ${alt}` -const getMissingError = (c, alt) => +const getMissingError: GetErrorFunction = (c, alt) => `Unable to find an element with the alt text: ${alt}` const queryAllByAltTextWithSuggestions = wrapAllByQueryWithSuggestion( diff --git a/src/queries/display-value.js b/src/queries/display-value.ts similarity index 58% rename from src/queries/display-value.js rename to src/queries/display-value.ts index 75ab083f..bab8a136 100644 --- a/src/queries/display-value.js +++ b/src/queries/display-value.ts @@ -1,5 +1,6 @@ import {wrapAllByQueryWithSuggestion} from '../query-helpers' import {checkContainerType} from '../helpers' +import {AllByBoundAttribute, GetErrorFunction} from '../../types' import { getNodeText, matches, @@ -8,33 +9,38 @@ import { buildQueries, } from './all-utils' -function queryAllByDisplayValue( +const queryAllByDisplayValue: AllByBoundAttribute = ( container, value, {exact = true, collapseWhitespace, trim, normalizer} = {}, -) { +) => { checkContainerType(container) const matcher = exact ? matches : fuzzyMatches const matchNormalizer = makeNormalizer({collapseWhitespace, trim, normalizer}) - return Array.from(container.querySelectorAll(`input,textarea,select`)).filter( - node => { - if (node.tagName === 'SELECT') { - const selectedOptions = Array.from(node.options).filter( - option => option.selected, - ) - return selectedOptions.some(optionNode => - matcher(getNodeText(optionNode), optionNode, value, matchNormalizer), - ) - } else { - return matcher(node.value, node, value, matchNormalizer) - } - }, - ) + return Array.from( + container.querySelectorAll(`input,textarea,select`), + ).filter(node => { + if (node.tagName === 'SELECT') { + const selectedOptions = Array.from( + (node as HTMLSelectElement).options, + ).filter(option => option.selected) + return selectedOptions.some(optionNode => + matcher(getNodeText(optionNode), optionNode, value, matchNormalizer), + ) + } else { + return matcher( + (node as HTMLInputElement).value, + node, + value, + matchNormalizer, + ) + } + }) } -const getMultipleError = (c, value) => +const getMultipleError: GetErrorFunction = (c, value) => `Found multiple elements with the display value: ${value}.` -const getMissingError = (c, value) => +const getMissingError: GetErrorFunction = (c, value) => `Unable to find an element with the display value: ${value}.` const queryAllByDisplayValueWithSuggestions = wrapAllByQueryWithSuggestion( diff --git a/src/queries/index.js b/src/queries/index.ts similarity index 100% rename from src/queries/index.js rename to src/queries/index.ts diff --git a/src/queries/label-text.js b/src/queries/label-text.ts similarity index 84% rename from src/queries/label-text.js rename to src/queries/label-text.ts index b844fb9c..0d25c880 100644 --- a/src/queries/label-text.js +++ b/src/queries/label-text.ts @@ -1,6 +1,7 @@ import {getConfig} from '../config' import {checkContainerType} from '../helpers' import {getLabels, getRealLabels, getLabelContent} from '../label-helpers' +import {AllByText, GetErrorFunction, Nullish} from '../../types' import { fuzzyMatches, matches, @@ -12,19 +13,21 @@ import { wrapSingleQueryWithSuggestion, } from './all-utils' -function queryAllLabels(container) { - return Array.from(container.querySelectorAll('label,input')) +function queryAllLabels( + container: HTMLElement, +): {textToMatch: Nullish; node: HTMLElement}[] { + return Array.from(container.querySelectorAll('label,input')) .map(node => { return {node, textToMatch: getLabelContent(node)} }) .filter(({textToMatch}) => textToMatch !== null) } -function queryAllLabelsByText( +const queryAllLabelsByText: AllByText = ( container, text, {exact = true, trim, collapseWhitespace, normalizer} = {}, -) { +) => { const matcher = exact ? matches : fuzzyMatches const matchNormalizer = makeNormalizer({collapseWhitespace, trim, normalizer}) @@ -37,27 +40,32 @@ function queryAllLabelsByText( .map(({node}) => node) } -function queryAllByLabelText( +const queryAllByLabelText: AllByText = ( container, text, {selector = '*', exact = true, collapseWhitespace, trim, normalizer} = {}, -) { +) => { checkContainerType(container) const matcher = exact ? matches : fuzzyMatches const matchNormalizer = makeNormalizer({collapseWhitespace, trim, normalizer}) - const matchingLabelledElements = Array.from(container.querySelectorAll('*')) + const matchingLabelledElements = Array.from( + container.querySelectorAll('*'), + ) .filter(element => { return ( getRealLabels(element).length || element.hasAttribute('aria-labelledby') ) }) - .reduce((labelledElements, labelledElement) => { + .reduce((labelledElements, labelledElement) => { const labelList = getLabels(container, labelledElement, {selector}) labelList .filter(label => Boolean(label.formControl)) .forEach(label => { - if (matcher(label.content, label.formControl, text, matchNormalizer)) + if ( + matcher(label.content, label.formControl, text, matchNormalizer) && + label.formControl + ) labelledElements.push(label.formControl) }) const labelsValue = labelList @@ -92,6 +100,9 @@ function queryAllByLabelText( return labelledElements }, []) .concat( + // TODO: Remove ignore after `queryAllByAttribute` will be moved to TS + // eslint-disable-next-line @typescript-eslint/ban-ts-comment + // @ts-expect-error queryAllByAttribute('aria-label', container, text, { exact, normalizer: matchNormalizer, @@ -110,7 +121,7 @@ function queryAllByLabelText( // ) // however, we can give a more helpful error message than the generic one, // so we're writing this one out by hand. -const getAllByLabelText = (container, text, ...rest) => { +const getAllByLabelText: AllByText = (container, text, ...rest) => { const els = queryAllByLabelText(container, text, ...rest) if (!els.length) { const labels = queryAllLabelsByText(container, text, ...rest) @@ -146,7 +157,10 @@ const getAllByLabelText = (container, text, ...rest) => { return els } -function getTagNameOfElementAssociatedWithLabelViaFor(container, label) { +function getTagNameOfElementAssociatedWithLabelViaFor( + container: Element, + label: Element, +): Nullish { const htmlFor = label.getAttribute('for') if (!htmlFor) { return null @@ -157,7 +171,7 @@ function getTagNameOfElementAssociatedWithLabelViaFor(container, label) { } // the reason mentioned above is the same reason we're not using buildQueries -const getMultipleError = (c, text) => +const getMultipleError: GetErrorFunction = (c, text) => `Found multiple elements with the text of: ${text}` const queryByLabelText = wrapSingleQueryWithSuggestion( makeSingleQuery(queryAllByLabelText, getMultipleError), diff --git a/src/queries/placeholder-text.js b/src/queries/placeholder-text.ts similarity index 68% rename from src/queries/placeholder-text.js rename to src/queries/placeholder-text.ts index bdea5945..9c07c137 100644 --- a/src/queries/placeholder-text.js +++ b/src/queries/placeholder-text.ts @@ -1,14 +1,18 @@ import {wrapAllByQueryWithSuggestion} from '../query-helpers' import {checkContainerType} from '../helpers' +import {AllByBoundAttribute, GetErrorFunction} from '../../types' import {queryAllByAttribute, buildQueries} from './all-utils' -function queryAllByPlaceholderText(...args) { - checkContainerType(...args) +const queryAllByPlaceholderText: AllByBoundAttribute = (...args) => { + checkContainerType(args[0]) + // TODO: Remove ignore after `queryAllByAttribute` will be moved to TS + // eslint-disable-next-line @typescript-eslint/ban-ts-comment + // @ts-expect-error return queryAllByAttribute('placeholder', ...args) } -const getMultipleError = (c, text) => +const getMultipleError: GetErrorFunction = (c, text) => `Found multiple elements with the placeholder text of: ${text}` -const getMissingError = (c, text) => +const getMissingError: GetErrorFunction = (c, text) => `Unable to find an element with the placeholder text of: ${text}` const queryAllByPlaceholderTextWithSuggestions = wrapAllByQueryWithSuggestion( diff --git a/src/queries/test-id.js b/src/queries/test-id.ts similarity index 67% rename from src/queries/test-id.js rename to src/queries/test-id.ts index f2ef5a9d..6a9c9c81 100644 --- a/src/queries/test-id.js +++ b/src/queries/test-id.ts @@ -1,17 +1,21 @@ import {checkContainerType} from '../helpers' import {wrapAllByQueryWithSuggestion} from '../query-helpers' +import {AllByBoundAttribute, GetErrorFunction} from '../../types' import {queryAllByAttribute, getConfig, buildQueries} from './all-utils' const getTestIdAttribute = () => getConfig().testIdAttribute -function queryAllByTestId(...args) { - checkContainerType(...args) +const queryAllByTestId: AllByBoundAttribute = (...args) => { + checkContainerType(args[0]) + // TODO: Remove ignore after `queryAllByAttribute` will be moved to TS + // eslint-disable-next-line @typescript-eslint/ban-ts-comment + // @ts-expect-error return queryAllByAttribute(getTestIdAttribute(), ...args) } -const getMultipleError = (c, id) => +const getMultipleError: GetErrorFunction = (c, id) => `Found multiple elements by: [${getTestIdAttribute()}="${id}"]` -const getMissingError = (c, id) => +const getMissingError: GetErrorFunction = (c, id) => `Unable to find an element by: [${getTestIdAttribute()}="${id}"]` const queryAllByTestIdWithSuggestions = wrapAllByQueryWithSuggestion( diff --git a/src/queries/text.js b/src/queries/text.ts similarity index 68% rename from src/queries/text.js rename to src/queries/text.ts index 903bba25..17faa17c 100644 --- a/src/queries/text.js +++ b/src/queries/text.ts @@ -1,6 +1,7 @@ import {wrapAllByQueryWithSuggestion} from '../query-helpers' import {checkContainerType} from '../helpers' import {DEFAULT_IGNORE_TAGS} from '../config' +import {AllByText, GetErrorFunction} from '../../types' import { fuzzyMatches, matches, @@ -9,7 +10,7 @@ import { buildQueries, } from './all-utils' -function queryAllByText( +const queryAllByText: AllByText = ( container, text, { @@ -20,22 +21,28 @@ function queryAllByText( ignore = DEFAULT_IGNORE_TAGS, normalizer, } = {}, -) { +) => { checkContainerType(container) const matcher = exact ? matches : fuzzyMatches const matchNormalizer = makeNormalizer({collapseWhitespace, trim, normalizer}) - let baseArray = [] + let baseArray: HTMLElement[] = [] if (typeof container.matches === 'function' && container.matches(selector)) { baseArray = [container] } - return [...baseArray, ...Array.from(container.querySelectorAll(selector))] - .filter(node => !ignore || !node.matches(ignore)) - .filter(node => matcher(getNodeText(node), node, text, matchNormalizer)) + 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 as string)) + .filter(node => matcher(getNodeText(node), node, text, matchNormalizer)) + ) } -const getMultipleError = (c, text) => +const getMultipleError: GetErrorFunction = (c, text) => `Found multiple elements with the text: ${text}` -const getMissingError = (c, text) => +const getMissingError: GetErrorFunction = (c, text) => `Unable to find an element with the text: ${text}. This could be because the text is broken up by multiple elements. In this case, you can provide a function for your text matcher to make your matcher more flexible.` const queryAllByTextWithSuggestions = wrapAllByQueryWithSuggestion( diff --git a/src/queries/title.js b/src/queries/title.ts similarity index 77% rename from src/queries/title.js rename to src/queries/title.ts index b56e6e05..82fdab6b 100644 --- a/src/queries/title.js +++ b/src/queries/title.ts @@ -1,5 +1,6 @@ import {wrapAllByQueryWithSuggestion} from '../query-helpers' import {checkContainerType} from '../helpers' +import {AllByBoundAttribute, GetErrorFunction} from '../../types' import { fuzzyMatches, matches, @@ -8,19 +9,21 @@ import { buildQueries, } from './all-utils' -const isSvgTitle = node => +const isSvgTitle = (node: HTMLElement) => node.tagName.toLowerCase() === 'title' && node.parentElement?.tagName.toLowerCase() === 'svg' -function queryAllByTitle( +const queryAllByTitle: AllByBoundAttribute = ( container, text, {exact = true, collapseWhitespace, trim, normalizer} = {}, -) { +) => { checkContainerType(container) const matcher = exact ? matches : fuzzyMatches const matchNormalizer = makeNormalizer({collapseWhitespace, trim, normalizer}) - return Array.from(container.querySelectorAll('[title], svg > title')).filter( + return Array.from( + container.querySelectorAll('[title], svg > title'), + ).filter( node => matcher(node.getAttribute('title'), node, text, matchNormalizer) || (isSvgTitle(node) && @@ -28,9 +31,9 @@ function queryAllByTitle( ) } -const getMultipleError = (c, title) => +const getMultipleError: GetErrorFunction = (c, title) => `Found multiple elements with the title: ${title}.` -const getMissingError = (c, title) => +const getMissingError: GetErrorFunction = (c, title) => `Unable to find an element with the title: ${title}.` const queryAllByTitleWithSuggestions = wrapAllByQueryWithSuggestion( diff --git a/types/__tests__/type-tests.ts b/types/__tests__/type-tests.ts index 4f3dc5a9..9b5c81e8 100644 --- a/types/__tests__/type-tests.ts +++ b/types/__tests__/type-tests.ts @@ -53,7 +53,7 @@ export async function testQueryHelpers() { content.split(/\s+/).some(id => id === automationId) const queryAllByAutomationId = ( container: HTMLElement, - automationId: string | string[], + automationId: string[] | string, options?: MatcherOptions, ) => queryAllByAttribute( diff --git a/types/config.d.ts b/types/config.d.ts index c8e239b6..c9c33633 100644 --- a/types/config.d.ts +++ b/types/config.d.ts @@ -16,5 +16,5 @@ export interface ConfigFn { (existingConfig: Config): Partial } -export function configure(configDelta: Partial | ConfigFn): void +export function configure(configDelta: ConfigFn | Partial): void export function getConfig(): Config diff --git a/types/get-queries-for-element.d.ts b/types/get-queries-for-element.d.ts index b93adfe1..04a48539 100644 --- a/types/get-queries-for-element.d.ts +++ b/types/get-queries-for-element.d.ts @@ -1,29 +1,40 @@ -import * as queries from './queries'; +import * as queries from './queries' export type BoundFunction = T extends ( - attribute: string, - element: HTMLElement, - text: infer P, - options: infer Q, + attribute: string, + element: HTMLElement, + text: infer P, + options: infer Q, ) => infer R - ? (text: P, options?: Q) => R - : T extends (a1: any, text: infer P, options: infer Q, waitForElementOptions: infer W) => infer R - ? (text: P, options?: Q, waitForElementOptions?: W) => R - : T extends (a1: any, text: infer P, options: infer Q) => infer R - ? (text: P, options?: Q) => R - : never; -export type BoundFunctions = { [P in keyof T]: BoundFunction }; + ? (text: P, options?: Q) => R + : T extends ( + a1: any, + text: infer P, + options: infer Q, + waitForElementOptions: infer W, + ) => infer R + ? (text: P, options?: Q, waitForElementOptions?: W) => R + : T extends (a1: any, text: infer P, options: infer Q) => infer R + ? (text: P, options?: Q) => R + : never +export type BoundFunctions = {[P in keyof T]: BoundFunction} export type Query = ( - container: HTMLElement, - ...args: any[] -) => Error | Promise | Promise | HTMLElement[] | HTMLElement | null; + container: HTMLElement, + ...args: any[] +) => + | Error + | HTMLElement + | HTMLElement[] + | Promise + | Promise + | null export interface Queries { - [T: string]: Query; + [T: string]: Query } export function getQueriesForElement( - element: HTMLElement, - queriesToBind?: T, -): BoundFunctions; + element: HTMLElement, + queriesToBind?: T, +): BoundFunctions diff --git a/types/matches.d.ts b/types/matches.d.ts index 2d05d4ab..85e9c9a7 100644 --- a/types/matches.d.ts +++ b/types/matches.d.ts @@ -6,7 +6,7 @@ export type MatcherFunction = ( content: string, element: Nullish, ) => boolean -export type Matcher = MatcherFunction | RegExp | string | number +export type Matcher = MatcherFunction | RegExp | number | string // Get autocomplete for ARIARole union types, while still supporting another string // Ref: https://github.com/microsoft/TypeScript/issues/29729#issuecomment-505826972 diff --git a/types/queries.d.ts b/types/queries.d.ts index d81fdcef..42777ffd 100644 --- a/types/queries.d.ts +++ b/types/queries.d.ts @@ -108,8 +108,8 @@ export interface ByRoleOptions extends MatcherOptions { * Only considers elements with the specified accessible name. */ name?: - | string | RegExp + | string | ((accessibleName: string, element: Element) => boolean) } diff --git a/types/query-helpers.d.ts b/types/query-helpers.d.ts index 2e32020e..a01462d1 100644 --- a/types/query-helpers.d.ts +++ b/types/query-helpers.d.ts @@ -1,9 +1,11 @@ -import {Matcher, MatcherOptions} from './matches' +import {Matcher, MatcherOptions, Nullish} from './matches' import {waitForOptions} from './wait-for' +export type GetErrorFunction = (c: Nullish, alt: string) => string + export interface SelectorMatcherOptions extends MatcherOptions { selector?: string - ignore?: string | boolean + ignore?: boolean | string } export type QueryByAttribute = ( diff --git a/types/screen.d.ts b/types/screen.d.ts index a25dfe23..4013af4a 100644 --- a/types/screen.d.ts +++ b/types/screen.d.ts @@ -8,7 +8,7 @@ export type Screen = BoundFunctions & { * of elements */ debug: ( - element?: Element | HTMLDocument | Array, + element?: Array | Element | HTMLDocument, maxLength?: number, options?: OptionsReceived, ) => void diff --git a/types/suggestions.d.ts b/types/suggestions.d.ts index c2743641..e332dfdb 100644 --- a/types/suggestions.d.ts +++ b/types/suggestions.d.ts @@ -14,30 +14,30 @@ export interface Suggestion { } export type Variant = + | 'find' + | 'findAll' | 'get' | 'getAll' | 'query' | 'queryAll' - | 'find' - | 'findAll' export type Method = - | 'Role' - | 'role' + | 'AltText' + | 'alttext' + | 'DisplayValue' + | 'displayvalue' | 'LabelText' | 'labeltext' | 'PlaceholderText' | 'placeholdertext' + | 'Role' + | 'role' + | 'TestId' + | 'testid' | 'Text' | 'text' - | 'DisplayValue' - | 'displayvalue' - | 'AltText' - | 'alttext' | 'Title' | 'title' - | 'TestId' - | 'testid' export function getSuggestedQuery( element: HTMLElement, diff --git a/types/wait-for-element-to-be-removed.d.ts b/types/wait-for-element-to-be-removed.d.ts index d0daae53..e570aac7 100644 --- a/types/wait-for-element-to-be-removed.d.ts +++ b/types/wait-for-element-to-be-removed.d.ts @@ -1,6 +1,6 @@ -import { waitForOptions } from "./wait-for"; +import {waitForOptions} from './wait-for' export function waitForElementToBeRemoved( - callback: (() => T) | T, - options?: waitForOptions, -): Promise; + callback: T | (() => T), + options?: waitForOptions, +): Promise diff --git a/types/wait-for.d.ts b/types/wait-for.d.ts index f5850dac..ab194169 100644 --- a/types/wait-for.d.ts +++ b/types/wait-for.d.ts @@ -7,6 +7,6 @@ export interface waitForOptions { } export function waitFor( - callback: () => T | Promise, + callback: () => Promise | T, options?: waitForOptions, ): Promise