From d893896a5fb81e4a0f92921d07b0e73a43d69a05 Mon Sep 17 00:00:00 2001 From: Simcha Shats Date: Wed, 5 May 2021 14:25:48 +0300 Subject: [PATCH 1/2] refacor: move queries to TS / prettify some code according ABC --- src/config.ts | 2 +- src/{get-node-text.js => get-node-text.ts} | 4 +- src/label-helpers.ts | 13 +++-- src/queries/{all-utils.js => all-utils.ts} | 0 src/queries/{alt-text.js => alt-text.ts} | 13 +++-- .../{display-value.js => display-value.ts} | 42 +++++++++------- src/queries/{index.js => index.ts} | 0 src/queries/{label-text.js => label-text.ts} | 38 +++++++++----- ...laceholder-text.js => placeholder-text.ts} | 12 +++-- src/queries/{test-id.js => test-id.ts} | 12 +++-- src/queries/{text.js => text.ts} | 23 ++++++--- src/queries/{title.js => title.ts} | 15 +++--- types/__tests__/type-tests.ts | 2 +- types/config.d.ts | 2 +- types/get-queries-for-element.d.ts | 49 ++++++++++++------- types/matches.d.ts | 2 +- types/queries.d.ts | 2 +- types/query-helpers.d.ts | 6 ++- types/screen.d.ts | 2 +- types/suggestions.d.ts | 20 ++++---- types/wait-for-element-to-be-removed.d.ts | 8 +-- types/wait-for.d.ts | 2 +- 22 files changed, 163 insertions(+), 106 deletions(-) rename src/{get-node-text.js => get-node-text.ts} (75%) rename src/queries/{all-utils.js => all-utils.ts} (100%) rename src/queries/{alt-text.js => alt-text.ts} (76%) rename src/queries/{display-value.js => display-value.ts} (58%) rename src/queries/{index.js => index.ts} (100%) rename src/queries/{label-text.js => label-text.ts} (84%) rename src/queries/{placeholder-text.js => placeholder-text.ts} (68%) rename src/queries/{test-id.js => test-id.ts} (67%) rename src/queries/{text.js => text.ts} (68%) rename src/queries/{title.js => title.ts} (77%) 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 From 9a7e7fa437ca7fbf6e4a4b2ed41db51d222c2ea8 Mon Sep 17 00:00:00 2001 From: Simcha Shats Date: Wed, 5 May 2021 16:50:39 +0300 Subject: [PATCH 2/2] refactor: move queries to TS --- src/event-map.js | 350 ------------------ src/event-map.ts | 350 ++++++++++++++++++ ...-element.js => get-queries-for-element.ts} | 11 +- ...r-code-frame.js => get-user-code-frame.ts} | 30 +- src/{index.js => index.ts} | 0 src/queries/{role.js => role.ts} | 77 ++-- types/events.d.ts | 116 +++--- types/matches.d.ts | 2 +- types/queries.d.ts | 10 +- 9 files changed, 495 insertions(+), 451 deletions(-) delete mode 100644 src/event-map.js create mode 100644 src/event-map.ts rename src/{get-queries-for-element.js => get-queries-for-element.ts} (70%) rename src/{get-user-code-frame.js => get-user-code-frame.ts} (54%) rename src/{index.js => index.ts} (100%) rename src/queries/{role.js => role.ts} (75%) diff --git a/src/event-map.js b/src/event-map.js deleted file mode 100644 index 6b026094..00000000 --- a/src/event-map.js +++ /dev/null @@ -1,350 +0,0 @@ -export const eventMap = { - // Clipboard Events - copy: { - EventType: 'ClipboardEvent', - defaultInit: {bubbles: true, cancelable: true, composed: true}, - }, - cut: { - EventType: 'ClipboardEvent', - defaultInit: {bubbles: true, cancelable: true, composed: true}, - }, - paste: { - EventType: 'ClipboardEvent', - defaultInit: {bubbles: true, cancelable: true, composed: true}, - }, - // Composition Events - compositionEnd: { - EventType: 'CompositionEvent', - defaultInit: {bubbles: true, cancelable: true, composed: true}, - }, - compositionStart: { - EventType: 'CompositionEvent', - defaultInit: {bubbles: true, cancelable: true, composed: true}, - }, - compositionUpdate: { - EventType: 'CompositionEvent', - defaultInit: {bubbles: true, cancelable: true, composed: true}, - }, - // Keyboard Events - keyDown: { - EventType: 'KeyboardEvent', - defaultInit: {bubbles: true, cancelable: true, charCode: 0, composed: true}, - }, - keyPress: { - EventType: 'KeyboardEvent', - defaultInit: {bubbles: true, cancelable: true, charCode: 0, composed: true}, - }, - keyUp: { - EventType: 'KeyboardEvent', - defaultInit: {bubbles: true, cancelable: true, charCode: 0, composed: true}, - }, - // Focus Events - focus: { - EventType: 'FocusEvent', - defaultInit: {bubbles: false, cancelable: false, composed: true}, - }, - blur: { - EventType: 'FocusEvent', - defaultInit: {bubbles: false, cancelable: false, composed: true}, - }, - focusIn: { - EventType: 'FocusEvent', - defaultInit: {bubbles: true, cancelable: false, composed: true}, - }, - focusOut: { - EventType: 'FocusEvent', - defaultInit: {bubbles: true, cancelable: false, composed: true}, - }, - // Form Events - change: { - EventType: 'Event', - defaultInit: {bubbles: true, cancelable: false}, - }, - input: { - EventType: 'InputEvent', - defaultInit: {bubbles: true, cancelable: false, composed: true}, - }, - invalid: { - EventType: 'Event', - defaultInit: {bubbles: false, cancelable: true}, - }, - submit: { - EventType: 'Event', - defaultInit: {bubbles: true, cancelable: true}, - }, - reset: { - EventType: 'Event', - defaultInit: {bubbles: true, cancelable: true}, - }, - // Mouse Events - click: { - EventType: 'MouseEvent', - defaultInit: {bubbles: true, cancelable: true, button: 0, composed: true}, - }, - contextMenu: { - EventType: 'MouseEvent', - defaultInit: {bubbles: true, cancelable: true, composed: true}, - }, - dblClick: { - EventType: 'MouseEvent', - defaultInit: {bubbles: true, cancelable: true, composed: true}, - }, - drag: { - EventType: 'DragEvent', - defaultInit: {bubbles: true, cancelable: true, composed: true}, - }, - dragEnd: { - EventType: 'DragEvent', - defaultInit: {bubbles: true, cancelable: false, composed: true}, - }, - dragEnter: { - EventType: 'DragEvent', - defaultInit: {bubbles: true, cancelable: true, composed: true}, - }, - dragExit: { - EventType: 'DragEvent', - defaultInit: {bubbles: true, cancelable: false, composed: true}, - }, - dragLeave: { - EventType: 'DragEvent', - defaultInit: {bubbles: true, cancelable: false, composed: true}, - }, - dragOver: { - EventType: 'DragEvent', - defaultInit: {bubbles: true, cancelable: true, composed: true}, - }, - dragStart: { - EventType: 'DragEvent', - defaultInit: {bubbles: true, cancelable: true, composed: true}, - }, - drop: { - EventType: 'DragEvent', - defaultInit: {bubbles: true, cancelable: true, composed: true}, - }, - mouseDown: { - EventType: 'MouseEvent', - defaultInit: {bubbles: true, cancelable: true, composed: true}, - }, - mouseEnter: { - EventType: 'MouseEvent', - defaultInit: {bubbles: false, cancelable: false, composed: true}, - }, - mouseLeave: { - EventType: 'MouseEvent', - defaultInit: {bubbles: false, cancelable: false, composed: true}, - }, - mouseMove: { - EventType: 'MouseEvent', - defaultInit: {bubbles: true, cancelable: true, composed: true}, - }, - mouseOut: { - EventType: 'MouseEvent', - defaultInit: {bubbles: true, cancelable: true, composed: true}, - }, - mouseOver: { - EventType: 'MouseEvent', - defaultInit: {bubbles: true, cancelable: true, composed: true}, - }, - mouseUp: { - EventType: 'MouseEvent', - defaultInit: {bubbles: true, cancelable: true, composed: true}, - }, - // Selection Events - select: { - EventType: 'Event', - defaultInit: {bubbles: true, cancelable: false}, - }, - // Touch Events - touchCancel: { - EventType: 'TouchEvent', - defaultInit: {bubbles: true, cancelable: false, composed: true}, - }, - touchEnd: { - EventType: 'TouchEvent', - defaultInit: {bubbles: true, cancelable: true, composed: true}, - }, - touchMove: { - EventType: 'TouchEvent', - defaultInit: {bubbles: true, cancelable: true, composed: true}, - }, - touchStart: { - EventType: 'TouchEvent', - defaultInit: {bubbles: true, cancelable: true, composed: true}, - }, - // UI Events - scroll: { - EventType: 'UIEvent', - defaultInit: {bubbles: false, cancelable: false}, - }, - // Wheel Events - wheel: { - EventType: 'WheelEvent', - defaultInit: {bubbles: true, cancelable: true, composed: true}, - }, - // Media Events - abort: { - EventType: 'Event', - defaultInit: {bubbles: false, cancelable: false}, - }, - canPlay: { - EventType: 'Event', - defaultInit: {bubbles: false, cancelable: false}, - }, - canPlayThrough: { - EventType: 'Event', - defaultInit: {bubbles: false, cancelable: false}, - }, - durationChange: { - EventType: 'Event', - defaultInit: {bubbles: false, cancelable: false}, - }, - emptied: { - EventType: 'Event', - defaultInit: {bubbles: false, cancelable: false}, - }, - encrypted: { - EventType: 'Event', - defaultInit: {bubbles: false, cancelable: false}, - }, - ended: { - EventType: 'Event', - defaultInit: {bubbles: false, cancelable: false}, - }, - loadedData: { - EventType: 'Event', - defaultInit: {bubbles: false, cancelable: false}, - }, - loadedMetadata: { - EventType: 'Event', - defaultInit: {bubbles: false, cancelable: false}, - }, - loadStart: { - EventType: 'ProgressEvent', - defaultInit: {bubbles: false, cancelable: false}, - }, - pause: { - EventType: 'Event', - defaultInit: {bubbles: false, cancelable: false}, - }, - play: { - EventType: 'Event', - defaultInit: {bubbles: false, cancelable: false}, - }, - playing: { - EventType: 'Event', - defaultInit: {bubbles: false, cancelable: false}, - }, - progress: { - EventType: 'ProgressEvent', - defaultInit: {bubbles: false, cancelable: false}, - }, - rateChange: { - EventType: 'Event', - defaultInit: {bubbles: false, cancelable: false}, - }, - seeked: { - EventType: 'Event', - defaultInit: {bubbles: false, cancelable: false}, - }, - seeking: { - EventType: 'Event', - defaultInit: {bubbles: false, cancelable: false}, - }, - stalled: { - EventType: 'Event', - defaultInit: {bubbles: false, cancelable: false}, - }, - suspend: { - EventType: 'Event', - defaultInit: {bubbles: false, cancelable: false}, - }, - timeUpdate: { - EventType: 'Event', - defaultInit: {bubbles: false, cancelable: false}, - }, - volumeChange: { - EventType: 'Event', - defaultInit: {bubbles: false, cancelable: false}, - }, - waiting: { - EventType: 'Event', - defaultInit: {bubbles: false, cancelable: false}, - }, - // Image Events - load: { - EventType: 'UIEvent', - defaultInit: {bubbles: false, cancelable: false}, - }, - error: { - EventType: 'Event', - defaultInit: {bubbles: false, cancelable: false}, - }, - // Animation Events - animationStart: { - EventType: 'AnimationEvent', - defaultInit: {bubbles: true, cancelable: false}, - }, - animationEnd: { - EventType: 'AnimationEvent', - defaultInit: {bubbles: true, cancelable: false}, - }, - animationIteration: { - EventType: 'AnimationEvent', - defaultInit: {bubbles: true, cancelable: false}, - }, - // Transition Events - transitionEnd: { - EventType: 'TransitionEvent', - defaultInit: {bubbles: true, cancelable: true}, - }, - // pointer events - pointerOver: { - EventType: 'PointerEvent', - defaultInit: {bubbles: true, cancelable: true, composed: true}, - }, - pointerEnter: { - EventType: 'PointerEvent', - defaultInit: {bubbles: false, cancelable: false}, - }, - pointerDown: { - EventType: 'PointerEvent', - defaultInit: {bubbles: true, cancelable: true, composed: true}, - }, - pointerMove: { - EventType: 'PointerEvent', - defaultInit: {bubbles: true, cancelable: true, composed: true}, - }, - pointerUp: { - EventType: 'PointerEvent', - defaultInit: {bubbles: true, cancelable: true, composed: true}, - }, - pointerCancel: { - EventType: 'PointerEvent', - defaultInit: {bubbles: true, cancelable: false, composed: true}, - }, - pointerOut: { - EventType: 'PointerEvent', - defaultInit: {bubbles: true, cancelable: true, composed: true}, - }, - pointerLeave: { - EventType: 'PointerEvent', - defaultInit: {bubbles: false, cancelable: false}, - }, - gotPointerCapture: { - EventType: 'PointerEvent', - defaultInit: {bubbles: true, cancelable: false, composed: true}, - }, - lostPointerCapture: { - EventType: 'PointerEvent', - defaultInit: {bubbles: true, cancelable: false, composed: true}, - }, - // history events - popState: { - EventType: 'PopStateEvent', - defaultInit: {bubbles: true, cancelable: false}, - }, - } - - export const eventAliasMap = { - doubleClick: 'dblClick', - } diff --git a/src/event-map.ts b/src/event-map.ts new file mode 100644 index 00000000..e8cb6a5d --- /dev/null +++ b/src/event-map.ts @@ -0,0 +1,350 @@ +export const eventMap = { + // Clipboard Events + copy: { + EventType: 'ClipboardEvent', + defaultInit: {bubbles: true, cancelable: true, composed: true}, + }, + cut: { + EventType: 'ClipboardEvent', + defaultInit: {bubbles: true, cancelable: true, composed: true}, + }, + paste: { + EventType: 'ClipboardEvent', + defaultInit: {bubbles: true, cancelable: true, composed: true}, + }, + // Composition Events + compositionEnd: { + EventType: 'CompositionEvent', + defaultInit: {bubbles: true, cancelable: true, composed: true}, + }, + compositionStart: { + EventType: 'CompositionEvent', + defaultInit: {bubbles: true, cancelable: true, composed: true}, + }, + compositionUpdate: { + EventType: 'CompositionEvent', + defaultInit: {bubbles: true, cancelable: true, composed: true}, + }, + // Keyboard Events + keyDown: { + EventType: 'KeyboardEvent', + defaultInit: {bubbles: true, cancelable: true, charCode: 0, composed: true}, + }, + keyPress: { + EventType: 'KeyboardEvent', + defaultInit: {bubbles: true, cancelable: true, charCode: 0, composed: true}, + }, + keyUp: { + EventType: 'KeyboardEvent', + defaultInit: {bubbles: true, cancelable: true, charCode: 0, composed: true}, + }, + // Focus Events + focus: { + EventType: 'FocusEvent', + defaultInit: {bubbles: false, cancelable: false, composed: true}, + }, + blur: { + EventType: 'FocusEvent', + defaultInit: {bubbles: false, cancelable: false, composed: true}, + }, + focusIn: { + EventType: 'FocusEvent', + defaultInit: {bubbles: true, cancelable: false, composed: true}, + }, + focusOut: { + EventType: 'FocusEvent', + defaultInit: {bubbles: true, cancelable: false, composed: true}, + }, + // Form Events + change: { + EventType: 'Event', + defaultInit: {bubbles: true, cancelable: false}, + }, + input: { + EventType: 'InputEvent', + defaultInit: {bubbles: true, cancelable: false, composed: true}, + }, + invalid: { + EventType: 'Event', + defaultInit: {bubbles: false, cancelable: true}, + }, + submit: { + EventType: 'Event', + defaultInit: {bubbles: true, cancelable: true}, + }, + reset: { + EventType: 'Event', + defaultInit: {bubbles: true, cancelable: true}, + }, + // Mouse Events + click: { + EventType: 'MouseEvent', + defaultInit: {bubbles: true, cancelable: true, button: 0, composed: true}, + }, + contextMenu: { + EventType: 'MouseEvent', + defaultInit: {bubbles: true, cancelable: true, composed: true}, + }, + dblClick: { + EventType: 'MouseEvent', + defaultInit: {bubbles: true, cancelable: true, composed: true}, + }, + drag: { + EventType: 'DragEvent', + defaultInit: {bubbles: true, cancelable: true, composed: true}, + }, + dragEnd: { + EventType: 'DragEvent', + defaultInit: {bubbles: true, cancelable: false, composed: true}, + }, + dragEnter: { + EventType: 'DragEvent', + defaultInit: {bubbles: true, cancelable: true, composed: true}, + }, + dragExit: { + EventType: 'DragEvent', + defaultInit: {bubbles: true, cancelable: false, composed: true}, + }, + dragLeave: { + EventType: 'DragEvent', + defaultInit: {bubbles: true, cancelable: false, composed: true}, + }, + dragOver: { + EventType: 'DragEvent', + defaultInit: {bubbles: true, cancelable: true, composed: true}, + }, + dragStart: { + EventType: 'DragEvent', + defaultInit: {bubbles: true, cancelable: true, composed: true}, + }, + drop: { + EventType: 'DragEvent', + defaultInit: {bubbles: true, cancelable: true, composed: true}, + }, + mouseDown: { + EventType: 'MouseEvent', + defaultInit: {bubbles: true, cancelable: true, composed: true}, + }, + mouseEnter: { + EventType: 'MouseEvent', + defaultInit: {bubbles: false, cancelable: false, composed: true}, + }, + mouseLeave: { + EventType: 'MouseEvent', + defaultInit: {bubbles: false, cancelable: false, composed: true}, + }, + mouseMove: { + EventType: 'MouseEvent', + defaultInit: {bubbles: true, cancelable: true, composed: true}, + }, + mouseOut: { + EventType: 'MouseEvent', + defaultInit: {bubbles: true, cancelable: true, composed: true}, + }, + mouseOver: { + EventType: 'MouseEvent', + defaultInit: {bubbles: true, cancelable: true, composed: true}, + }, + mouseUp: { + EventType: 'MouseEvent', + defaultInit: {bubbles: true, cancelable: true, composed: true}, + }, + // Selection Events + select: { + EventType: 'Event', + defaultInit: {bubbles: true, cancelable: false}, + }, + // Touch Events + touchCancel: { + EventType: 'TouchEvent', + defaultInit: {bubbles: true, cancelable: false, composed: true}, + }, + touchEnd: { + EventType: 'TouchEvent', + defaultInit: {bubbles: true, cancelable: true, composed: true}, + }, + touchMove: { + EventType: 'TouchEvent', + defaultInit: {bubbles: true, cancelable: true, composed: true}, + }, + touchStart: { + EventType: 'TouchEvent', + defaultInit: {bubbles: true, cancelable: true, composed: true}, + }, + // UI Events + scroll: { + EventType: 'UIEvent', + defaultInit: {bubbles: false, cancelable: false}, + }, + // Wheel Events + wheel: { + EventType: 'WheelEvent', + defaultInit: {bubbles: true, cancelable: true, composed: true}, + }, + // Media Events + abort: { + EventType: 'Event', + defaultInit: {bubbles: false, cancelable: false}, + }, + canPlay: { + EventType: 'Event', + defaultInit: {bubbles: false, cancelable: false}, + }, + canPlayThrough: { + EventType: 'Event', + defaultInit: {bubbles: false, cancelable: false}, + }, + durationChange: { + EventType: 'Event', + defaultInit: {bubbles: false, cancelable: false}, + }, + emptied: { + EventType: 'Event', + defaultInit: {bubbles: false, cancelable: false}, + }, + encrypted: { + EventType: 'Event', + defaultInit: {bubbles: false, cancelable: false}, + }, + ended: { + EventType: 'Event', + defaultInit: {bubbles: false, cancelable: false}, + }, + loadedData: { + EventType: 'Event', + defaultInit: {bubbles: false, cancelable: false}, + }, + loadedMetadata: { + EventType: 'Event', + defaultInit: {bubbles: false, cancelable: false}, + }, + loadStart: { + EventType: 'ProgressEvent', + defaultInit: {bubbles: false, cancelable: false}, + }, + pause: { + EventType: 'Event', + defaultInit: {bubbles: false, cancelable: false}, + }, + play: { + EventType: 'Event', + defaultInit: {bubbles: false, cancelable: false}, + }, + playing: { + EventType: 'Event', + defaultInit: {bubbles: false, cancelable: false}, + }, + progress: { + EventType: 'ProgressEvent', + defaultInit: {bubbles: false, cancelable: false}, + }, + rateChange: { + EventType: 'Event', + defaultInit: {bubbles: false, cancelable: false}, + }, + seeked: { + EventType: 'Event', + defaultInit: {bubbles: false, cancelable: false}, + }, + seeking: { + EventType: 'Event', + defaultInit: {bubbles: false, cancelable: false}, + }, + stalled: { + EventType: 'Event', + defaultInit: {bubbles: false, cancelable: false}, + }, + suspend: { + EventType: 'Event', + defaultInit: {bubbles: false, cancelable: false}, + }, + timeUpdate: { + EventType: 'Event', + defaultInit: {bubbles: false, cancelable: false}, + }, + volumeChange: { + EventType: 'Event', + defaultInit: {bubbles: false, cancelable: false}, + }, + waiting: { + EventType: 'Event', + defaultInit: {bubbles: false, cancelable: false}, + }, + // Image Events + load: { + EventType: 'UIEvent', + defaultInit: {bubbles: false, cancelable: false}, + }, + error: { + EventType: 'Event', + defaultInit: {bubbles: false, cancelable: false}, + }, + // Animation Events + animationStart: { + EventType: 'AnimationEvent', + defaultInit: {bubbles: true, cancelable: false}, + }, + animationEnd: { + EventType: 'AnimationEvent', + defaultInit: {bubbles: true, cancelable: false}, + }, + animationIteration: { + EventType: 'AnimationEvent', + defaultInit: {bubbles: true, cancelable: false}, + }, + // Transition Events + transitionEnd: { + EventType: 'TransitionEvent', + defaultInit: {bubbles: true, cancelable: true}, + }, + // pointer events + pointerOver: { + EventType: 'PointerEvent', + defaultInit: {bubbles: true, cancelable: true, composed: true}, + }, + pointerEnter: { + EventType: 'PointerEvent', + defaultInit: {bubbles: false, cancelable: false}, + }, + pointerDown: { + EventType: 'PointerEvent', + defaultInit: {bubbles: true, cancelable: true, composed: true}, + }, + pointerMove: { + EventType: 'PointerEvent', + defaultInit: {bubbles: true, cancelable: true, composed: true}, + }, + pointerUp: { + EventType: 'PointerEvent', + defaultInit: {bubbles: true, cancelable: true, composed: true}, + }, + pointerCancel: { + EventType: 'PointerEvent', + defaultInit: {bubbles: true, cancelable: false, composed: true}, + }, + pointerOut: { + EventType: 'PointerEvent', + defaultInit: {bubbles: true, cancelable: true, composed: true}, + }, + pointerLeave: { + EventType: 'PointerEvent', + defaultInit: {bubbles: false, cancelable: false}, + }, + gotPointerCapture: { + EventType: 'PointerEvent', + defaultInit: {bubbles: true, cancelable: false, composed: true}, + }, + lostPointerCapture: { + EventType: 'PointerEvent', + defaultInit: {bubbles: true, cancelable: false, composed: true}, + }, + // history events + popState: { + EventType: 'PopStateEvent', + defaultInit: {bubbles: true, cancelable: false}, + }, +} + +export const eventAliasMap = { + doubleClick: 'dblClick', +} diff --git a/src/get-queries-for-element.js b/src/get-queries-for-element.ts similarity index 70% rename from src/get-queries-for-element.js rename to src/get-queries-for-element.ts index cc81578b..aa2e90da 100644 --- a/src/get-queries-for-element.js +++ b/src/get-queries-for-element.ts @@ -10,14 +10,17 @@ import * as defaultQueries from './queries' * @param {Object} initialValue for reducer * @returns {FuncMap} returns object of functions bound to container */ + +type BoundFunction = {[key: string]: Function} + function getQueriesForElement( - element, - queries = defaultQueries, - initialValue = {}, + element: HTMLElement, + queries: BoundFunction = defaultQueries, + initialValue: BoundFunction = {}, ) { return Object.keys(queries).reduce((helpers, key) => { const fn = queries[key] - helpers[key] = fn.bind(null, element) + helpers[key] = fn.bind(null, element) as Function return helpers }, initialValue) } diff --git a/src/get-user-code-frame.js b/src/get-user-code-frame.ts similarity index 54% rename from src/get-user-code-frame.js rename to src/get-user-code-frame.ts index 7cdb90b6..561be225 100644 --- a/src/get-user-code-frame.js +++ b/src/get-user-code-frame.ts @@ -1,21 +1,25 @@ // We try to load node dependencies -let chalk = null -let readFileSync = null -let codeFrameColumns = null +let chalk: {dim: Function} | null = null +let readFileSync: Function | null = null +let codeFrameColumns: Function | null = null try { - const nodeRequire = module && module.require + // eslint-disable-next-line @typescript-eslint/no-unnecessary-condition + const nodeRequire = module?.require + // eslint-disable-next-line @typescript-eslint/no-unsafe-assignment,@typescript-eslint/no-unsafe-member-access readFileSync = nodeRequire.call(module, 'fs').readFileSync + // eslint-disable-next-line @typescript-eslint/no-unsafe-member-access,@typescript-eslint/no-unsafe-assignment codeFrameColumns = nodeRequire.call(module, '@babel/code-frame') .codeFrameColumns + // eslint-disable-next-line @typescript-eslint/no-unsafe-assignment 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)" -function getCodeFrame(frame) { +function getCodeFrame(frame: string) { const locationStart = frame.indexOf('(') + 1 const locationEnd = frame.indexOf(')') const frameLocation = frame.slice(locationStart, locationEnd) @@ -29,12 +33,14 @@ function getCodeFrame(frame) { let rawFileContents = '' try { - rawFileContents = readFileSync(filename, 'utf-8') + // eslint-disable-next-line @typescript-eslint/no-unsafe-assignment + rawFileContents = readFileSync?.(filename, 'utf-8') } catch { return '' } - const codeFrame = codeFrameColumns( + // eslint-disable-next-line @typescript-eslint/no-unsafe-assignment + const codeFrame = codeFrameColumns?.( rawFileContents, { start: {line, column}, @@ -44,7 +50,7 @@ function getCodeFrame(frame) { linesBelow: 0, }, ) - return `${chalk.dim(frameLocation)}\n${codeFrame}\n` + return `${chalk?.dim(frameLocation)}\n${codeFrame}\n` } function getUserCodeFrame() { @@ -53,13 +59,15 @@ function getUserCodeFrame() { if (!readFileSync || !codeFrameColumns) { return '' } - const err = new Error() - const firstClientCodeFrame = err.stack + const err: Error = new Error() + // eslint-disable-next-line @typescript-eslint/ban-ts-comment + // @ts-expect-error + const firstClientCodeFrame: string | undefined = err.stack .split('\n') .slice(1) // Remove first line which has the form "Error: TypeError" .find(frame => !frame.includes('node_modules/')) // Ignore frames from 3rd party libraries - return getCodeFrame(firstClientCodeFrame) + return getCodeFrame(firstClientCodeFrame ?? '') } export {getUserCodeFrame} diff --git a/src/index.js b/src/index.ts similarity index 100% rename from src/index.js rename to src/index.ts diff --git a/src/queries/role.js b/src/queries/role.ts similarity index 75% rename from src/queries/role.js rename to src/queries/role.ts index 747e2ca0..dd5d0d9e 100644 --- a/src/queries/role.js +++ b/src/queries/role.ts @@ -1,5 +1,9 @@ import {computeAccessibleName} from 'dom-accessibility-api' -import {roles as allRoles} from 'aria-query' +import { + ARIAAbstractRole, + ARIARoleDefintionKey, + roles as allRoles, +} from 'aria-query' import { computeAriaSelected, computeAriaChecked, @@ -13,6 +17,7 @@ import { } from '../role-helpers' import {wrapAllByQueryWithSuggestion} from '../query-helpers' import {checkContainerType} from '../helpers' +import {AllByRole, ByRoleMatcher, ByRoleOptionsName, Nullish} from '../../types' import { buildQueries, fuzzyMatches, @@ -21,7 +26,7 @@ import { matches, } from './all-utils' -function queryAllByRole( +const queryAllByRole: AllByRole = ( container, role, { @@ -38,28 +43,35 @@ function queryAllByRole( level, expanded, } = {}, -) { +) => { checkContainerType(container) const matcher = exact ? matches : fuzzyMatches const matchNormalizer = makeNormalizer({collapseWhitespace, trim, normalizer}) if (selected !== undefined) { // guard against unknown roles - if (allRoles.get(role)?.props['aria-selected'] === undefined) { + if ( + allRoles.get(role)?.props['aria-selected'] === + undefined + ) { throw new Error(`"aria-selected" is not supported on role "${role}".`) } } if (checked !== undefined) { // guard against unknown roles - if (allRoles.get(role)?.props['aria-checked'] === undefined) { + if ( + allRoles.get(role)?.props['aria-checked'] === undefined + ) { throw new Error(`"aria-checked" is not supported on role "${role}".`) } } if (pressed !== undefined) { // guard against unknown roles - if (allRoles.get(role)?.props['aria-pressed'] === undefined) { + if ( + allRoles.get(role)?.props['aria-pressed'] === undefined + ) { throw new Error(`"aria-pressed" is not supported on role "${role}".`) } } @@ -73,13 +85,15 @@ function queryAllByRole( if (expanded !== undefined) { // guard against unknown roles - if (allRoles.get(role)?.props['aria-expanded'] === undefined) { + if ( + allRoles.get(role)?.props['aria-expanded'] === undefined + ) { throw new Error(`"aria-expanded" is not supported on role "${role}".`) } } const subtreeIsInaccessibleCache = new WeakMap() - function cachedIsSubtreeInaccessible(element) { + function cachedIsSubtreeInaccessible(element: HTMLElement) { if (!subtreeIsInaccessibleCache.has(element)) { subtreeIsInaccessibleCache.set(element, isSubtreeInaccessible(element)) } @@ -87,12 +101,12 @@ function queryAllByRole( return subtreeIsInaccessibleCache.get(element) } - return Array.from(container.querySelectorAll('*')) + return Array.from(container.querySelectorAll('*')) .filter(node => { const isRoleSpecifiedExplicitly = node.hasAttribute('role') if (isRoleSpecifiedExplicitly) { - const roleValue = node.getAttribute('role') + const roleValue = node.getAttribute('role') ?? '' if (queryFallbacks) { return roleValue .split(' ') @@ -108,7 +122,9 @@ function queryAllByRole( return matcher(firstWord, node, role, matchNormalizer) } - const implicitRoles = getImplicitAriaRoles(node) + // TODO: Remove ignore after `getImplicitAriaRoles` will be moved to TS + // eslint-disable-next-line @typescript-eslint/no-unsafe-assignment + const implicitRoles: Nullish[] = getImplicitAriaRoles(node) return implicitRoles.some(implicitRole => matcher(implicitRole, node, role, matchNormalizer), @@ -134,11 +150,14 @@ function queryAllByRole( return true }) .filter(element => { - return hidden === false - ? isInaccessible(element, { + return hidden + ? true + : !isInaccessible(element, { + // TODO: Remove ignore after `isInaccessible` will be moved to TS + // eslint-disable-next-line @typescript-eslint/ban-ts-comment + // @ts-expect-error isSubtreeInaccessible: cachedIsSubtreeInaccessible, - }) === false - : true + }) }) .filter(element => { if (name === undefined) { @@ -158,7 +177,11 @@ function queryAllByRole( }) } -const getMultipleError = (c, role, {name} = {}) => { +const getMultipleError = ( + c: HTMLElement, + role: ByRoleMatcher, + {name}: {name?: ByRoleOptionsName} = {}, +): string => { let nameHint = '' if (name === undefined) { nameHint = '' @@ -172,9 +195,12 @@ const getMultipleError = (c, role, {name} = {}) => { } const getMissingError = ( - container, - role, - {hidden = getConfig().defaultHidden, name} = {}, + container: HTMLElement, + role: string, + { + hidden = getConfig().defaultHidden, + name, + }: {hidden?: boolean; name?: ByRoleOptionsName} = {}, ) => { if (getConfig()._disableExpensiveErrorDiagnostics) { return `Unable to find role="${role}"` @@ -184,23 +210,26 @@ const getMissingError = ( Array.from(container.children).forEach(childElement => { roles += prettyRoles(childElement, { hidden, + // TODO: Remove ignore after `prettyRoles` will be moved to TS + // eslint-disable-next-line @typescript-eslint/ban-ts-comment + // @ts-expect-error includeName: name !== undefined, }) }) let roleMessage if (roles.length === 0) { - if (hidden === false) { + if (hidden) { + roleMessage = 'There are no available roles.' + } else { roleMessage = 'There are no accessible roles. But there might be some inaccessible roles. ' + 'If you wish to access them, then set the `hidden` option to `true`. ' + 'Learn more about this here: https://testing-library.com/docs/dom-testing-library/api-queries#byrole' - } else { - roleMessage = 'There are no available roles.' } } else { roleMessage = ` -Here are the ${hidden === false ? 'accessible' : 'available'} roles: +Here are the ${hidden ? 'available' : 'accessible'} roles: ${roles.replace(/\n/g, '\n ').replace(/\n\s\s\n/g, '\n\n')} `.trim() @@ -217,7 +246,7 @@ Here are the ${hidden === false ? 'accessible' : 'available'} roles: return ` Unable to find an ${ - hidden === false ? 'accessible ' : '' + hidden ? '' : 'accessible ' }element with the role "${role}"${nameHint} ${roleMessage}`.trim() diff --git a/types/events.d.ts b/types/events.d.ts index 925da69f..aa323412 100644 --- a/types/events.d.ts +++ b/types/events.d.ts @@ -1,25 +1,23 @@ +import {Nullish} from './matches' + export type EventType = - | 'copy' - | 'cut' - | 'paste' - | 'compositionEnd' - | 'compositionStart' - | 'compositionUpdate' - | 'keyDown' - | 'keyPress' - | 'keyUp' - | 'focus' + | 'abort' + | 'animationEnd' + | 'animationIteration' + | 'animationStart' | 'blur' - | 'focusIn' - | 'focusOut' + | 'canPlay' + | 'canPlayThrough' | 'change' - | 'input' - | 'invalid' - | 'submit' - | 'reset' | 'click' + | 'compositionEnd' + | 'compositionStart' + | 'compositionUpdate' | 'contextMenu' + | 'copy' + | 'cut' | 'dblClick' + | 'doubleClick' | 'drag' | 'dragEnd' | 'dragEnter' @@ -28,83 +26,87 @@ export type EventType = | 'dragOver' | 'dragStart' | 'drop' - | 'mouseDown' - | 'mouseEnter' - | 'mouseLeave' - | 'mouseMove' - | 'mouseOut' - | 'mouseOver' - | 'mouseUp' - | 'popState' - | 'select' - | 'touchCancel' - | 'touchEnd' - | 'touchMove' - | 'touchStart' - | 'scroll' - | 'wheel' - | 'abort' - | 'canPlay' - | 'canPlayThrough' | 'durationChange' | 'emptied' | 'encrypted' | 'ended' + | 'error' + | 'focus' + | 'focusIn' + | 'focusOut' + | 'gotPointerCapture' + | 'input' + | 'invalid' + | 'keyDown' + | 'keyPress' + | 'keyUp' + | 'load' | 'loadedData' | 'loadedMetadata' | 'loadStart' + | 'lostPointerCapture' + | 'mouseDown' + | 'mouseEnter' + | 'mouseLeave' + | 'mouseMove' + | 'mouseOut' + | 'mouseOver' + | 'mouseUp' + | 'paste' | 'pause' | 'play' | 'playing' + | 'pointerCancel' + | 'pointerDown' + | 'pointerEnter' + | 'pointerLeave' + | 'pointerMove' + | 'pointerOut' + | 'pointerOver' + | 'pointerUp' + | 'popState' | 'progress' | 'rateChange' + | 'reset' + | 'scroll' | 'seeked' | 'seeking' + | 'select' | 'stalled' + | 'submit' | 'suspend' | 'timeUpdate' + | 'touchCancel' + | 'touchEnd' + | 'touchMove' + | 'touchStart' + | 'transitionEnd' | 'volumeChange' | 'waiting' - | 'load' - | 'error' - | 'animationStart' - | 'animationEnd' - | 'animationIteration' - | 'transitionEnd' - | 'doubleClick' - | 'pointerOver' - | 'pointerEnter' - | 'pointerDown' - | 'pointerMove' - | 'pointerUp' - | 'pointerCancel' - | 'pointerOut' - | 'pointerLeave' - | 'gotPointerCapture' - | 'lostPointerCapture' + | 'wheel' export type FireFunction = ( - element: Document | Element | Window | Node, - event: Event, + element: Nullish, + event: Nullish, ) => boolean export type FireObject = { [K in EventType]: ( - element: Document | Element | Window | Node, + element: Document | Element | Node | Window, options?: {}, ) => boolean } export type CreateFunction = ( eventName: string, - node: Document | Element | Window | Node, + node: Nullish, init?: {}, options?: {EventType?: string; defaultInit?: {}}, ) => Event export type CreateObject = { [K in EventType]: ( - element: Document | Element | Window | Node, + element: Document | Element | Node | Window, options?: {}, ) => Event } -export const createEvent: CreateObject & CreateFunction +export const createEvent: CreateFunction & CreateObject export const fireEvent: FireFunction & FireObject diff --git a/types/matches.d.ts b/types/matches.d.ts index 85e9c9a7..d5fff504 100644 --- a/types/matches.d.ts +++ b/types/matches.d.ts @@ -10,7 +10,7 @@ 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 -export type ByRoleMatcher = ARIARole | MatcherFunction | {} +export type ByRoleMatcher = ARIARole | Matcher | MatcherFunction export type NormalizerFn = (text: string) => string diff --git a/types/queries.d.ts b/types/queries.d.ts index 42777ffd..f0e71b5c 100644 --- a/types/queries.d.ts +++ b/types/queries.d.ts @@ -66,6 +66,11 @@ export type FindByText = ( waitForElementOptions?: waitForOptions, ) => Promise +export type ByRoleOptionsName = + | RegExp + | string + | ((accessibleName: string, element: Nullish) => boolean) + export interface ByRoleOptions extends MatcherOptions { /** * If true includes elements in the query set that are usually excluded from @@ -107,10 +112,7 @@ export interface ByRoleOptions extends MatcherOptions { /** * Only considers elements with the specified accessible name. */ - name?: - | RegExp - | string - | ((accessibleName: string, element: Element) => boolean) + name?: ByRoleOptionsName } export type AllByRole = (