@testing-library/react-native 12.0.0 → 12.1.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +1 -0
- package/build/act.js +2 -0
- package/build/act.js.map +1 -1
- package/build/fireEvent.js +3 -4
- package/build/fireEvent.js.map +1 -1
- package/build/flushMicroTasks.d.ts +1 -1
- package/build/flushMicroTasks.js.map +1 -1
- package/build/helpers/format-default.d.ts +5 -0
- package/build/helpers/format-default.js +57 -0
- package/build/helpers/format-default.js.map +1 -0
- package/build/helpers/format.d.ts +1 -1
- package/build/helpers/format.js +5 -1
- package/build/helpers/format.js.map +1 -1
- package/build/helpers/host-component-names.js +15 -18
- package/build/helpers/host-component-names.js.map +1 -1
- package/build/helpers/matchers/accessibilityState.js +4 -0
- package/build/helpers/matchers/accessibilityState.js.map +1 -1
- package/build/index.flow.js +1 -1
- package/build/queries/makeQueries.js +61 -14
- package/build/queries/makeQueries.js.map +1 -1
- package/build/render-act.d.ts +3 -0
- package/build/render-act.js +18 -0
- package/build/render-act.js.map +1 -0
- package/build/render.d.ts +12 -12
- package/build/render.js +9 -18
- package/build/render.js.map +1 -1
- package/build/waitFor.d.ts +1 -1
- package/build/waitFor.js +14 -3
- package/build/waitFor.js.map +1 -1
- package/package.json +7 -4
- package/typings/index.flow.js +1 -1
package/README.md
CHANGED
|
@@ -137,6 +137,7 @@ The [public API](https://callstack.github.io/react-native-testing-library/docs/a
|
|
|
137
137
|
|
|
138
138
|
## Migration Guides
|
|
139
139
|
|
|
140
|
+
- [Migration to 12.0](https://callstack.github.io/react-native-testing-library/docs/migration-v12)
|
|
140
141
|
- [Migration to 11.0](https://callstack.github.io/react-native-testing-library/docs/migration-v11)
|
|
141
142
|
- [Migration to 9.0](https://callstack.github.io/react-native-testing-library/docs/migration-v9)
|
|
142
143
|
- [Migration to 7.0](https://callstack.github.io/react-native-testing-library/docs/migration-v7)
|
package/build/act.js
CHANGED
|
@@ -11,6 +11,8 @@ var _reactVersions = require("./react-versions");
|
|
|
11
11
|
// This file and the act() implementation is sourced from react-testing-library
|
|
12
12
|
// https://github.com/testing-library/react-testing-library/blob/c80809a956b0b9f3289c4a6fa8b5e8cc72d6ef6d/src/act-compat.js
|
|
13
13
|
|
|
14
|
+
// See https://github.com/reactwg/react-18/discussions/102 for more context on global.IS_REACT_ACT_ENVIRONMENT
|
|
15
|
+
|
|
14
16
|
function setIsReactActEnvironment(isReactActEnvironment) {
|
|
15
17
|
globalThis.IS_REACT_ACT_ENVIRONMENT = isReactActEnvironment;
|
|
16
18
|
}
|
package/build/act.js.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"act.js","names":["_reactTestRenderer","require","_reactVersions","setIsReactActEnvironment","isReactActEnvironment","globalThis","IS_REACT_ACT_ENVIRONMENT","getIsReactActEnvironment","withGlobalActEnvironment","actImplementation","callback","previousActEnvironment","callbackNeedsToBeAwaited","actResult","result","then","thenable","resolve","reject","returnValue","error","act","checkReactVersionAtLeast","reactTestRendererAct","_default","exports","default"],"sources":["../src/act.ts"],"sourcesContent":["// This file and the act() implementation is sourced from react-testing-library\n// https://github.com/testing-library/react-testing-library/blob/c80809a956b0b9f3289c4a6fa8b5e8cc72d6ef6d/src/act-compat.js\nimport { act as reactTestRendererAct } from 'react-test-renderer';\nimport { checkReactVersionAtLeast } from './react-versions';\n\ntype ReactAct = typeof reactTestRendererAct;\n\n// See https://github.com/reactwg/react-18/discussions/102 for more context on global.IS_REACT_ACT_ENVIRONMENT\ndeclare global {\n var IS_REACT_ACT_ENVIRONMENT: boolean | undefined;\n}\n\nfunction setIsReactActEnvironment(isReactActEnvironment: boolean | undefined) {\n globalThis.IS_REACT_ACT_ENVIRONMENT = isReactActEnvironment;\n}\n\nfunction getIsReactActEnvironment() {\n return globalThis.IS_REACT_ACT_ENVIRONMENT;\n}\n\nfunction withGlobalActEnvironment(actImplementation: ReactAct) {\n return (callback: Parameters<ReactAct>[0]) => {\n const previousActEnvironment = getIsReactActEnvironment();\n setIsReactActEnvironment(true);\n\n // this code is riddled with eslint disabling comments because this doesn't use real promises but eslint thinks we do\n try {\n // The return value of `act` is always a thenable.\n let callbackNeedsToBeAwaited = false;\n const actResult = actImplementation(() => {\n const result = callback();\n if (\n result !== null &&\n typeof result === 'object' &&\n // @ts-expect-error this should be a promise or thenable\n // eslint-disable-next-line promise/prefer-await-to-then\n typeof result.then === 'function'\n ) {\n callbackNeedsToBeAwaited = true;\n }\n return result;\n });\n\n if (callbackNeedsToBeAwaited) {\n const thenable = actResult;\n return {\n then: (\n resolve: (value: never) => never,\n reject: (value: never) => never\n ) => {\n // eslint-disable-next-line\n thenable.then(\n // eslint-disable-next-line promise/always-return\n (returnValue) => {\n setIsReactActEnvironment(previousActEnvironment);\n resolve(returnValue);\n },\n (error) => {\n setIsReactActEnvironment(previousActEnvironment);\n reject(error);\n }\n );\n },\n };\n } else {\n setIsReactActEnvironment(previousActEnvironment);\n return actResult;\n }\n } catch (error) {\n // Can't be a `finally {}` block since we don't know if we have to immediately restore IS_REACT_ACT_ENVIRONMENT\n // or if we have to await the callback first.\n setIsReactActEnvironment(previousActEnvironment);\n throw error;\n }\n };\n}\n\nconst act: ReactAct = checkReactVersionAtLeast(18, 0)\n ? (withGlobalActEnvironment(reactTestRendererAct) as ReactAct)\n : reactTestRendererAct;\n\nexport default act;\nexport {\n setIsReactActEnvironment as setReactActEnvironment,\n getIsReactActEnvironment,\n};\n"],"mappings":";;;;;;;;AAEA,IAAAA,kBAAA,GAAAC,OAAA;AACA,IAAAC,cAAA,GAAAD,OAAA;AAHA;AACA;;
|
|
1
|
+
{"version":3,"file":"act.js","names":["_reactTestRenderer","require","_reactVersions","setIsReactActEnvironment","isReactActEnvironment","globalThis","IS_REACT_ACT_ENVIRONMENT","getIsReactActEnvironment","withGlobalActEnvironment","actImplementation","callback","previousActEnvironment","callbackNeedsToBeAwaited","actResult","result","then","thenable","resolve","reject","returnValue","error","act","checkReactVersionAtLeast","reactTestRendererAct","_default","exports","default"],"sources":["../src/act.ts"],"sourcesContent":["// This file and the act() implementation is sourced from react-testing-library\n// https://github.com/testing-library/react-testing-library/blob/c80809a956b0b9f3289c4a6fa8b5e8cc72d6ef6d/src/act-compat.js\nimport { act as reactTestRendererAct } from 'react-test-renderer';\nimport { checkReactVersionAtLeast } from './react-versions';\n\ntype ReactAct = typeof reactTestRendererAct;\n\n// See https://github.com/reactwg/react-18/discussions/102 for more context on global.IS_REACT_ACT_ENVIRONMENT\ndeclare global {\n var IS_REACT_ACT_ENVIRONMENT: boolean | undefined;\n}\n\nfunction setIsReactActEnvironment(isReactActEnvironment: boolean | undefined) {\n globalThis.IS_REACT_ACT_ENVIRONMENT = isReactActEnvironment;\n}\n\nfunction getIsReactActEnvironment() {\n return globalThis.IS_REACT_ACT_ENVIRONMENT;\n}\n\nfunction withGlobalActEnvironment(actImplementation: ReactAct) {\n return (callback: Parameters<ReactAct>[0]) => {\n const previousActEnvironment = getIsReactActEnvironment();\n setIsReactActEnvironment(true);\n\n // this code is riddled with eslint disabling comments because this doesn't use real promises but eslint thinks we do\n try {\n // The return value of `act` is always a thenable.\n let callbackNeedsToBeAwaited = false;\n const actResult = actImplementation(() => {\n const result = callback();\n if (\n result !== null &&\n typeof result === 'object' &&\n // @ts-expect-error this should be a promise or thenable\n // eslint-disable-next-line promise/prefer-await-to-then\n typeof result.then === 'function'\n ) {\n callbackNeedsToBeAwaited = true;\n }\n return result;\n });\n\n if (callbackNeedsToBeAwaited) {\n const thenable = actResult;\n return {\n then: (\n resolve: (value: never) => never,\n reject: (value: never) => never\n ) => {\n // eslint-disable-next-line\n thenable.then(\n // eslint-disable-next-line promise/always-return\n (returnValue) => {\n setIsReactActEnvironment(previousActEnvironment);\n resolve(returnValue);\n },\n (error) => {\n setIsReactActEnvironment(previousActEnvironment);\n reject(error);\n }\n );\n },\n };\n } else {\n setIsReactActEnvironment(previousActEnvironment);\n return actResult;\n }\n } catch (error) {\n // Can't be a `finally {}` block since we don't know if we have to immediately restore IS_REACT_ACT_ENVIRONMENT\n // or if we have to await the callback first.\n setIsReactActEnvironment(previousActEnvironment);\n throw error;\n }\n };\n}\n\nconst act: ReactAct = checkReactVersionAtLeast(18, 0)\n ? (withGlobalActEnvironment(reactTestRendererAct) as ReactAct)\n : reactTestRendererAct;\n\nexport default act;\nexport {\n setIsReactActEnvironment as setReactActEnvironment,\n getIsReactActEnvironment,\n};\n"],"mappings":";;;;;;;;AAEA,IAAAA,kBAAA,GAAAC,OAAA;AACA,IAAAC,cAAA,GAAAD,OAAA;AAHA;AACA;;AAMA;;AAKA,SAASE,wBAAwBA,CAACC,qBAA0C,EAAE;EAC5EC,UAAU,CAACC,wBAAwB,GAAGF,qBAAqB;AAC7D;AAEA,SAASG,wBAAwBA,CAAA,EAAG;EAClC,OAAOF,UAAU,CAACC,wBAAwB;AAC5C;AAEA,SAASE,wBAAwBA,CAACC,iBAA2B,EAAE;EAC7D,OAAQC,QAAiC,IAAK;IAC5C,MAAMC,sBAAsB,GAAGJ,wBAAwB,EAAE;IACzDJ,wBAAwB,CAAC,IAAI,CAAC;;IAE9B;IACA,IAAI;MACF;MACA,IAAIS,wBAAwB,GAAG,KAAK;MACpC,MAAMC,SAAS,GAAGJ,iBAAiB,CAAC,MAAM;QACxC,MAAMK,MAAM,GAAGJ,QAAQ,EAAE;QACzB,IACEI,MAAM,KAAK,IAAI,IACf,OAAOA,MAAM,KAAK,QAAQ;QAC1B;QACA;QACA,OAAOA,MAAM,CAACC,IAAI,KAAK,UAAU,EACjC;UACAH,wBAAwB,GAAG,IAAI;QACjC;QACA,OAAOE,MAAM;MACf,CAAC,CAAC;MAEF,IAAIF,wBAAwB,EAAE;QAC5B,MAAMI,QAAQ,GAAGH,SAAS;QAC1B,OAAO;UACLE,IAAI,EAAEA,CACJE,OAAgC,EAChCC,MAA+B,KAC5B;YACH;YACAF,QAAQ,CAACD,IAAI;YACX;YACCI,WAAW,IAAK;cACfhB,wBAAwB,CAACQ,sBAAsB,CAAC;cAChDM,OAAO,CAACE,WAAW,CAAC;YACtB,CAAC,EACAC,KAAK,IAAK;cACTjB,wBAAwB,CAACQ,sBAAsB,CAAC;cAChDO,MAAM,CAACE,KAAK,CAAC;YACf,CAAC,CACF;UACH;QACF,CAAC;MACH,CAAC,MAAM;QACLjB,wBAAwB,CAACQ,sBAAsB,CAAC;QAChD,OAAOE,SAAS;MAClB;IACF,CAAC,CAAC,OAAOO,KAAK,EAAE;MACd;MACA;MACAjB,wBAAwB,CAACQ,sBAAsB,CAAC;MAChD,MAAMS,KAAK;IACb;EACF,CAAC;AACH;AAEA,MAAMC,GAAa,GAAG,IAAAC,uCAAwB,EAAC,EAAE,EAAE,CAAC,CAAC,GAChDd,wBAAwB,CAACe,sBAAoB,CAAC,GAC/CA,sBAAoB;AAAC,IAAAC,QAAA,GAEVH,GAAG;AAAAI,OAAA,CAAAC,OAAA,GAAAF,QAAA"}
|
package/build/fireEvent.js
CHANGED
|
@@ -15,11 +15,10 @@ const isTextInput = element => {
|
|
|
15
15
|
return false;
|
|
16
16
|
}
|
|
17
17
|
|
|
18
|
-
// We have to test if the element type is either the TextInput component
|
|
19
|
-
// (
|
|
20
|
-
// TextInput (which would be true if it is a host component)
|
|
18
|
+
// We have to test if the element type is either the `TextInput` component
|
|
19
|
+
// (for composite component) or the string "TextInput" (for host component)
|
|
21
20
|
// All queries return host components but since fireEvent bubbles up
|
|
22
|
-
// it would trigger the parent prop without the composite component check
|
|
21
|
+
// it would trigger the parent prop without the composite component check.
|
|
23
22
|
return (0, _filterNodeByType.filterNodeByType)(element, _reactNative.TextInput) || (0, _filterNodeByType.filterNodeByType)(element, (0, _hostComponentNames.getHostComponentNames)().textInput);
|
|
24
23
|
};
|
|
25
24
|
const isTouchResponder = element => {
|
package/build/fireEvent.js.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"fireEvent.js","names":["_reactNative","require","_act","_interopRequireDefault","_componentTree","_filterNodeByType","_hostComponentNames","obj","__esModule","default","isTextInput","element","filterNodeByType","TextInput","getHostComponentNames","textInput","isTouchResponder","isHostElement","props","onStartShouldSetResponder","isPointerEventEnabled","isParent","parentCondition","pointerEvents","parent","isTouchEvent","eventName","isEventEnabled","touchResponder","editable","touchStart","touchMove","onMoveShouldSetResponder","undefined","findEventHandler","callsite","nearestTouchResponder","handler","getEventHandler","eventHandlerName","toEventHandlerName","invokeEvent","data","returnValue","act","charAt","toUpperCase","slice","pressHandler","changeTextHandler","scrollHandler","fireEvent","press","changeText","scroll","_default","exports"],"sources":["../src/fireEvent.ts"],"sourcesContent":["import { ReactTestInstance } from 'react-test-renderer';\nimport { TextInput } from 'react-native';\nimport act from './act';\nimport { isHostElement } from './helpers/component-tree';\nimport { filterNodeByType } from './helpers/filterNodeByType';\nimport { getHostComponentNames } from './helpers/host-component-names';\n\ntype EventHandler = (...args: any) => unknown;\n\nconst isTextInput = (element?: ReactTestInstance) => {\n if (!element) {\n return false;\n }\n\n // We have to test if the element type is either the TextInput component\n // (
|
|
1
|
+
{"version":3,"file":"fireEvent.js","names":["_reactNative","require","_act","_interopRequireDefault","_componentTree","_filterNodeByType","_hostComponentNames","obj","__esModule","default","isTextInput","element","filterNodeByType","TextInput","getHostComponentNames","textInput","isTouchResponder","isHostElement","props","onStartShouldSetResponder","isPointerEventEnabled","isParent","parentCondition","pointerEvents","parent","isTouchEvent","eventName","isEventEnabled","touchResponder","editable","touchStart","touchMove","onMoveShouldSetResponder","undefined","findEventHandler","callsite","nearestTouchResponder","handler","getEventHandler","eventHandlerName","toEventHandlerName","invokeEvent","data","returnValue","act","charAt","toUpperCase","slice","pressHandler","changeTextHandler","scrollHandler","fireEvent","press","changeText","scroll","_default","exports"],"sources":["../src/fireEvent.ts"],"sourcesContent":["import { ReactTestInstance } from 'react-test-renderer';\nimport { TextInput } from 'react-native';\nimport act from './act';\nimport { isHostElement } from './helpers/component-tree';\nimport { filterNodeByType } from './helpers/filterNodeByType';\nimport { getHostComponentNames } from './helpers/host-component-names';\n\ntype EventHandler = (...args: any) => unknown;\n\nconst isTextInput = (element?: ReactTestInstance) => {\n if (!element) {\n return false;\n }\n\n // We have to test if the element type is either the `TextInput` component\n // (for composite component) or the string \"TextInput\" (for host component)\n // All queries return host components but since fireEvent bubbles up\n // it would trigger the parent prop without the composite component check.\n return (\n filterNodeByType(element, TextInput) ||\n filterNodeByType(element, getHostComponentNames().textInput)\n );\n};\n\nconst isTouchResponder = (element?: ReactTestInstance) => {\n if (!isHostElement(element)) return false;\n\n return !!element?.props.onStartShouldSetResponder || isTextInput(element);\n};\n\nconst isPointerEventEnabled = (\n element?: ReactTestInstance,\n isParent?: boolean\n): boolean => {\n const parentCondition = isParent\n ? element?.props.pointerEvents === 'box-only'\n : element?.props.pointerEvents === 'box-none';\n\n if (element?.props.pointerEvents === 'none' || parentCondition) {\n return false;\n }\n\n if (!element?.parent) return true;\n\n return isPointerEventEnabled(element.parent, true);\n};\n\nconst isTouchEvent = (eventName?: string) => {\n return eventName === 'press';\n};\n\nconst isEventEnabled = (\n element?: ReactTestInstance,\n touchResponder?: ReactTestInstance,\n eventName?: string\n) => {\n if (isTextInput(element)) return element?.props.editable !== false;\n if (!isPointerEventEnabled(element) && isTouchEvent(eventName)) return false;\n\n const touchStart = touchResponder?.props.onStartShouldSetResponder?.();\n const touchMove = touchResponder?.props.onMoveShouldSetResponder?.();\n\n if (touchStart || touchMove) return true;\n\n return touchStart === undefined && touchMove === undefined;\n};\n\nconst findEventHandler = (\n element: ReactTestInstance,\n eventName: string,\n callsite?: any,\n nearestTouchResponder?: ReactTestInstance\n): EventHandler | null => {\n const touchResponder = isTouchResponder(element)\n ? element\n : nearestTouchResponder;\n\n const handler = getEventHandler(element, eventName);\n if (handler && isEventEnabled(element, touchResponder, eventName))\n return handler;\n\n if (element.parent === null || element.parent.parent === null) {\n return null;\n }\n\n return findEventHandler(element.parent, eventName, callsite, touchResponder);\n};\n\nconst getEventHandler = (\n element: ReactTestInstance,\n eventName: string\n): EventHandler | undefined => {\n const eventHandlerName = toEventHandlerName(eventName);\n if (typeof element.props[eventHandlerName] === 'function') {\n return element.props[eventHandlerName];\n }\n\n if (typeof element.props[eventName] === 'function') {\n return element.props[eventName];\n }\n\n return undefined;\n};\n\nconst invokeEvent = (\n element: ReactTestInstance,\n eventName: string,\n callsite?: any,\n ...data: Array<any>\n) => {\n const handler = findEventHandler(element, eventName, callsite);\n\n if (!handler) {\n return;\n }\n\n let returnValue;\n\n act(() => {\n returnValue = handler(...data);\n });\n\n return returnValue;\n};\n\nconst toEventHandlerName = (eventName: string) =>\n `on${eventName.charAt(0).toUpperCase()}${eventName.slice(1)}`;\n\nconst pressHandler = (element: ReactTestInstance, ...data: Array<any>): void =>\n invokeEvent(element, 'press', pressHandler, ...data);\nconst changeTextHandler = (\n element: ReactTestInstance,\n ...data: Array<any>\n): void => invokeEvent(element, 'changeText', changeTextHandler, ...data);\nconst scrollHandler = (element: ReactTestInstance, ...data: Array<any>): void =>\n invokeEvent(element, 'scroll', scrollHandler, ...data);\n\nconst fireEvent = (\n element: ReactTestInstance,\n eventName: string,\n ...data: Array<any>\n): void => invokeEvent(element, eventName, fireEvent, ...data);\n\nfireEvent.press = pressHandler;\nfireEvent.changeText = changeTextHandler;\nfireEvent.scroll = scrollHandler;\n\nexport default fireEvent;\n"],"mappings":";;;;;;AACA,IAAAA,YAAA,GAAAC,OAAA;AACA,IAAAC,IAAA,GAAAC,sBAAA,CAAAF,OAAA;AACA,IAAAG,cAAA,GAAAH,OAAA;AACA,IAAAI,iBAAA,GAAAJ,OAAA;AACA,IAAAK,mBAAA,GAAAL,OAAA;AAAuE,SAAAE,uBAAAI,GAAA,WAAAA,GAAA,IAAAA,GAAA,CAAAC,UAAA,GAAAD,GAAA,KAAAE,OAAA,EAAAF,GAAA;AAIvE,MAAMG,WAAW,GAAIC,OAA2B,IAAK;EACnD,IAAI,CAACA,OAAO,EAAE;IACZ,OAAO,KAAK;EACd;;EAEA;EACA;EACA;EACA;EACA,OACE,I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C,QAAA"}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"flushMicroTasks.js","names":["_timers","require","flushMicroTasks","then","resolve","setImmediate"],"sources":["../src/flushMicroTasks.ts"],"sourcesContent":["import { setImmediate } from './helpers/timers';\n\ntype Thenable<T> = { then: (callback: () => T) => unknown };\n\nexport function flushMicroTasks
|
|
1
|
+
{"version":3,"file":"flushMicroTasks.js","names":["_timers","require","flushMicroTasks","then","resolve","setImmediate"],"sources":["../src/flushMicroTasks.ts"],"sourcesContent":["import { setImmediate } from './helpers/timers';\n\ntype Thenable<T> = { then: (callback: () => T) => unknown };\n\nexport function flushMicroTasks(): Thenable<void> {\n return {\n // using \"thenable\" instead of a Promise, because otherwise it breaks when\n // using \"modern\" fake timers\n then(resolve) {\n setImmediate(resolve);\n },\n };\n}\n"],"mappings":";;;;;;AAAA,IAAAA,OAAA,GAAAC,OAAA;AAIO,SAASC,eAAeA,CAAA,EAAmB;EAChD,OAAO;IACL;IACA;IACAC,IAAIA,CAACC,OAAO,EAAE;MACZ,IAAAC,oBAAY,EAACD,OAAO,CAAC;IACvB;EACF,CAAC;AACH"}
|
|
@@ -0,0 +1,57 @@
|
|
|
1
|
+
"use strict";
|
|
2
|
+
|
|
3
|
+
Object.defineProperty(exports, "__esModule", {
|
|
4
|
+
value: true
|
|
5
|
+
});
|
|
6
|
+
exports.defaultMapProps = void 0;
|
|
7
|
+
var _reactNative = require("react-native");
|
|
8
|
+
const propsToDisplay = ['testID', 'nativeID', 'accessibilityElementsHidden', 'accessibilityViewIsModal', 'importantForAccessibility', 'accessibilityRole', 'accessibilityLabel', 'accessibilityLabelledBy', 'accessibilityHint', 'placeholder', 'value', 'defaultValue', 'title'];
|
|
9
|
+
|
|
10
|
+
/**
|
|
11
|
+
* Preserve props that are helpful in diagnosing test failures, while stripping rest
|
|
12
|
+
*/
|
|
13
|
+
const defaultMapProps = props => {
|
|
14
|
+
const result = {};
|
|
15
|
+
const styles = _reactNative.StyleSheet.flatten(props.style);
|
|
16
|
+
if (styles?.display === 'none') {
|
|
17
|
+
result.style = {
|
|
18
|
+
display: 'none'
|
|
19
|
+
};
|
|
20
|
+
}
|
|
21
|
+
const accessibilityState = removeUndefinedKeys(props.accessibilityState);
|
|
22
|
+
if (accessibilityState !== undefined) {
|
|
23
|
+
result.accessibilityState = accessibilityState;
|
|
24
|
+
}
|
|
25
|
+
const accessibilityValue = removeUndefinedKeys(props.accessibilityValue);
|
|
26
|
+
if (accessibilityValue !== undefined) {
|
|
27
|
+
result.accessibilityValue = accessibilityValue;
|
|
28
|
+
}
|
|
29
|
+
propsToDisplay.forEach(propName => {
|
|
30
|
+
if (propName in props) {
|
|
31
|
+
result[propName] = props[propName];
|
|
32
|
+
}
|
|
33
|
+
});
|
|
34
|
+
return result;
|
|
35
|
+
};
|
|
36
|
+
exports.defaultMapProps = defaultMapProps;
|
|
37
|
+
function isObject(value) {
|
|
38
|
+
return typeof value === 'object' && value !== null && !Array.isArray(value);
|
|
39
|
+
}
|
|
40
|
+
function removeUndefinedKeys(prop) {
|
|
41
|
+
if (!isObject(prop)) {
|
|
42
|
+
return prop;
|
|
43
|
+
}
|
|
44
|
+
const result = {};
|
|
45
|
+
Object.entries(prop).forEach(([key, value]) => {
|
|
46
|
+
if (value !== undefined) {
|
|
47
|
+
result[key] = value;
|
|
48
|
+
}
|
|
49
|
+
});
|
|
50
|
+
|
|
51
|
+
// If object does not have any props we will ignore it.
|
|
52
|
+
if (Object.keys(result).length === 0) {
|
|
53
|
+
return undefined;
|
|
54
|
+
}
|
|
55
|
+
return result;
|
|
56
|
+
}
|
|
57
|
+
//# sourceMappingURL=format-default.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"format-default.js","names":["_reactNative","require","propsToDisplay","defaultMapProps","props","result","styles","StyleSheet","flatten","style","display","accessibilityState","removeUndefinedKeys","undefined","accessibilityValue","forEach","propName","exports","isObject","value","Array","isArray","prop","Object","entries","key","keys","length"],"sources":["../../src/helpers/format-default.ts"],"sourcesContent":["import { StyleSheet, ViewStyle } from 'react-native';\nimport { MapPropsFunction } from './format';\n\nconst propsToDisplay = [\n 'testID',\n 'nativeID',\n 'accessibilityElementsHidden',\n 'accessibilityViewIsModal',\n 'importantForAccessibility',\n 'accessibilityRole',\n 'accessibilityLabel',\n 'accessibilityLabelledBy',\n 'accessibilityHint',\n 'placeholder',\n 'value',\n 'defaultValue',\n 'title',\n];\n\n/**\n * Preserve props that are helpful in diagnosing test failures, while stripping rest\n */\nexport const defaultMapProps: MapPropsFunction = (props) => {\n const result: Record<string, unknown> = {};\n\n const styles = StyleSheet.flatten(props.style as ViewStyle);\n if (styles?.display === 'none') {\n result.style = { display: 'none' };\n }\n\n const accessibilityState = removeUndefinedKeys(props.accessibilityState);\n if (accessibilityState !== undefined) {\n result.accessibilityState = accessibilityState;\n }\n\n const accessibilityValue = removeUndefinedKeys(props.accessibilityValue);\n if (accessibilityValue !== undefined) {\n result.accessibilityValue = accessibilityValue;\n }\n\n propsToDisplay.forEach((propName) => {\n if (propName in props) {\n result[propName] = props[propName];\n }\n });\n\n return result;\n};\n\nfunction isObject(value: unknown): value is Record<string, unknown> {\n return typeof value === 'object' && value !== null && !Array.isArray(value);\n}\n\nfunction removeUndefinedKeys(prop: unknown) {\n if (!isObject(prop)) {\n return prop;\n }\n\n const result: Record<string, unknown> = {};\n Object.entries(prop).forEach(([key, value]) => {\n if (value !== undefined) {\n result[key] = value;\n }\n });\n\n // If object does not have any props we will ignore it.\n if (Object.keys(result).length === 0) {\n return undefined;\n }\n\n return result;\n}\n"],"mappings":";;;;;;AAAA,IAAAA,YAAA,GAAAC,OAAA;AAGA,MAAMC,cAAc,GAAG,CACrB,QAAQ,EACR,UAAU,EACV,6BAA6B,EAC7B,0BAA0B,EAC1B,2BAA2B,EAC3B,mBAAmB,EACnB,oBAAoB,EACpB,yBAAyB,EACzB,mBAAmB,EACnB,aAAa,EACb,OAAO,EACP,cAAc,EACd,OAAO,CACR;;AAED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AAC,CAACU,GAAG,EAAEN,KAAK,CAAC,KAAK;IAC7C,IAAIA,KAAK,KAAKN,SAAS,EAAE;MACvBR,MAAM,CAACoB,GAAG,CAAC,GAAGN,KAAK;IACrB;EACF,CAAC,CAAC;;EAEF;EACA,IAAII,MAAM,CAACG,IAAI,CAACrB,MAAM,CAAC,CAACsB,MAAM,KAAK,CAAC,EAAE;IACpC,OAAOd,SAAS;EAClB;EAEA,OAAOR,MAAM;AACf"}
|
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
import type { ReactTestRendererJSON } from 'react-test-renderer';
|
|
2
|
-
type MapPropsFunction = (props: Record<string, unknown>, node: ReactTestRendererJSON) => Record<string, unknown>;
|
|
2
|
+
export type MapPropsFunction = (props: Record<string, unknown>, node: ReactTestRendererJSON) => Record<string, unknown>;
|
|
3
3
|
export type FormatOptions = {
|
|
4
4
|
mapProps?: MapPropsFunction;
|
|
5
5
|
};
|
package/build/helpers/format.js
CHANGED
|
@@ -9,7 +9,8 @@ function _getRequireWildcardCache(nodeInterop) { if (typeof WeakMap !== "functio
|
|
|
9
9
|
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; }
|
|
10
10
|
const format = (input, options = {}) => (0, _prettyFormat.default)(input, {
|
|
11
11
|
plugins: [getCustomPlugin(options.mapProps), _prettyFormat.plugins.ReactElement],
|
|
12
|
-
highlight:
|
|
12
|
+
highlight: shouldHighlight(),
|
|
13
|
+
printBasicPrototype: false
|
|
13
14
|
});
|
|
14
15
|
const getCustomPlugin = mapProps => {
|
|
15
16
|
return {
|
|
@@ -26,6 +27,9 @@ const getCustomPlugin = mapProps => {
|
|
|
26
27
|
}
|
|
27
28
|
};
|
|
28
29
|
};
|
|
30
|
+
function shouldHighlight() {
|
|
31
|
+
return process?.env?.COLORS !== 'false';
|
|
32
|
+
}
|
|
29
33
|
var _default = format;
|
|
30
34
|
exports.default = _default;
|
|
31
35
|
//# sourceMappingURL=format.js.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"format.js","names":["_prettyFormat","_interopRequireWildcard","require","_getRequireWildcardCache","nodeInterop","WeakMap","cacheBabelInterop","cacheNodeInterop","obj","__esModule","default","cache","has","get","newObj","hasPropertyDescriptor","Object","defineProperty","getOwnPropertyDescriptor","key","prototype","hasOwnProperty","call","desc","set","format","input","options","prettyFormat","plugins","getCustomPlugin","mapProps","ReactElement","highlight","test","val","ReactTestComponent","serialize","config","indentation","depth","refs","printer","newVal","props","_default","exports"],"sources":["../../src/helpers/format.ts"],"sourcesContent":["import type { ReactTestRendererJSON } from 'react-test-renderer';\nimport prettyFormat, { NewPlugin, plugins } from 'pretty-format';\n\
|
|
1
|
+
{"version":3,"file":"format.js","names":["_prettyFormat","_interopRequireWildcard","require","_getRequireWildcardCache","nodeInterop","WeakMap","cacheBabelInterop","cacheNodeInterop","obj","__esModule","default","cache","has","get","newObj","hasPropertyDescriptor","Object","defineProperty","getOwnPropertyDescriptor","key","prototype","hasOwnProperty","call","desc","set","format","input","options","prettyFormat","plugins","getCustomPlugin","mapProps","ReactElement","highlight","shouldHighlight","printBasicPrototype","test","val","ReactTestComponent","serialize","config","indentation","depth","refs","printer","newVal","props","process","env","COLORS","_default","exports"],"sources":["../../src/helpers/format.ts"],"sourcesContent":["import type { ReactTestRendererJSON } from 'react-test-renderer';\nimport prettyFormat, { NewPlugin, plugins } from 'pretty-format';\n\nexport type MapPropsFunction = (\n props: Record<string, unknown>,\n node: ReactTestRendererJSON\n) => Record<string, unknown>;\n\nexport type FormatOptions = {\n mapProps?: MapPropsFunction;\n};\n\nconst format = (\n input: ReactTestRendererJSON | ReactTestRendererJSON[],\n options: FormatOptions = {}\n) =>\n prettyFormat(input, {\n plugins: [getCustomPlugin(options.mapProps), plugins.ReactElement],\n highlight: shouldHighlight(),\n printBasicPrototype: false,\n });\n\nconst getCustomPlugin = (mapProps?: MapPropsFunction): NewPlugin => {\n return {\n test: (val) => plugins.ReactTestComponent.test(val),\n serialize: (val, config, indentation, depth, refs, printer) => {\n let newVal = val;\n if (mapProps && val.props) {\n newVal = { ...val, props: mapProps(val.props, val) };\n }\n return plugins.ReactTestComponent.serialize(\n newVal,\n config,\n indentation,\n depth,\n refs,\n printer\n );\n },\n };\n};\n\nfunction shouldHighlight() {\n return process?.env?.COLORS !== 'false';\n}\n\nexport default format;\n"],"mappings":";;;;;;AACA,IAAAA,aAAA,GAAAC,uBAAA,CAAAC,OAAA;AAAiE,SAAAC,yBAAAC,WAAA,eAAAC,OAAA,kCAAAC,iBAAA,OAAAD,OAAA,QAAAE,gBAAA,OAAAF,OAAA,YAAAF,wBAAA,YAAAA,CAAAC,WAAA,WAAAA,WAAA,GAAAG,gBAAA,GAAAD,iBAAA,KAAAF,WAAA;AAAA,SAAAH,wBAAAO,GAAA,EAAAJ,WAAA,SAAAA,WAAA,IAAAI,GAAA,IAAAA,GAAA,CAAAC,UAAA,WAAAD,GAAA,QAAAA,GAAA,oBAAAA,GAAA,wBAAAA,GAAA,4BAAAE,OAAA,EAAAF,GAAA,UAAAG,KAAA,GAAAR,wBAAA,CAAAC,WAAA,OAAAO,KAAA,IAAAA,KAAA,CAAAC,GAAA,CAAAJ,GAAA,YAAAG,KAAA,CAAAE,GAAA,CAAAL,GAAA,SAAAM,MAAA,WAAAC,qBAAA,GAAAC,MAAA,CAAAC,cAAA,IAAAD,MAAA,CAAAE,wB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AC;MACtD;MACA,OAAOR,qBAAO,CAACS,kBAAkB,CAACC,SAAS,CACzCM,MAAM,EACNL,MAAM,EACNC,WAAW,EACXC,KAAK,EACLC,IAAI,EACJC,OAAO,CACR;IACH;EACF,CAAC;AACH,CAAC;AAED,SAASV,eAAeA,CAAA,EAAG;EACzB,OAAOa,OAAO,EAAEC,GAAG,EAAEC,MAAM,KAAK,OAAO;AACzC;AAAC,IAAAC,QAAA,GAEczB,MAAM;AAAA0B,OAAA,CAAAzC,OAAA,GAAAwC,QAAA"}
|
|
@@ -5,12 +5,12 @@ Object.defineProperty(exports, "__esModule", {
|
|
|
5
5
|
});
|
|
6
6
|
exports.configureHostComponentNamesIfNeeded = configureHostComponentNamesIfNeeded;
|
|
7
7
|
exports.getHostComponentNames = getHostComponentNames;
|
|
8
|
-
var
|
|
8
|
+
var React = _interopRequireWildcard(require("react"));
|
|
9
9
|
var _reactNative = require("react-native");
|
|
10
|
-
var _reactTestRenderer = _interopRequireDefault(require("react-test-renderer"));
|
|
11
10
|
var _config = require("../config");
|
|
12
|
-
var
|
|
13
|
-
function
|
|
11
|
+
var _renderAct = require("../render-act");
|
|
12
|
+
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); }
|
|
13
|
+
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; }
|
|
14
14
|
const userConfigErrorMessage = `There seems to be an issue with your configuration that prevents React Native Testing Library from working correctly.
|
|
15
15
|
Please check if you are using compatible versions of React Native and React Native Testing Library.`;
|
|
16
16
|
function getHostComponentNames() {
|
|
@@ -35,28 +35,25 @@ function configureHostComponentNamesIfNeeded() {
|
|
|
35
35
|
}
|
|
36
36
|
function detectHostComponentNames() {
|
|
37
37
|
try {
|
|
38
|
-
const renderer =
|
|
38
|
+
const renderer = (0, _renderAct.renderWithAct)( /*#__PURE__*/React.createElement(_reactNative.View, null, /*#__PURE__*/React.createElement(_reactNative.Text, {
|
|
39
39
|
testID: "text"
|
|
40
|
-
}, "Hello"), /*#__PURE__*/
|
|
40
|
+
}, "Hello"), /*#__PURE__*/React.createElement(_reactNative.TextInput, {
|
|
41
41
|
testID: "textInput"
|
|
42
42
|
})));
|
|
43
|
-
const {
|
|
44
|
-
getByTestId
|
|
45
|
-
} = (0, _within.getQueriesForElement)(renderer.root);
|
|
46
|
-
const textHostName = getByTestId('text').type;
|
|
47
|
-
const textInputHostName = getByTestId('textInput').type;
|
|
48
|
-
|
|
49
|
-
// This code path should not happen as getByTestId always returns host elements.
|
|
50
|
-
if (typeof textHostName !== 'string' || typeof textInputHostName !== 'string') {
|
|
51
|
-
throw new Error('getByTestId returned non-host component');
|
|
52
|
-
}
|
|
53
43
|
return {
|
|
54
|
-
text:
|
|
55
|
-
textInput:
|
|
44
|
+
text: getByTestId(renderer.root, 'text').type,
|
|
45
|
+
textInput: getByTestId(renderer.root, 'textInput').type
|
|
56
46
|
};
|
|
57
47
|
} catch (error) {
|
|
58
48
|
const errorMessage = error && typeof error === 'object' && 'message' in error ? error.message : null;
|
|
59
49
|
throw new Error(`Trying to detect host component names triggered the following error:\n\n${errorMessage}\n\n${userConfigErrorMessage}`);
|
|
60
50
|
}
|
|
61
51
|
}
|
|
52
|
+
function getByTestId(instance, testID) {
|
|
53
|
+
const nodes = instance.findAll(node => typeof node.type === 'string' && node.props.testID === testID);
|
|
54
|
+
if (nodes.length === 0) {
|
|
55
|
+
throw new Error(`Unable to find an element with testID: ${testID}`);
|
|
56
|
+
}
|
|
57
|
+
return nodes[0];
|
|
58
|
+
}
|
|
62
59
|
//# sourceMappingURL=host-component-names.js.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"host-component-names.js","names":["
|
|
1
|
+
{"version":3,"file":"host-component-names.js","names":["React","_interopRequireWildcard","require","_reactNative","_config","_renderAct","_getRequireWildcardCache","nodeInterop","WeakMap","cacheBabelInterop","cacheNodeInterop","obj","__esModule","default","cache","has","get","newObj","hasPropertyDescriptor","Object","defineProperty","getOwnPropertyDescriptor","key","prototype","hasOwnProperty","call","desc","set","userConfigErrorMessage","getHostComponentNames","hostComponentNames","getConfig","detectHostComponentNames","configureInternal","configureHostComponentNamesIfNeeded","configHostComponentNames","renderer","renderWithAct","createElement","View","Text","testID","TextInput","text","getByTestId","root","type","textInput","error","errorMessage","message","Error","instance","nodes","findAll","node","props","length"],"sources":["../../src/helpers/host-component-names.tsx"],"sourcesContent":["import * as React from 'react';\nimport { ReactTestInstance } from 'react-test-renderer';\nimport { Text, TextInput, View } from 'react-native';\nimport { configureInternal, getConfig, HostComponentNames } from '../config';\nimport { renderWithAct } from '../render-act';\n\nconst userConfigErrorMessage = `There seems to be an issue with your configuration that prevents React Native Testing Library from working correctly.\nPlease check if you are using compatible versions of React Native and React Native Testing Library.`;\n\nexport function getHostComponentNames(): HostComponentNames {\n let hostComponentNames = getConfig().hostComponentNames;\n if (!hostComponentNames) {\n hostComponentNames = detectHostComponentNames();\n configureInternal({ hostComponentNames });\n }\n\n return hostComponentNames;\n}\n\nexport function configureHostComponentNamesIfNeeded() {\n const configHostComponentNames = getConfig().hostComponentNames;\n if (configHostComponentNames) {\n return;\n }\n\n const hostComponentNames = detectHostComponentNames();\n configureInternal({ hostComponentNames });\n}\n\nfunction detectHostComponentNames(): HostComponentNames {\n try {\n const renderer = renderWithAct(\n <View>\n <Text testID=\"text\">Hello</Text>\n <TextInput testID=\"textInput\" />\n </View>\n );\n\n return {\n text: getByTestId(renderer.root, 'text').type as string,\n textInput: getByTestId(renderer.root, 'textInput').type as string,\n };\n } catch (error) {\n const errorMessage =\n error && typeof error === 'object' && 'message' in error\n ? error.message\n : null;\n\n throw new Error(\n `Trying to detect host component names triggered the following error:\\n\\n${errorMessage}\\n\\n${userConfigErrorMessage}`\n );\n }\n}\n\nfunction getByTestId(instance: ReactTestInstance, testID: string) {\n const nodes = instance.findAll(\n (node) => typeof node.type === 'string' && node.props.testID === testID\n );\n\n if (nodes.length === 0) {\n throw new Error(`Unable to find an element with testID: ${testID}`);\n }\n\n return nodes[0];\n}\n"],"mappings":";;;;;;;AAAA,IAAAA,KAAA,GAAAC,uBAAA,CAAAC,OAAA;AAEA,IAAAC,YAAA,GAAAD,OAAA;AACA,IAAAE,OAAA,GAAAF,OAAA;AACA,IAAAG,UAAA,GAAAH,OAAA;AAA8C,SAAAI,yBAAAC,WAAA,eAAAC,OAAA,kCAAAC,iBAAA,OAAAD,OAAA,QAAAE,gBAAA,OAAAF,OAAA,YAAAF,wBAAA,YAAAA,CAAAC,WAAA,WAAAA,WAAA,GAAAG,gBAAA,GAAAD,iBAAA,KAAAF,WAAA;AAAA,SAAAN,wBAAAU,GAAA,EAAAJ,WAAA,SAAAA,WAAA,IAAAI,GAAA,IAAAA,GAAA,CAAAC,UAAA,WAAAD,GAAA,QAAAA,GAAA,oBAAAA,GAAA,wBAAAA,GAAA,4BAAAE,OAAA,EAAAF,GAAA,UAAAG,KAAA,GAAAR,wBAAA,CAAAC,WAAA,OAAAO,KAAA,IAAAA,KAAA,CAAAC,GAAA,CAAAJ,GAAA,YAAAG,KAAA,CAAAE,GAAA,CAAAL,GAAA,SAAAM,MAAA,WAAAC,qBAAA,GAAAC,MAAA,CAAAC,cA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qBACHvC,KAAA,CAAAsC,aAAA,CAACnC,YAAA,CAAAqC,IAAI;MAACC,MAAM,EAAC;IAAM,GAAC,OAAK,CAAO,eAChCzC,KAAA,CAAAsC,aAAA,CAACnC,YAAA,CAAAuC,SAAS;MAACD,MAAM,EAAC;IAAW,EAAG,CAC3B,CACR;IAED,OAAO;MACLE,IAAI,EAAEC,WAAW,CAACR,QAAQ,CAACS,IAAI,EAAE,MAAM,CAAC,CAACC,IAAc;MACvDC,SAAS,EAAEH,WAAW,CAACR,QAAQ,CAACS,IAAI,EAAE,WAAW,CAAC,CAACC;IACrD,CAAC;EACH,CAAC,CAAC,OAAOE,KAAK,EAAE;IACd,MAAMC,YAAY,GAChBD,KAAK,IAAI,OAAOA,KAAK,KAAK,QAAQ,IAAI,SAAS,IAAIA,KAAK,GACpDA,KAAK,CAACE,OAAO,GACb,IAAI;IAEV,MAAM,IAAIC,KAAK,CACZ,2EAA0EF,YAAa,OAAMrB,sBAAuB,EAAC,CACvH;EACH;AACF;AAEA,SAASgB,WAAWA,CAACQ,QAA2B,EAAEX,MAAc,EAAE;EAChE,MAAMY,KAAK,GAAGD,QAAQ,CAACE,OAAO,CAC3BC,IAAI,IAAK,OAAOA,IAAI,CAACT,IAAI,KAAK,QAAQ,IAAIS,IAAI,CAACC,KAAK,CAACf,MAAM,KAAKA,MAAM,CACxE;EAED,IAAIY,KAAK,CAACI,MAAM,KAAK,CAAC,EAAE;IACtB,MAAM,IAAIN,KAAK,CAAE,0CAAyCV,MAAO,EAAC,CAAC;EACrE;EAEA,OAAOY,KAAK,CAAC,CAAC,CAAC;AACjB"}
|
|
@@ -5,6 +5,10 @@ Object.defineProperty(exports, "__esModule", {
|
|
|
5
5
|
});
|
|
6
6
|
exports.matchAccessibilityState = matchAccessibilityState;
|
|
7
7
|
var _accessiblity = require("../accessiblity");
|
|
8
|
+
// This type is the same as AccessibilityState from `react-native` package
|
|
9
|
+
// It is re-declared here due to issues with migration from `@types/react-native` to
|
|
10
|
+
// built in `react-native` types.
|
|
11
|
+
// See: https://github.com/callstack/react-native-testing-library/issues/1351
|
|
8
12
|
/**
|
|
9
13
|
* Default accessibility state values based on experiments using accessibility
|
|
10
14
|
* inspector/screen reader on iOS and Android.
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"accessibilityState.js","names":["_accessiblity","require","defaultState","disabled","selected","checked","undefined","busy","expanded","matchAccessibilityState","node","matcher","state","props","accessibilityState","accessibilityStateKeys","every","key","matchState"],"sources":["../../../src/helpers/matchers/accessibilityState.ts"],"sourcesContent":["import { AccessibilityState } from 'react-native';\nimport { ReactTestInstance } from 'react-test-renderer';\nimport { accessibilityStateKeys } from '../accessiblity';\n\n// This type is the same as AccessibilityState from `react-native` package\n// It is re-declared here due to issues with migration from `@types/react-native` to\n// built in `react-native` types.\n// See: https://github.com/callstack/react-native-testing-library/issues/1351\nexport interface AccessibilityStateMatcher {\n disabled?: boolean;\n selected?: boolean;\n checked?: boolean | 'mixed';\n busy?: boolean;\n expanded?: boolean;\n}\n\n/**\n * Default accessibility state values based on experiments using accessibility\n * inspector/screen reader on iOS and Android.\n *\n * @see https://github.com/callstack/react-native-testing-library/wiki/Accessibility:-State\n */\nconst defaultState: AccessibilityState = {\n disabled: false,\n selected: false,\n checked: undefined,\n busy: false,\n expanded: undefined,\n};\n\nexport function matchAccessibilityState(\n node: ReactTestInstance,\n matcher: AccessibilityStateMatcher\n) {\n const state = node.props.accessibilityState;\n return accessibilityStateKeys.every((key) => matchState(state, matcher, key));\n}\n\nfunction matchState(\n state: AccessibilityState,\n matcher: AccessibilityStateMatcher,\n key: keyof AccessibilityState\n) {\n return (\n matcher[key] === undefined ||\n matcher[key] === (state?.[key] ?? defaultState[key])\n );\n}\n"],"mappings":";;;;;;AAEA,IAAAA,aAAA,GAAAC,OAAA;
|
|
1
|
+
{"version":3,"file":"accessibilityState.js","names":["_accessiblity","require","defaultState","disabled","selected","checked","undefined","busy","expanded","matchAccessibilityState","node","matcher","state","props","accessibilityState","accessibilityStateKeys","every","key","matchState"],"sources":["../../../src/helpers/matchers/accessibilityState.ts"],"sourcesContent":["import { AccessibilityState } from 'react-native';\nimport { ReactTestInstance } from 'react-test-renderer';\nimport { accessibilityStateKeys } from '../accessiblity';\n\n// This type is the same as AccessibilityState from `react-native` package\n// It is re-declared here due to issues with migration from `@types/react-native` to\n// built in `react-native` types.\n// See: https://github.com/callstack/react-native-testing-library/issues/1351\nexport interface AccessibilityStateMatcher {\n disabled?: boolean;\n selected?: boolean;\n checked?: boolean | 'mixed';\n busy?: boolean;\n expanded?: boolean;\n}\n\n/**\n * Default accessibility state values based on experiments using accessibility\n * inspector/screen reader on iOS and Android.\n *\n * @see https://github.com/callstack/react-native-testing-library/wiki/Accessibility:-State\n */\nconst defaultState: AccessibilityState = {\n disabled: false,\n selected: false,\n checked: undefined,\n busy: false,\n expanded: undefined,\n};\n\nexport function matchAccessibilityState(\n node: ReactTestInstance,\n matcher: AccessibilityStateMatcher\n) {\n const state = node.props.accessibilityState;\n return accessibilityStateKeys.every((key) => matchState(state, matcher, key));\n}\n\nfunction matchState(\n state: AccessibilityState,\n matcher: AccessibilityStateMatcher,\n key: keyof AccessibilityState\n) {\n return (\n matcher[key] === undefined ||\n matcher[key] === (state?.[key] ?? defaultState[key])\n );\n}\n"],"mappings":";;;;;;AAEA,IAAAA,aAAA,GAAAC,OAAA;AAEA;AACA;AACA;AACA;AASA;AACA;AACA;AACA;AACA;AACA;AACA,MAAMC,YAAgC,GAAG;EACvCC,QAAQ,EAAE,KAAK;EACfC,QAAQ,EAAE,KAAK;EACfC,OAAO,EAAEC,SAAS;EAClBC,IAAI,EAAE,KAAK;EACXC,QAAQ,EAAEF;AACZ,CAAC;AAEM,SAASG,uBAAuBA,CACrCC,IAAuB,EACvBC,OAAkC,EAClC;EACA,MAAMC,KAAK,GAAGF,IAAI,CAACG,KAAK,CAACC,kBAAkB;EAC3C,OAAOC,oCAAsB,CAACC,KAAK,CAAEC,GAAG,IAAKC,UAAU,CAACN,KAAK,EAAED,OAAO,EAAEM,GAAG,CAAC,CAAC;AAC/E;AAEA,SAASC,UAAUA,CACjBN,KAAyB,EACzBD,OAAkC,EAClCM,GAA6B,EAC7B;EACA,OACEN,OAAO,CAACM,GAAG,CAAC,KAAKX,SAAS,IAC1BK,OAAO,CAACM,GAAG,CAAC,MAAML,KAAK,GAAGK,GAAG,CAAC,IAAIf,YAAY,CAACe,GAAG,CAAC,CAAC;AAExD"}
|
package/build/index.flow.js
CHANGED
|
@@ -6,6 +6,9 @@ Object.defineProperty(exports, "__esModule", {
|
|
|
6
6
|
exports.makeQueries = makeQueries;
|
|
7
7
|
var _errors = require("../helpers/errors");
|
|
8
8
|
var _waitFor = _interopRequireDefault(require("../waitFor"));
|
|
9
|
+
var _format = _interopRequireDefault(require("../helpers/format"));
|
|
10
|
+
var _screen = require("../screen");
|
|
11
|
+
var _formatDefault = require("../helpers/format-default");
|
|
9
12
|
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
|
|
10
13
|
const deprecatedKeys = ['timeout', 'interval', 'stackTraceError'];
|
|
11
14
|
|
|
@@ -24,29 +27,54 @@ function extractDeprecatedWaitForOptions(options) {
|
|
|
24
27
|
const option = options[key];
|
|
25
28
|
if (option) {
|
|
26
29
|
// eslint-disable-next-line no-console
|
|
27
|
-
console.warn(`Use of option "${key}" in a findBy* query options (2nd parameter) is deprecated. Please pass this option in the waitForOptions (3rd parameter).
|
|
28
|
-
Example:
|
|
30
|
+
console.warn(`Use of option "${key}" in a findBy* query options (2nd parameter) is deprecated. Please pass this option in the waitForOptions (3rd parameter).
|
|
31
|
+
Example:
|
|
29
32
|
|
|
30
33
|
findByText(text, {}, { ${key}: ${option.toString()} })`);
|
|
31
34
|
}
|
|
32
35
|
});
|
|
33
36
|
return waitForOptions;
|
|
34
37
|
}
|
|
38
|
+
function formatErrorMessage(message, printElementTree) {
|
|
39
|
+
if (!printElementTree) {
|
|
40
|
+
return message;
|
|
41
|
+
}
|
|
42
|
+
const json = _screen.screen.toJSON();
|
|
43
|
+
if (!json) {
|
|
44
|
+
return message;
|
|
45
|
+
}
|
|
46
|
+
return `${message}\n\n${(0, _format.default)(json, {
|
|
47
|
+
mapProps: _formatDefault.defaultMapProps
|
|
48
|
+
})}`;
|
|
49
|
+
}
|
|
50
|
+
function appendElementTreeToError(error) {
|
|
51
|
+
const oldMessage = error.message;
|
|
52
|
+
error.message = formatErrorMessage(oldMessage, true);
|
|
53
|
+
|
|
54
|
+
// Required to make Jest print the element tree on error
|
|
55
|
+
error.stack = error.stack?.replace(oldMessage, error.message);
|
|
56
|
+
return error;
|
|
57
|
+
}
|
|
35
58
|
function makeQueries(queryAllByQuery, getMissingError, getMultipleError) {
|
|
36
|
-
function getAllByQuery(instance
|
|
59
|
+
function getAllByQuery(instance, {
|
|
60
|
+
printElementTree = true
|
|
61
|
+
} = {}) {
|
|
37
62
|
return function getAllFn(predicate, options) {
|
|
38
63
|
const results = queryAllByQuery(instance)(predicate, options);
|
|
39
64
|
if (results.length === 0) {
|
|
40
|
-
|
|
65
|
+
const errorMessage = formatErrorMessage(getMissingError(predicate, options), printElementTree);
|
|
66
|
+
throw new _errors.ErrorWithStack(errorMessage, getAllFn);
|
|
41
67
|
}
|
|
42
68
|
return results;
|
|
43
69
|
};
|
|
44
70
|
}
|
|
45
|
-
function queryByQuery(instance
|
|
71
|
+
function queryByQuery(instance, {
|
|
72
|
+
printElementTree = true
|
|
73
|
+
} = {}) {
|
|
46
74
|
return function singleQueryFn(predicate, options) {
|
|
47
75
|
const results = queryAllByQuery(instance)(predicate, options);
|
|
48
76
|
if (results.length > 1) {
|
|
49
|
-
throw new _errors.ErrorWithStack(getMultipleError(predicate, options), singleQueryFn);
|
|
77
|
+
throw new _errors.ErrorWithStack(formatErrorMessage(getMultipleError(predicate, options), printElementTree), singleQueryFn);
|
|
50
78
|
}
|
|
51
79
|
if (results.length === 0) {
|
|
52
80
|
return null;
|
|
@@ -54,33 +82,52 @@ function makeQueries(queryAllByQuery, getMissingError, getMultipleError) {
|
|
|
54
82
|
return results[0];
|
|
55
83
|
};
|
|
56
84
|
}
|
|
57
|
-
function getByQuery(instance
|
|
85
|
+
function getByQuery(instance, {
|
|
86
|
+
printElementTree = true
|
|
87
|
+
} = {}) {
|
|
58
88
|
return function getFn(predicate, options) {
|
|
59
89
|
const results = queryAllByQuery(instance)(predicate, options);
|
|
60
90
|
if (results.length > 1) {
|
|
61
91
|
throw new _errors.ErrorWithStack(getMultipleError(predicate, options), getFn);
|
|
62
92
|
}
|
|
63
93
|
if (results.length === 0) {
|
|
64
|
-
|
|
94
|
+
const errorMessage = formatErrorMessage(getMissingError(predicate, options), printElementTree);
|
|
95
|
+
throw new _errors.ErrorWithStack(errorMessage, getFn);
|
|
65
96
|
}
|
|
66
97
|
return results[0];
|
|
67
98
|
};
|
|
68
99
|
}
|
|
69
100
|
function findAllByQuery(instance) {
|
|
70
|
-
return function findAllFn(predicate, queryOptions,
|
|
101
|
+
return function findAllFn(predicate, queryOptions, {
|
|
102
|
+
onTimeout = error => appendElementTreeToError(error),
|
|
103
|
+
...waitForOptions
|
|
104
|
+
} = {}) {
|
|
105
|
+
const stackTraceError = new _errors.ErrorWithStack('STACK_TRACE_ERROR', findAllFn);
|
|
71
106
|
const deprecatedWaitForOptions = extractDeprecatedWaitForOptions(queryOptions);
|
|
72
|
-
return (0, _waitFor.default)(() => getAllByQuery(instance
|
|
107
|
+
return (0, _waitFor.default)(() => getAllByQuery(instance, {
|
|
108
|
+
printElementTree: false
|
|
109
|
+
})(predicate, queryOptions), {
|
|
73
110
|
...deprecatedWaitForOptions,
|
|
74
|
-
...waitForOptions
|
|
111
|
+
...waitForOptions,
|
|
112
|
+
stackTraceError,
|
|
113
|
+
onTimeout
|
|
75
114
|
});
|
|
76
115
|
};
|
|
77
116
|
}
|
|
78
117
|
function findByQuery(instance) {
|
|
79
|
-
return function findFn(predicate, queryOptions,
|
|
118
|
+
return function findFn(predicate, queryOptions, {
|
|
119
|
+
onTimeout = error => appendElementTreeToError(error),
|
|
120
|
+
...waitForOptions
|
|
121
|
+
} = {}) {
|
|
122
|
+
const stackTraceError = new _errors.ErrorWithStack('STACK_TRACE_ERROR', findFn);
|
|
80
123
|
const deprecatedWaitForOptions = extractDeprecatedWaitForOptions(queryOptions);
|
|
81
|
-
return (0, _waitFor.default)(() => getByQuery(instance
|
|
124
|
+
return (0, _waitFor.default)(() => getByQuery(instance, {
|
|
125
|
+
printElementTree: false
|
|
126
|
+
})(predicate, queryOptions), {
|
|
82
127
|
...deprecatedWaitForOptions,
|
|
83
|
-
...waitForOptions
|
|
128
|
+
...waitForOptions,
|
|
129
|
+
stackTraceError,
|
|
130
|
+
onTimeout
|
|
84
131
|
});
|
|
85
132
|
};
|
|
86
133
|
}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"makeQueries.js","names":["_errors","require","_waitFor","_interopRequireDefault","obj","__esModule","default","deprecatedKeys","extractDeprecatedWaitForOptions","options","undefined","waitForOptions","timeout","interval","stackTraceError","forEach","key","option","console","warn","toString","makeQueries","queryAllByQuery","getMissingError","getMultipleError","getAllByQuery","instance","getAllFn","predicate","results","length","ErrorWithStack","queryByQuery","singleQueryFn","getByQuery","getFn","findAllByQuery","findAllFn","queryOptions","deprecatedWaitForOptions","waitFor","findByQuery","findFn","getBy","getAllBy","queryBy","queryAllBy","findBy","findAllBy"],"sources":["../../src/queries/makeQueries.ts"],"sourcesContent":["import type { ReactTestInstance } from 'react-test-renderer';\nimport { ErrorWithStack } from '../helpers/errors';\nimport waitFor from '../waitFor';\nimport type { WaitForOptions } from '../waitFor';\n\nexport type GetByQuery<Predicate, Options = void> = (\n predicate: Predicate,\n options?: Options\n) => ReactTestInstance;\n\nexport type GetAllByQuery<Predicate, Options = void> = (\n predicate: Predicate,\n options?: Options\n) => ReactTestInstance[];\n\nexport type QueryByQuery<Predicate, Options = void> = (\n predicate: Predicate,\n options?: Options\n) => ReactTestInstance | null;\n\nexport type QueryAllByQuery<Predicate, Options = void> = (\n predicate: Predicate,\n options?: Options\n) => ReactTestInstance[];\n\nexport type FindByQuery<Predicate, Options = void> = (\n predicate: Predicate,\n // Remove `& WaitForOptions` when all queries have been migrated to support 2nd arg query options.\n options?: Options & WaitForOptions,\n waitForOptions?: WaitForOptions\n) => Promise<ReactTestInstance>;\n\nexport type FindAllByQuery<Predicate, Options = void> = (\n predicate: Predicate,\n // Remove `& WaitForOptions` when all queries have been migrated to support 2nd arg query options.\n options?: Options & WaitForOptions,\n waitForOptions?: WaitForOptions\n) => Promise<ReactTestInstance[]>;\n\ntype UnboundQuery<Query> = (instance: ReactTestInstance) => Query;\n\nexport type UnboundQueries<Predicate, Options> = {\n getBy: UnboundQuery<GetByQuery<Predicate, Options>>;\n getAllBy: UnboundQuery<GetAllByQuery<Predicate, Options>>;\n queryBy: UnboundQuery<QueryByQuery<Predicate, Options>>;\n queryAllBy: UnboundQuery<QueryAllByQuery<Predicate, Options>>;\n findBy: UnboundQuery<FindByQuery<Predicate, Options>>;\n findAllBy: UnboundQuery<FindAllByQuery<Predicate, Options>>;\n};\n\nconst deprecatedKeys: (keyof WaitForOptions)[] = [\n 'timeout',\n 'interval',\n 'stackTraceError',\n];\n\n// The WaitForOptions has been moved to the second option param of findBy* methods with the adding of TextMatchOptions\n// To make the migration easier and avoid a breaking change, keep reading this options from the first param but warn\nfunction extractDeprecatedWaitForOptions(options?: WaitForOptions) {\n if (!options) {\n return undefined;\n }\n\n const waitForOptions: WaitForOptions = {\n timeout: options.timeout,\n interval: options.interval,\n stackTraceError: options.stackTraceError,\n };\n\n deprecatedKeys.forEach((key) => {\n const option = options[key];\n if (option) {\n // eslint-disable-next-line no-console\n console.warn(\n `Use of option \"${key}\" in a findBy* query options (2nd parameter) is deprecated. Please pass this option in the waitForOptions (3rd parameter). \nExample: \n\n findByText(text, {}, { ${key}: ${option.toString()} })`\n );\n }\n });\n\n return waitForOptions;\n}\n\nexport function makeQueries<Predicate, Options>(\n queryAllByQuery: UnboundQuery<QueryAllByQuery<Predicate, Options>>,\n getMissingError: (predicate: Predicate, options?: Options) => string,\n getMultipleError: (predicate: Predicate, options?: Options) => string\n): UnboundQueries<Predicate, Options> {\n function getAllByQuery(instance: ReactTestInstance) {\n return function getAllFn(predicate: Predicate, options?: Options) {\n const results = queryAllByQuery(instance)(predicate, options);\n\n if (results.length === 0) {\n throw new ErrorWithStack(getMissingError(predicate, options), getAllFn);\n }\n\n return results;\n };\n }\n\n function queryByQuery(instance: ReactTestInstance) {\n return function singleQueryFn(predicate: Predicate, options?: Options) {\n const results = queryAllByQuery(instance)(predicate, options);\n\n if (results.length > 1) {\n throw new ErrorWithStack(\n getMultipleError(predicate, options),\n singleQueryFn\n );\n }\n\n if (results.length === 0) {\n return null;\n }\n\n return results[0];\n };\n }\n\n function getByQuery(instance: ReactTestInstance) {\n return function getFn(predicate: Predicate, options?: Options) {\n const results = queryAllByQuery(instance)(predicate, options);\n\n if (results.length > 1) {\n throw new ErrorWithStack(getMultipleError(predicate, options), getFn);\n }\n\n if (results.length === 0) {\n throw new ErrorWithStack(getMissingError(predicate, options), getFn);\n }\n\n return results[0];\n };\n }\n\n function findAllByQuery(instance: ReactTestInstance) {\n return function findAllFn(\n predicate: Predicate,\n queryOptions?: Options & WaitForOptions,\n waitForOptions: WaitForOptions = {}\n ) {\n const deprecatedWaitForOptions =\n extractDeprecatedWaitForOptions(queryOptions);\n return waitFor(() => getAllByQuery(instance)(predicate, queryOptions), {\n ...deprecatedWaitForOptions,\n ...waitForOptions,\n });\n };\n }\n\n function findByQuery(instance: ReactTestInstance) {\n return function findFn(\n predicate: Predicate,\n queryOptions?: Options & WaitForOptions,\n waitForOptions: WaitForOptions = {}\n ) {\n const deprecatedWaitForOptions =\n extractDeprecatedWaitForOptions(queryOptions);\n return waitFor(() => getByQuery(instance)(predicate, queryOptions), {\n ...deprecatedWaitForOptions,\n ...waitForOptions,\n });\n };\n }\n\n return {\n getBy: getByQuery,\n getAllBy: getAllByQuery,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,CAAC,CAAC,EACnC;MACA,MAAM4B,wBAAwB,GAC5B/B,+BAA+B,CAAC8B,YAAY,CAAC;MAC/C,OAAO,IAAAE,gBAAO,EAAC,MAAMf,aAAa,CAACC,QAAQ,CAAC,CAACE,SAAS,EAAEU,YAAY,CAAC,EAAE;QACrE,GAAGC,wBAAwB;QAC3B,GAAG5B;MACL,CAAC,CAAC;IACJ,CAAC;EACH;EAEA,SAAS8B,WAAWA,CAACf,QAA2B,EAAE;IAChD,OAAO,SAASgB,MAAMA,CACpBd,SAAoB,EACpBU,YAAuC,EACvC3B,cAA8B,GAAG,CAAC,CAAC,EACnC;MACA,MAAM4B,wBAAwB,GAC5B/B,+BAA+B,CAAC8B,YAAY,CAAC;MAC/C,OAAO,IAAAE,gBAAO,EAAC,MAAMN,UAAU,CAACR,QAAQ,CAAC,CAACE,SAAS,EAAEU,YAAY,CAAC,EAAE;QAClE,GAAGC,wBAAwB;QAC3B,GAAG5B;MACL,CAAC,CAAC;IACJ,CAAC;EACH;EAEA,OAAO;IACLgC,KAAK,EAAET,UAAU;IACjBU,QAAQ,EAAEnB,aAAa;IACvBoB,OAAO,EAAEb,YAAY;IACrBc,UAAU,EAAExB,eAAe;IAC3ByB,MAAM,EAAEN,WAAW;IACnBO,SAAS,EAAEZ;EACb,CAAC;AACH"}
|
|
1
|
+
{"version":3,"file":"makeQueries.js","names":["_errors","require","_waitFor","_interopRequireDefault","_format","_screen","_formatDefault","obj","__esModule","default","deprecatedKeys","extractDeprecatedWaitForOptions","options","undefined","waitForOptions","timeout","interval","stackTraceError","forEach","key","option","console","warn","toString","formatErrorMessage","message","printElementTree","json","screen","toJSON","format","mapProps","defaultMapProps","appendElementTreeToError","error","oldMessage","stack","replace","makeQueries","queryAllByQuery","getMissingError","getMultipleError","getAllByQuery","instance","getAllFn","predicate","results","length","errorMessage","ErrorWithStack","queryByQuery","singleQueryFn","getByQuery","getFn","findAllByQuery","findAllFn","queryOptions","onTimeout","deprecatedWaitForOptions","waitFor","findByQuery","findFn","getBy","getAllBy","queryBy","queryAllBy","findBy","findAllBy"],"sources":["../../src/queries/makeQueries.ts"],"sourcesContent":["import type { ReactTestInstance } from 'react-test-renderer';\nimport { ErrorWithStack } from '../helpers/errors';\nimport waitFor from '../waitFor';\nimport type { WaitForOptions } from '../waitFor';\nimport format from '../helpers/format';\nimport { screen } from '../screen';\nimport { defaultMapProps } from '../helpers/format-default';\n\nexport type GetByQuery<Predicate, Options = void> = (\n predicate: Predicate,\n options?: Options\n) => ReactTestInstance;\n\nexport type GetAllByQuery<Predicate, Options = void> = (\n predicate: Predicate,\n options?: Options\n) => ReactTestInstance[];\n\nexport type QueryByQuery<Predicate, Options = void> = (\n predicate: Predicate,\n options?: Options\n) => ReactTestInstance | null;\n\nexport type QueryAllByQuery<Predicate, Options = void> = (\n predicate: Predicate,\n options?: Options\n) => ReactTestInstance[];\n\nexport type FindByQuery<Predicate, Options = void> = (\n predicate: Predicate,\n // Remove `& WaitForOptions` when all queries have been migrated to support 2nd arg query options.\n options?: Options & WaitForOptions,\n waitForOptions?: WaitForOptions\n) => Promise<ReactTestInstance>;\n\nexport type FindAllByQuery<Predicate, Options = void> = (\n predicate: Predicate,\n // Remove `& WaitForOptions` when all queries have been migrated to support 2nd arg query options.\n options?: Options & WaitForOptions,\n waitForOptions?: WaitForOptions\n) => Promise<ReactTestInstance[]>;\n\ntype UnboundQuery<Query> = (instance: ReactTestInstance) => Query;\n\nexport type UnboundQueries<Predicate, Options> = {\n getBy: UnboundQuery<GetByQuery<Predicate, Options>>;\n getAllBy: UnboundQuery<GetAllByQuery<Predicate, Options>>;\n queryBy: UnboundQuery<QueryByQuery<Predicate, Options>>;\n queryAllBy: UnboundQuery<QueryAllByQuery<Predicate, Options>>;\n findBy: UnboundQuery<FindByQuery<Predicate, Options>>;\n findAllBy: UnboundQuery<FindAllByQuery<Predicate, Options>>;\n};\n\nconst deprecatedKeys: (keyof WaitForOptions)[] = [\n 'timeout',\n 'interval',\n 'stackTraceError',\n];\n\n// The WaitForOptions has been moved to the second option param of findBy* methods with the adding of TextMatchOptions\n// To make the migration easier and avoid a breaking change, keep reading this options from the first param but warn\nfunction extractDeprecatedWaitForOptions(options?: WaitForOptions) {\n if (!options) {\n return undefined;\n }\n\n const waitForOptions: WaitForOptions = {\n timeout: options.timeout,\n interval: options.interval,\n stackTraceError: options.stackTraceError,\n };\n\n deprecatedKeys.forEach((key) => {\n const option = options[key];\n if (option) {\n // eslint-disable-next-line no-console\n console.warn(\n `Use of option \"${key}\" in a findBy* query options (2nd parameter) is deprecated. Please pass this option in the waitForOptions (3rd parameter).\nExample:\n\n findByText(text, {}, { ${key}: ${option.toString()} })`\n );\n }\n });\n\n return waitForOptions;\n}\n\nfunction formatErrorMessage(message: string, printElementTree: boolean) {\n if (!printElementTree) {\n return message;\n }\n\n const json = screen.toJSON();\n if (!json) {\n return message;\n }\n\n return `${message}\\n\\n${format(json, {\n mapProps: defaultMapProps,\n })}`;\n}\n\nfunction appendElementTreeToError(error: Error) {\n const oldMessage = error.message;\n error.message = formatErrorMessage(oldMessage, true);\n\n // Required to make Jest print the element tree on error\n error.stack = error.stack?.replace(oldMessage, error.message);\n\n return error;\n}\n\nexport function makeQueries<Predicate, Options>(\n queryAllByQuery: UnboundQuery<QueryAllByQuery<Predicate, Options>>,\n getMissingError: (predicate: Predicate, options?: Options) => string,\n getMultipleError: (predicate: Predicate, options?: Options) => string\n): UnboundQueries<Predicate, Options> {\n function getAllByQuery(\n instance: ReactTestInstance,\n { printElementTree = true } = {}\n ) {\n return function getAllFn(predicate: Predicate, options?: Options) {\n const results = queryAllByQuery(instance)(predicate, options);\n\n if (results.length === 0) {\n const errorMessage = formatErrorMessage(\n getMissingError(predicate, options),\n printElementTree\n );\n throw new ErrorWithStack(errorMessage, getAllFn);\n }\n\n return results;\n };\n }\n\n function queryByQuery(\n instance: ReactTestInstance,\n { printElementTree = true } = {}\n ) {\n return function singleQueryFn(predicate: Predicate, options?: Options) {\n const results = queryAllByQuery(instance)(predicate, options);\n\n if (results.length > 1) {\n throw new ErrorWithStack(\n formatErrorMessage(\n getMultipleError(predicate, options),\n printElementTree\n ),\n singleQueryFn\n );\n }\n\n if (results.length === 0) {\n return null;\n }\n\n return results[0];\n };\n }\n\n function getByQuery(\n instance: ReactTestInstance,\n { printElementTree = true } = {}\n ) {\n return function getFn(predicate: Predicate, options?: Options) {\n const results = queryAllByQuery(instance)(predicate, options);\n\n if (results.length > 1) {\n throw new ErrorWithStack(getMultipleError(predicate, options), getFn);\n }\n\n if (results.length === 0) {\n const errorMessage = formatErrorMessage(\n getMissingError(predicate, options),\n printElementTree\n );\n throw new ErrorWithStack(errorMessage, getFn);\n }\n\n return results[0];\n };\n }\n\n function findAllByQuery(instance: ReactTestInstance) {\n return function findAllFn(\n predicate: Predicate,\n queryOptions?: Options & WaitForOptions,\n {\n onTimeout = (error) => appendElementTreeToError(error),\n ...waitForOptions\n }: WaitForOptions = {}\n ) {\n const stackTraceError = new ErrorWithStack(\n 'STACK_TRACE_ERROR',\n findAllFn\n );\n const deprecatedWaitForOptions =\n extractDeprecatedWaitForOptions(queryOptions);\n\n return waitFor(\n () =>\n getAllByQuery(instance, { printElementTree: false })(\n predicate,\n queryOptions\n ),\n {\n ...deprecatedWaitForOptions,\n ...waitForOptions,\n stackTraceError,\n onTimeout,\n }\n );\n };\n }\n\n function findByQuery(instance: ReactTestInstance) {\n return function findFn(\n predicate: Predicate,\n queryOptions?: Options & WaitForOptions,\n {\n onTimeout = (error) => appendElementTreeToError(error),\n ...waitForOptions\n }: WaitForOptions = {}\n ) {\n const stackTraceError = new ErrorWithStack('STACK_TRACE_ERROR', findFn);\n const deprecatedWaitForOptions =\n extractDeprecatedWaitForOptions(queryOptions);\n\n return waitFor(\n () =>\n getByQuery(instance, { printElementTree: false })(\n predicate,\n queryOptions\n ),\n {\n ...deprecatedWaitForOptions,\n ...waitForOptions,\n stackTraceError,\n onTimeout,\n }\n );\n };\n }\n\n return {\n getBy: getByQuery,\n getAllB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
|
5
|
+
});
|
|
6
|
+
exports.renderWithAct = renderWithAct;
|
|
7
|
+
var _reactTestRenderer = _interopRequireDefault(require("react-test-renderer"));
|
|
8
|
+
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
|
|
9
|
+
function renderWithAct(component, options) {
|
|
10
|
+
let renderer;
|
|
11
|
+
_reactTestRenderer.default.act(() => {
|
|
12
|
+
renderer = _reactTestRenderer.default.create(component, options);
|
|
13
|
+
});
|
|
14
|
+
|
|
15
|
+
// @ts-ignore act is synchronous, so renderer is already initialised here
|
|
16
|
+
return renderer;
|
|
17
|
+
}
|
|
18
|
+
//# sourceMappingURL=render-act.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"render-act.js","names":["_reactTestRenderer","_interopRequireDefault","require","obj","__esModule","default","renderWithAct","component","options","renderer","TestRenderer","act","create"],"sources":["../src/render-act.ts"],"sourcesContent":["import TestRenderer from 'react-test-renderer';\nimport type {\n ReactTestRenderer,\n TestRendererOptions,\n} from 'react-test-renderer';\n\nexport function renderWithAct(\n component: React.ReactElement,\n options?: TestRendererOptions\n): ReactTestRenderer {\n let renderer: ReactTestRenderer;\n\n TestRenderer.act(() => {\n renderer = TestRenderer.create(component, options);\n });\n\n // @ts-ignore act is synchronous, so renderer is already initialised here\n return renderer;\n}\n"],"mappings":";;;;;;AAAA,IAAAA,kBAAA,GAAAC,sBAAA,CAAAC,OAAA;AAA+C,SAAAD,uBAAAE,GAAA,WAAAA,GAAA,IAAAA,GAAA,CAAAC,UAAA,GAAAD,GAAA,KAAAE,OAAA,EAAAF,GAAA;AAMxC,SAASG,aAAaA,CAC3BC,SAA6B,EAC7BC,OAA6B,EACV;EACnB,IAAIC,QAA2B;EAE/BC,0BAAY,CAACC,GAAG,CAAC,MAAM;IACrBF,QAAQ,GAAGC,0BAAY,CAACE,MAAM,CAACL,SAAS,EAAEC,OAAO,CAAC;EACpD,CAAC,CAAC;;EAEF;EACA,OAAOC,QAAQ;AACjB"}
|
package/build/render.d.ts
CHANGED
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import
|
|
1
|
+
import type { ReactTestInstance } from 'react-test-renderer';
|
|
2
2
|
import * as React from 'react';
|
|
3
3
|
import { DebugOptions } from './helpers/debugDeep';
|
|
4
4
|
export type RenderOptions = {
|
|
@@ -15,26 +15,26 @@ export default function render<T>(component: React.ReactElement<T>, { wrapper: W
|
|
|
15
15
|
update: (component: React.ReactElement<any, string | React.JSXElementConstructor<any>>) => void;
|
|
16
16
|
unmount: () => void;
|
|
17
17
|
rerender: (component: React.ReactElement<any, string | React.JSXElementConstructor<any>>) => void;
|
|
18
|
-
toJSON: () =>
|
|
18
|
+
toJSON: () => import("react-test-renderer").ReactTestRendererJSON | import("react-test-renderer").ReactTestRendererJSON[] | null;
|
|
19
19
|
debug: DebugFunction;
|
|
20
|
-
root:
|
|
21
|
-
UNSAFE_root:
|
|
20
|
+
root: ReactTestInstance;
|
|
21
|
+
UNSAFE_root: ReactTestInstance;
|
|
22
22
|
UNSAFE_getByProps: (props: {
|
|
23
23
|
[key: string]: any;
|
|
24
|
-
}) =>
|
|
24
|
+
}) => ReactTestInstance;
|
|
25
25
|
UNSAFE_getAllByProps: (props: {
|
|
26
26
|
[key: string]: any;
|
|
27
|
-
}) =>
|
|
27
|
+
}) => ReactTestInstance[];
|
|
28
28
|
UNSAFE_queryByProps: (props: {
|
|
29
29
|
[key: string]: any;
|
|
30
|
-
}) =>
|
|
30
|
+
}) => ReactTestInstance | null;
|
|
31
31
|
UNSAFE_queryAllByProps: (props: {
|
|
32
32
|
[key: string]: any;
|
|
33
|
-
}) =>
|
|
34
|
-
UNSAFE_getByType: <P>(type: React.ComponentType<P>) =>
|
|
35
|
-
UNSAFE_getAllByType: <P_1>(type: React.ComponentType<P_1>) =>
|
|
36
|
-
UNSAFE_queryByType: <P_2>(type: React.ComponentType<P_2>) =>
|
|
37
|
-
UNSAFE_queryAllByType: <P_3>(type: React.ComponentType<P_3>) =>
|
|
33
|
+
}) => ReactTestInstance[];
|
|
34
|
+
UNSAFE_getByType: <P>(type: React.ComponentType<P>) => ReactTestInstance;
|
|
35
|
+
UNSAFE_getAllByType: <P_1>(type: React.ComponentType<P_1>) => ReactTestInstance[];
|
|
36
|
+
UNSAFE_queryByType: <P_2>(type: React.ComponentType<P_2>) => ReactTestInstance | null;
|
|
37
|
+
UNSAFE_queryAllByType: <P_3>(type: React.ComponentType<P_3>) => ReactTestInstance[];
|
|
38
38
|
getByA11yValue: import("./queries/makeQueries").GetByQuery<import("./helpers/matchers/accessibilityValue").AccessibilityValueMatcher, import("./queries/options").CommonQueryOptions>;
|
|
39
39
|
getAllByA11yValue: import("./queries/makeQueries").GetAllByQuery<import("./helpers/matchers/accessibilityValue").AccessibilityValueMatcher, import("./queries/options").CommonQueryOptions>;
|
|
40
40
|
queryByA11yValue: import("./queries/makeQueries").QueryByQuery<import("./helpers/matchers/accessibilityValue").AccessibilityValueMatcher, import("./queries/options").CommonQueryOptions>;
|
package/build/render.js
CHANGED
|
@@ -4,21 +4,21 @@ Object.defineProperty(exports, "__esModule", {
|
|
|
4
4
|
value: true
|
|
5
5
|
});
|
|
6
6
|
exports.default = render;
|
|
7
|
-
var _reactTestRenderer = _interopRequireDefault(require("react-test-renderer"));
|
|
8
7
|
var React = _interopRequireWildcard(require("react"));
|
|
9
8
|
var _act = _interopRequireDefault(require("./act"));
|
|
10
9
|
var _cleanup = require("./cleanup");
|
|
11
|
-
var _debugShallow = _interopRequireDefault(require("./helpers/debugShallow"));
|
|
12
|
-
var _debugDeep = _interopRequireDefault(require("./helpers/debugDeep"));
|
|
13
|
-
var _within = require("./within");
|
|
14
|
-
var _screen = require("./screen");
|
|
15
|
-
var _stringValidation = require("./helpers/stringValidation");
|
|
16
10
|
var _config = require("./config");
|
|
17
11
|
var _componentTree = require("./helpers/component-tree");
|
|
12
|
+
var _debugDeep = _interopRequireDefault(require("./helpers/debugDeep"));
|
|
13
|
+
var _debugShallow = _interopRequireDefault(require("./helpers/debugShallow"));
|
|
18
14
|
var _hostComponentNames = require("./helpers/host-component-names");
|
|
15
|
+
var _stringValidation = require("./helpers/stringValidation");
|
|
16
|
+
var _renderAct = require("./render-act");
|
|
17
|
+
var _screen = require("./screen");
|
|
18
|
+
var _within = require("./within");
|
|
19
|
+
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
|
|
19
20
|
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); }
|
|
20
21
|
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; }
|
|
21
|
-
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
|
|
22
22
|
/**
|
|
23
23
|
* Renders test component deeply using react-test-renderer and exposes helpers
|
|
24
24
|
* to assert on the output.
|
|
@@ -36,7 +36,7 @@ function render(component, {
|
|
|
36
36
|
});
|
|
37
37
|
}
|
|
38
38
|
const wrap = element => Wrapper ? /*#__PURE__*/React.createElement(Wrapper, null, element) : element;
|
|
39
|
-
const renderer = renderWithAct(wrap(component), createNodeMock ? {
|
|
39
|
+
const renderer = (0, _renderAct.renderWithAct)(wrap(component), createNodeMock ? {
|
|
40
40
|
createNodeMock
|
|
41
41
|
} : undefined);
|
|
42
42
|
return buildRenderResult(renderer, wrap);
|
|
@@ -54,7 +54,7 @@ function renderWithStringValidation(component, {
|
|
|
54
54
|
id: "renderProfiler",
|
|
55
55
|
onRender: handleRender
|
|
56
56
|
}, Wrapper ? /*#__PURE__*/React.createElement(Wrapper, null, element) : element);
|
|
57
|
-
const renderer = renderWithAct(wrap(component), createNodeMock ? {
|
|
57
|
+
const renderer = (0, _renderAct.renderWithAct)(wrap(component), createNodeMock ? {
|
|
58
58
|
createNodeMock
|
|
59
59
|
} : undefined);
|
|
60
60
|
(0, _stringValidation.validateStringsRenderedWithinText)(renderer.toJSON());
|
|
@@ -94,15 +94,6 @@ function buildRenderResult(renderer, wrap) {
|
|
|
94
94
|
(0, _screen.setRenderResult)(result);
|
|
95
95
|
return result;
|
|
96
96
|
}
|
|
97
|
-
function renderWithAct(component, options) {
|
|
98
|
-
let renderer;
|
|
99
|
-
(0, _act.default)(() => {
|
|
100
|
-
renderer = _reactTestRenderer.default.create(component, options);
|
|
101
|
-
});
|
|
102
|
-
|
|
103
|
-
// @ts-ignore act is sync, so renderer is always initialised here
|
|
104
|
-
return renderer;
|
|
105
|
-
}
|
|
106
97
|
function updateWithAct(renderer, wrap) {
|
|
107
98
|
return function (component) {
|
|
108
99
|
(0, _act.default)(() => {
|
package/build/render.js.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"render.js","names":["_reactTestRenderer","_interopRequireDefault","require","React","_interopRequireWildcard","_act","_cleanup","_debugShallow","_debugDeep","_within","_screen","_stringValidation","_config","_componentTree","_hostComponentNames","_getRequireWildcardCache","nodeInterop","WeakMap","cacheBabelInterop","cacheNodeInterop","obj","__esModule","default","cache","has","get","newObj","hasPropertyDescriptor","Object","defineProperty","getOwnPropertyDescriptor","key","prototype","hasOwnProperty","call","desc","set","render","component","wrapper","Wrapper","createNodeMock","unstable_validateStringsRenderedWithinText","configureHostComponentNamesIfNeeded","renderWithStringValidation","wrap","element","createElement","renderer","renderWithAct","undefined","buildRenderResult","handleRender","_","phase","validateStringsRenderedWithinText","screen","toJSON","Profiler","id","onRender","update","updateWithAct","instance","root","unmount","act","addToCleanupQueue","result","getQueriesForElement","rerender","debug","getHostChildren","UNSAFE_root","enumerable","Error","setRenderResult","options","TestRenderer","create","debugImpl","defaultDebugOptions","getConfig","debugOptions","message","console","warn","json","debugDeep","shallow","debugShallow"],"sources":["../src/render.tsx"],"sourcesContent":["import TestRenderer from 'react-test-renderer';\nimport type { ReactTestInstance, ReactTestRenderer } from 'react-test-renderer';\nimport * as React from 'react';\nimport { Profiler } from 'react';\nimport act from './act';\nimport { addToCleanupQueue } from './cleanup';\nimport debugShallow from './helpers/debugShallow';\nimport debugDeep, { DebugOptions } from './helpers/debugDeep';\nimport { getQueriesForElement } from './within';\nimport { setRenderResult, screen } from './screen';\nimport { validateStringsRenderedWithinText } from './helpers/stringValidation';\nimport { getConfig } from './config';\nimport { getHostChildren } from './helpers/component-tree';\nimport { configureHostComponentNamesIfNeeded } from './helpers/host-component-names';\n\nexport type RenderOptions = {\n wrapper?: React.ComponentType<any>;\n createNodeMock?: (element: React.ReactElement) => any;\n unstable_validateStringsRenderedWithinText?: boolean;\n};\n\ntype TestRendererOptions = {\n createNodeMock: (element: React.ReactElement) => any;\n};\n\nexport type RenderResult = ReturnType<typeof render>;\n\n/**\n * Renders test component deeply using react-test-renderer and exposes helpers\n * to assert on the output.\n */\nexport default function render<T>(\n component: React.ReactElement<T>,\n {\n wrapper: Wrapper,\n createNodeMock,\n unstable_validateStringsRenderedWithinText,\n }: RenderOptions = {}\n) {\n configureHostComponentNamesIfNeeded();\n\n if (unstable_validateStringsRenderedWithinText) {\n return renderWithStringValidation(component, {\n wrapper: Wrapper,\n createNodeMock,\n });\n }\n\n const wrap = (element: React.ReactElement) =>\n Wrapper ? <Wrapper>{element}</Wrapper> : element;\n\n const renderer = renderWithAct(\n wrap(component),\n createNodeMock ? { createNodeMock } : undefined\n );\n\n return buildRenderResult(renderer, wrap);\n}\n\nfunction renderWithStringValidation<T>(\n component: React.ReactElement<T>,\n {\n wrapper: Wrapper,\n createNodeMock,\n }: Omit<RenderOptions, 'unstable_validateStringsRenderedWithinText'> = {}\n) {\n const handleRender: React.ProfilerProps['onRender'] = (_, phase) => {\n if (phase === 'update') {\n validateStringsRenderedWithinText(screen.toJSON());\n }\n };\n\n const wrap = (element: React.ReactElement) => (\n <Profiler id=\"renderProfiler\" onRender={handleRender}>\n {Wrapper ? <Wrapper>{element}</Wrapper> : element}\n </Profiler>\n );\n\n const renderer = renderWithAct(\n wrap(component),\n createNodeMock ? { createNodeMock } : undefined\n );\n validateStringsRenderedWithinText(renderer.toJSON());\n\n return buildRenderResult(renderer, wrap);\n}\n\nfunction buildRenderResult(\n renderer: ReactTestRenderer,\n wrap: (element: React.ReactElement) => JSX.Element\n) {\n const update = updateWithAct(renderer, wrap);\n const instance = renderer.root;\n\n const unmount = () => {\n act(() => {\n renderer.unmount();\n });\n };\n\n addToCleanupQueue(unmount);\n\n const result = {\n ...getQueriesForElement(instance),\n update,\n unmount,\n rerender: update, // alias for `update`\n toJSON: renderer.toJSON,\n debug: debug(instance, renderer),\n get root() {\n return getHostChildren(instance)[0];\n },\n UNSAFE_root: instance,\n };\n\n // Add as non-enumerable property, so that it's safe to enumerate\n // `render` result, e.g. using destructuring rest syntax.\n Object.defineProperty(result, 'container', {\n enumerable: false,\n get() {\n throw new Error(\n \"'container' property has been renamed to 'UNSAFE_root'.\\n\\n\" +\n \"Consider using 'root' property which returns root host element.\"\n );\n },\n });\n\n setRenderResult(result);\n return result;\n}\n\nfunction renderWithAct(\n component: React.ReactElement,\n options?: TestRendererOptions\n): ReactTestRenderer {\n let renderer: ReactTestRenderer;\n\n act(() => {\n renderer = TestRenderer.create(component, options);\n });\n\n // @ts-ignore act is sync, so renderer is always initialised here\n return renderer;\n}\n\nfunction updateWithAct(\n renderer: ReactTestRenderer,\n wrap: (innerElement: React.ReactElement) => React.ReactElement\n) {\n return function (component: React.ReactElement) {\n act(() => {\n renderer.update(wrap(component));\n });\n };\n}\n\ninterface DebugFunction {\n (options?: DebugOptions | string): void;\n shallow: (message?: string) => void;\n}\n\nfunction debug(\n instance: ReactTestInstance,\n renderer: ReactTestRenderer\n): DebugFunction {\n function debugImpl(options?: DebugOptions | string) {\n const { defaultDebugOptions } = getConfig();\n const debugOptions =\n typeof options === 'string'\n ? { ...defaultDebugOptions, message: options }\n : { ...defaultDebugOptions, ...options };\n\n if (typeof options === 'string') {\n // eslint-disable-next-line no-console\n console.warn(\n 'Using debug(\"message\") is deprecated and will be removed in future release, please use debug({ message; \"message\" }) instead.'\n );\n }\n\n const json = renderer.toJSON();\n if (json) {\n return debugDeep(json, debugOptions);\n }\n }\n debugImpl.shallow = (message?: string) => debugShallow(instance, message);\n return debugImpl;\n}\n"],"mappings":";;;;;;AAAA,IAAAA,kBAAA,GAAAC,sBAAA,CAAAC,OAAA;AAEA,IAAAC,KAAA,GAAAC,uBAAA,CAAAF,OAAA;AAEA,IAAAG,IAAA,GAAAJ,sBAAA,CAAAC,OAAA;AACA,IAAAI,QAAA,GAAAJ,OAAA;AACA,IAAAK,aAAA,GAAAN,sBAAA,CAAAC,OAAA;AACA,IAAAM,UAAA,GAAAP,sBAAA,CAAAC,OAAA;AACA,IAAAO,OAAA,GAAAP,OAAA;AACA,IAAAQ,OAAA,GAAAR,OAAA;AACA,IAAAS,iBAAA,GAAAT,OAAA;AACA,IAAAU,OAAA,GAAAV,OAAA;AACA,IAAAW,cAAA,GAAAX,OAAA;AACA,IAAAY,mBAAA,GAAAZ,OAAA;AAAqF,SAAAa,yBAAAC,WAAA,eAAAC,OAAA,kCAAAC,iBAAA,OAAAD,OAAA,QAAAE,gBAAA,OAAAF,OAAA,YAAAF,wBAAA,YAAAA,CAAAC,WAAA,WAAAA,WAAA,GAAAG,gBAAA,GAAAD,iBAAA,KAAAF,WAAA;AAAA,SAAAZ,wBAA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AM;MACRlB,QAAQ,CAACa,MAAM,CAAChB,IAAI,CAACP,SAAS,CAAC,CAAC;IAClC,CAAC,CAAC;EACJ,CAAC;AACH;AAOA,SAASiC,KAAKA,CACZR,QAA2B,EAC3Bf,QAA2B,EACZ;EACf,SAASgC,SAASA,CAACH,OAA+B,EAAE;IAClD,MAAM;MAAEI;IAAoB,CAAC,GAAG,IAAAC,iBAAS,GAAE;IAC3C,MAAMC,YAAY,GAChB,OAAON,OAAO,KAAK,QAAQ,GACvB;MAAE,GAAGI,mBAAmB;MAAEG,OAAO,EAAEP;IAAQ,CAAC,GAC5C;MAAE,GAAGI,mBAAmB;MAAE,GAAGJ;IAAQ,CAAC;IAE5C,IAAI,OAAOA,OAAO,KAAK,QAAQ,EAAE;MAC/B;MACAQ,OAAO,CAACC,IAAI,CACV,+HAA+H,CAChI;IACH;IAEA,MAAMC,IAAI,GAAGvC,QAAQ,CAACS,MAAM,EAAE;IAC9B,IAAI8B,IAAI,EAAE;MACR,OAAO,IAAAC,kBAAS,EAACD,IAAI,EAAEJ,YAAY,CAAC;IACtC;EACF;EACAH,SAAS,CAACS,OAAO,GAAIL,OAAgB,IAAK,IAAAM,qBAAY,EAAC3B,QAAQ,EAAEqB,OAAO,CAAC;EACzE,OAAOJ,SAAS;AAClB"}
|
|
1
|
+
{"version":3,"file":"render.js","names":["React","_interopRequireWildcard","require","_act","_interopRequireDefault","_cleanup","_config","_componentTree","_debugDeep","_debugShallow","_hostComponentNames","_stringValidation","_renderAct","_screen","_within","obj","__esModule","default","_getRequireWildcardCache","nodeInterop","WeakMap","cacheBabelInterop","cacheNodeInterop","cache","has","get","newObj","hasPropertyDescriptor","Object","defineProperty","getOwnPropertyDescriptor","key","prototype","hasOwnProperty","call","desc","set","render","component","wrapper","Wrapper","createNodeMock","unstable_validateStringsRenderedWithinText","configureHostComponentNamesIfNeeded","renderWithStringValidation","wrap","element","createElement","renderer","renderWithAct","undefined","buildRenderResult","handleRender","_","phase","validateStringsRenderedWithinText","screen","toJSON","Profiler","id","onRender","update","updateWithAct","instance","root","unmount","act","addToCleanupQueue","result","getQueriesForElement","rerender","debug","getHostChildren","UNSAFE_root","enumerable","Error","setRenderResult","debugImpl","options","defaultDebugOptions","getConfig","debugOptions","message","console","warn","json","debugDeep","shallow","debugShallow"],"sources":["../src/render.tsx"],"sourcesContent":["import type { ReactTestInstance, ReactTestRenderer } from 'react-test-renderer';\nimport * as React from 'react';\nimport { Profiler } from 'react';\nimport act from './act';\nimport { addToCleanupQueue } from './cleanup';\nimport { getConfig } from './config';\nimport { getHostChildren } from './helpers/component-tree';\nimport debugDeep, { DebugOptions } from './helpers/debugDeep';\nimport debugShallow from './helpers/debugShallow';\nimport { configureHostComponentNamesIfNeeded } from './helpers/host-component-names';\nimport { validateStringsRenderedWithinText } from './helpers/stringValidation';\nimport { renderWithAct } from './render-act';\nimport { setRenderResult, screen } from './screen';\nimport { getQueriesForElement } from './within';\n\nexport type RenderOptions = {\n wrapper?: React.ComponentType<any>;\n createNodeMock?: (element: React.ReactElement) => any;\n unstable_validateStringsRenderedWithinText?: boolean;\n};\n\nexport type RenderResult = ReturnType<typeof render>;\n\n/**\n * Renders test component deeply using react-test-renderer and exposes helpers\n * to assert on the output.\n */\nexport default function render<T>(\n component: React.ReactElement<T>,\n {\n wrapper: Wrapper,\n createNodeMock,\n unstable_validateStringsRenderedWithinText,\n }: RenderOptions = {}\n) {\n configureHostComponentNamesIfNeeded();\n\n if (unstable_validateStringsRenderedWithinText) {\n return renderWithStringValidation(component, {\n wrapper: Wrapper,\n createNodeMock,\n });\n }\n\n const wrap = (element: React.ReactElement) =>\n Wrapper ? <Wrapper>{element}</Wrapper> : element;\n\n const renderer = renderWithAct(\n wrap(component),\n createNodeMock ? { createNodeMock } : undefined\n );\n\n return buildRenderResult(renderer, wrap);\n}\n\nfunction renderWithStringValidation<T>(\n component: React.ReactElement<T>,\n {\n wrapper: Wrapper,\n createNodeMock,\n }: Omit<RenderOptions, 'unstable_validateStringsRenderedWithinText'> = {}\n) {\n const handleRender: React.ProfilerProps['onRender'] = (_, phase) => {\n if (phase === 'update') {\n validateStringsRenderedWithinText(screen.toJSON());\n }\n };\n\n const wrap = (element: React.ReactElement) => (\n <Profiler id=\"renderProfiler\" onRender={handleRender}>\n {Wrapper ? <Wrapper>{element}</Wrapper> : element}\n </Profiler>\n );\n\n const renderer = renderWithAct(\n wrap(component),\n createNodeMock ? { createNodeMock } : undefined\n );\n validateStringsRenderedWithinText(renderer.toJSON());\n\n return buildRenderResult(renderer, wrap);\n}\n\nfunction buildRenderResult(\n renderer: ReactTestRenderer,\n wrap: (element: React.ReactElement) => JSX.Element\n) {\n const update = updateWithAct(renderer, wrap);\n const instance = renderer.root;\n\n const unmount = () => {\n act(() => {\n renderer.unmount();\n });\n };\n\n addToCleanupQueue(unmount);\n\n const result = {\n ...getQueriesForElement(instance),\n update,\n unmount,\n rerender: update, // alias for `update`\n toJSON: renderer.toJSON,\n debug: debug(instance, renderer),\n get root() {\n return getHostChildren(instance)[0];\n },\n UNSAFE_root: instance,\n };\n\n // Add as non-enumerable property, so that it's safe to enumerate\n // `render` result, e.g. using destructuring rest syntax.\n Object.defineProperty(result, 'container', {\n enumerable: false,\n get() {\n throw new Error(\n \"'container' property has been renamed to 'UNSAFE_root'.\\n\\n\" +\n \"Consider using 'root' property which returns root host element.\"\n );\n },\n });\n\n setRenderResult(result);\n return result;\n}\n\nfunction updateWithAct(\n renderer: ReactTestRenderer,\n wrap: (innerElement: React.ReactElement) => React.ReactElement\n) {\n return function (component: React.ReactElement) {\n act(() => {\n renderer.update(wrap(component));\n });\n };\n}\n\ninterface DebugFunction {\n (options?: DebugOptions | string): void;\n shallow: (message?: string) => void;\n}\n\nfunction debug(\n instance: ReactTestInstance,\n renderer: ReactTestRenderer\n): DebugFunction {\n function debugImpl(options?: DebugOptions | string) {\n const { defaultDebugOptions } = getConfig();\n const debugOptions =\n typeof options === 'string'\n ? { ...defaultDebugOptions, message: options }\n : { ...defaultDebugOptions, ...options };\n\n if (typeof options === 'string') {\n // eslint-disable-next-line no-console\n console.warn(\n 'Using debug(\"message\") is deprecated and will be removed in future release, please use debug({ message; \"message\" }) instead.'\n );\n }\n\n const json = renderer.toJSON();\n if (json) {\n return debugDeep(json, debugOptions);\n }\n }\n debugImpl.shallow = (message?: string) => debugShallow(instance, message);\n return debugImpl;\n}\n"],"mappings":";;;;;;AACA,IAAAA,KAAA,GAAAC,uBAAA,CAAAC,OAAA;AAEA,IAAAC,IAAA,GAAAC,sBAAA,CAAAF,OAAA;AACA,IAAAG,QAAA,GAAAH,OAAA;AACA,IAAAI,OAAA,GAAAJ,OAAA;AACA,IAAAK,cAAA,GAAAL,OAAA;AACA,IAAAM,UAAA,GAAAJ,sBAAA,CAAAF,OAAA;AACA,IAAAO,aAAA,GAAAL,sBAAA,CAAAF,OAAA;AACA,IAAAQ,mBAAA,GAAAR,OAAA;AACA,IAAAS,iBAAA,GAAAT,OAAA;AACA,IAAAU,UAAA,GAAAV,OAAA;AACA,IAAAW,OAAA,GAAAX,OAAA;AACA,IAAAY,OAAA,GAAAZ,OAAA;AAAgD,SAAAE,uBAAAW,GAAA,WAAAA,GAAA,IAAAA,GAAA,CAAAC,UAAA,GAAAD,GAAA,KAAAE,OAAA,EAAAF,GAAA;AAAA,SAAAG,yBAAAC,WAAA,eAAAC,OAAA,kCAAAC,iBAAA,OAAAD,OAAA,QAAAE,gBAAA,OAAAF,OAAA,YAAAF,wBAAA,YAAAA,CAAAC,WAAA,WAAAA,WAAA,GAAAG,gBAAA,GAAAD,iBAAA,KAAAF,WAAA;AAAA,SAAAlB,wBAAAc,GAAA,EAAAI,WAAA,SAAAA,WAAA,IAAAJ,GAAA,IAAAA,GAAA,CAAAC,UAAA,WAAAD,GAAA,QAAAA,GAAA,oBAAAA,GAAA,wBAAAA,GAAA,4BAAAE,OAAA,EAAAF,GAAA,UAAAQ,KAAA,GAAAL,wBAAA,CAAAC,WAAA,OAAAI,KAAA,IAAAA,KAAA,CAAAC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CAACS,MAAM,EAAE;IAC9B,IAAI4B,IAAI,EAAE;MACR,OAAO,IAAAC,kBAAS,EAACD,IAAI,EAAEJ,YAAY,CAAC;IACtC;EACF;EACAJ,SAAS,CAACU,OAAO,GAAIL,OAAgB,IAAK,IAAAM,qBAAY,EAACzB,QAAQ,EAAEmB,OAAO,CAAC;EACzE,OAAOL,SAAS;AAClB"}
|
package/build/waitFor.d.ts
CHANGED
|
@@ -3,6 +3,6 @@ export type WaitForOptions = {
|
|
|
3
3
|
timeout?: number;
|
|
4
4
|
interval?: number;
|
|
5
5
|
stackTraceError?: ErrorWithStack;
|
|
6
|
-
onTimeout?: (error:
|
|
6
|
+
onTimeout?: (error: Error) => Error;
|
|
7
7
|
};
|
|
8
8
|
export default function waitFor<T>(expectation: () => T, options?: WaitForOptions): Promise<T>;
|
package/build/waitFor.js
CHANGED
|
@@ -6,6 +6,7 @@ Object.defineProperty(exports, "__esModule", {
|
|
|
6
6
|
exports.default = waitFor;
|
|
7
7
|
var _act = _interopRequireWildcard(require("./act"));
|
|
8
8
|
var _config = require("./config");
|
|
9
|
+
var _flushMicroTasks = require("./flushMicroTasks");
|
|
9
10
|
var _errors = require("./helpers/errors");
|
|
10
11
|
var _timers = require("./helpers/timers");
|
|
11
12
|
var _reactVersions = require("./react-versions");
|
|
@@ -145,7 +146,11 @@ function waitForInternal(expectation, {
|
|
|
145
146
|
function handleTimeout() {
|
|
146
147
|
let error;
|
|
147
148
|
if (lastError) {
|
|
148
|
-
|
|
149
|
+
if (lastError instanceof Error) {
|
|
150
|
+
error = lastError;
|
|
151
|
+
} else {
|
|
152
|
+
error = new Error(String(lastError));
|
|
153
|
+
}
|
|
149
154
|
if (stackTraceError) {
|
|
150
155
|
(0, _errors.copyStackTrace)(error, stackTraceError);
|
|
151
156
|
}
|
|
@@ -156,7 +161,10 @@ function waitForInternal(expectation, {
|
|
|
156
161
|
}
|
|
157
162
|
}
|
|
158
163
|
if (typeof onTimeout === 'function') {
|
|
159
|
-
onTimeout(error);
|
|
164
|
+
const result = onTimeout(error);
|
|
165
|
+
if (result) {
|
|
166
|
+
error = result;
|
|
167
|
+
}
|
|
160
168
|
}
|
|
161
169
|
onDone({
|
|
162
170
|
type: 'error',
|
|
@@ -176,7 +184,10 @@ async function waitFor(expectation, options) {
|
|
|
176
184
|
const previousActEnvironment = (0, _act.getIsReactActEnvironment)();
|
|
177
185
|
(0, _act.setReactActEnvironment)(false);
|
|
178
186
|
try {
|
|
179
|
-
|
|
187
|
+
const result = await waitForInternal(expectation, optionsWithStackTrace);
|
|
188
|
+
// Flush the microtask queue before restoring the `act` environment
|
|
189
|
+
await (0, _flushMicroTasks.flushMicroTasks)();
|
|
190
|
+
return result;
|
|
180
191
|
} finally {
|
|
181
192
|
(0, _act.setReactActEnvironment)(previousActEnvironment);
|
|
182
193
|
}
|
package/build/waitFor.js.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"waitFor.js","names":["_act","_interopRequireWildcard","require","_config","_errors","_timers","_reactVersions","_getRequireWildcardCache","nodeInterop","WeakMap","cacheBabelInterop","cacheNodeInterop","obj","__esModule","default","cache","has","get","newObj","hasPropertyDescriptor","Object","defineProperty","getOwnPropertyDescriptor","key","prototype","hasOwnProperty","call","desc","set","DEFAULT_INTERVAL","waitForInternal","expectation","timeout","getConfig","asyncUtilTimeout","interval","stackTraceError","onTimeout","TypeError","Promise","resolve","reject","lastError","intervalId","finished","promiseStatus","overallTimeoutTimer","usingFakeTimers","jestFakeTimersAreEnabled","checkExpectation","fakeTimeRemaining","error","Error","copyStackTrace","handleTimeout","jest","advanceTimersByTime","setImmediate","setTimeout","setInterval","checkRealTimersCallback","onDone","done","clearTimeout","clearInterval","type","result","then","promiseResult","resolvedValue","rejectedValue","waitFor","options","ErrorWithStack","optionsWithStackTrace","checkReactVersionAtLeast","previousActEnvironment","getIsReactActEnvironment","setReactActEnvironment","act"],"sources":["../src/waitFor.ts"],"sourcesContent":["/* globals jest */\nimport act, { setReactActEnvironment, getIsReactActEnvironment } from './act';\nimport { getConfig } from './config';\nimport { ErrorWithStack, copyStackTrace } from './helpers/errors';\nimport {\n setTimeout,\n clearTimeout,\n setImmediate,\n jestFakeTimersAreEnabled,\n} from './helpers/timers';\nimport { checkReactVersionAtLeast } from './react-versions';\n\nconst DEFAULT_INTERVAL = 50;\n\nexport type WaitForOptions = {\n timeout?: number;\n interval?: number;\n stackTraceError?: ErrorWithStack;\n onTimeout?: (error: unknown) => Error;\n};\n\nfunction waitForInternal<T>(\n expectation: () => T,\n {\n timeout = getConfig().asyncUtilTimeout,\n interval = DEFAULT_INTERVAL,\n stackTraceError,\n onTimeout,\n }: WaitForOptions\n): Promise<T> {\n if (typeof expectation !== 'function') {\n throw new TypeError('Received `expectation` arg must be a function');\n }\n\n // eslint-disable-next-line no-async-promise-executor\n return new Promise(async (resolve, reject) => {\n let lastError: unknown, intervalId: ReturnType<typeof setTimeout>;\n let finished = false;\n let promiseStatus = 'idle';\n\n let overallTimeoutTimer: NodeJS.Timeout | null = null;\n\n const usingFakeTimers = jestFakeTimersAreEnabled();\n\n if (usingFakeTimers) {\n checkExpectation();\n // this is a dangerous rule to disable because it could lead to an\n // infinite loop. However, eslint isn't smart enough to know that we're\n // setting finished inside `onDone` which will be called when we're done\n // waiting or when we've timed out.\n // eslint-disable-next-line no-unmodified-loop-condition\n let fakeTimeRemaining = timeout;\n while (!finished) {\n if (!jestFakeTimersAreEnabled()) {\n const error = new Error(\n `Changed from using fake timers to real timers while using waitFor. This is not allowed and will result in very strange behavior. Please ensure you're awaiting all async things your test is doing before changing to real timers. For more info, please go to https://github.com/testing-library/dom-testing-library/issues/830`\n );\n if (stackTraceError) {\n copyStackTrace(error, stackTraceError);\n }\n reject(error);\n return;\n }\n\n // when fake timers are used we want to simulate the interval time passing\n if (fakeTimeRemaining <= 0) {\n handleTimeout();\n return;\n } else {\n fakeTimeRemaining -= interval;\n }\n\n // we *could* (maybe should?) use `advanceTimersToNextTimer` but it's\n // possible that could make this loop go on forever if someone is using\n // third party code that's setting up recursive timers so rapidly that\n // the user's timer's don't get a chance to resolve. So we'll advance\n // by an interval instead. (We have a test for this case).\n jest.advanceTimersByTime(interval);\n\n // It's really important that checkExpectation is run *before* we flush\n // in-flight promises. To be honest, I'm not sure why, and I can't quite\n // think of a way to reproduce the problem in a test, but I spent\n // an entire day banging my head against a wall on this.\n checkExpectation();\n\n // In this rare case, we *need* to wait for in-flight promises\n // to resolve before continuing. We don't need to take advantage\n // of parallelization so we're fine.\n // https://stackoverflow.com/a/59243586/971592\n // eslint-disable-next-line no-await-in-loop\n await new Promise((resolve) => setImmediate(resolve));\n }\n } else {\n overallTimeoutTimer = setTimeout(handleTimeout, timeout);\n intervalId = setInterval(checkRealTimersCallback, interval);\n checkExpectation();\n }\n\n function onDone(\n done: { type: 'result'; result: T } | { type: 'error'; error: unknown }\n ) {\n finished = true;\n if (overallTimeoutTimer) {\n clearTimeout(overallTimeoutTimer);\n }\n\n if (!usingFakeTimers) {\n clearInterval(intervalId);\n }\n\n if (done.type === 'error') {\n reject(done.error);\n } else {\n resolve(done.result);\n }\n }\n\n function checkRealTimersCallback() {\n if (jestFakeTimersAreEnabled()) {\n const error = new Error(\n `Changed from using real timers to fake timers while using waitFor. This is not allowed and will result in very strange behavior. Please ensure you're awaiting all async things your test is doing before changing to fake timers. For more info, please go to https://github.com/testing-library/dom-testing-library/issues/830`\n );\n if (stackTraceError) {\n copyStackTrace(error, stackTraceError);\n }\n return reject(error);\n } else {\n return checkExpectation();\n }\n }\n\n function checkExpectation() {\n if (promiseStatus === 'pending') return;\n try {\n const result = expectation();\n\n // @ts-ignore result can be a promise\n // eslint-disable-next-line promise/prefer-await-to-then\n if (typeof result?.then === 'function') {\n const promiseResult: Promise<T> = result as any;\n promiseStatus = 'pending';\n // eslint-disable-next-line promise/catch-or-return, promise/prefer-await-to-then\n promiseResult.then(\n (resolvedValue) => {\n promiseStatus = 'resolved';\n onDone({ type: 'result', result: resolvedValue });\n return;\n },\n (rejectedValue) => {\n promiseStatus = 'rejected';\n lastError = rejectedValue;\n return;\n }\n );\n } else {\n onDone({ type: 'result', result: result });\n }\n // If `callback` throws, wait for the next mutation, interval, or timeout.\n } catch (error) {\n // Save the most recent callback error to reject the promise with it in the event of a timeout\n lastError = error;\n }\n }\n\n function handleTimeout() {\n let error;\n if (lastError) {\n error = lastError;\n if (stackTraceError) {\n copyStackTrace(error, stackTraceError);\n }\n } else {\n error = new Error('Timed out in waitFor.');\n if (stackTraceError) {\n copyStackTrace(error, stackTraceError);\n }\n }\n if (typeof onTimeout === 'function') {\n onTimeout(error);\n }\n onDone({ type: 'error', error });\n }\n });\n}\n\nexport default async function waitFor<T>(\n expectation: () => T,\n options?: WaitForOptions\n): Promise<T> {\n // Being able to display a useful stack trace requires generating it before doing anything async\n const stackTraceError = new ErrorWithStack('STACK_TRACE_ERROR', waitFor);\n const optionsWithStackTrace = { stackTraceError, ...options };\n\n if (checkReactVersionAtLeast(18, 0)) {\n const previousActEnvironment = getIsReactActEnvironment();\n setReactActEnvironment(false);\n\n try {\n return await waitForInternal(expectation, optionsWithStackTrace);\n } finally {\n setReactActEnvironment(previousActEnvironment);\n }\n }\n\n if (!checkReactVersionAtLeast(16, 9)) {\n return waitForInternal(expectation, optionsWithStackTrace);\n }\n\n let result: T;\n\n await act(async () => {\n result = await waitForInternal(expectation, optionsWithStackTrace);\n });\n\n // Either we have result or `waitFor` threw error\n return result!;\n}\n"],"mappings":";;;;;;AACA,IAAAA,IAAA,GAAAC,uBAAA,CAAAC,OAAA;AACA,IAAAC,OAAA,GAAAD,OAAA;AACA,IAAAE,OAAA,GAAAF,OAAA;AACA,IAAAG,OAAA,GAAAH,OAAA;AAMA,IAAAI,cAAA,GAAAJ,OAAA;AAA4D,SAAAK,yBAAAC,WAAA,eAAAC,OAAA,kCAAAC,iBAAA,OAAAD,OAAA,QAAAE,gBAAA,OAAAF,OAAA,YAAAF,wBAAA,YAAAA,CAAAC,WAAA,WAAAA,WAAA,GA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WAAW,EAAE2C,qBAAqB,CAAC;EAC5D;EAEA,IAAIR,MAAS;EAEb,MAAM,IAAAa,YAAG,EAAC,YAAY;IACpBb,MAAM,GAAG,MAAMpC,eAAe,CAACC,WAAW,EAAE2C,qBAAqB,CAAC;EACpE,CAAC,CAAC;;EAEF;EACA,OAAOR,MAAM;AACf"}
|
|
1
|
+
{"version":3,"file":"waitFor.js","names":["_act","_interopRequireWildcard","require","_config","_flushMicroTasks","_errors","_timers","_reactVersions","_getRequireWildcardCache","nodeInterop","WeakMap","cacheBabelInterop","cacheNodeInterop","obj","__esModule","default","cache","has","get","newObj","hasPropertyDescriptor","Object","defineProperty","getOwnPropertyDescriptor","key","prototype","hasOwnProperty","call","desc","set","DEFAULT_INTERVAL","waitForInternal","expectation","timeout","getConfig","asyncUtilTimeout","interval","stackTraceError","onTimeout","TypeError","Promise","resolve","reject","lastError","intervalId","finished","promiseStatus","overallTimeoutTimer","usingFakeTimers","jestFakeTimersAreEnabled","checkExpectation","fakeTimeRemaining","error","Error","copyStackTrace","handleTimeout","jest","advanceTimersByTime","setImmediate","setTimeout","setInterval","checkRealTimersCallback","onDone","done","clearTimeout","clearInterval","type","result","then","promiseResult","resolvedValue","rejectedValue","String","waitFor","options","ErrorWithStack","optionsWithStackTrace","checkReactVersionAtLeast","previousActEnvironment","getIsReactActEnvironment","setReactActEnvironment","flushMicroTasks","act"],"sources":["../src/waitFor.ts"],"sourcesContent":["/* globals jest */\nimport act, { setReactActEnvironment, getIsReactActEnvironment } from './act';\nimport { getConfig } from './config';\nimport { flushMicroTasks } from './flushMicroTasks';\nimport { ErrorWithStack, copyStackTrace } from './helpers/errors';\nimport {\n setTimeout,\n clearTimeout,\n setImmediate,\n jestFakeTimersAreEnabled,\n} from './helpers/timers';\nimport { checkReactVersionAtLeast } from './react-versions';\n\nconst DEFAULT_INTERVAL = 50;\n\nexport type WaitForOptions = {\n timeout?: number;\n interval?: number;\n stackTraceError?: ErrorWithStack;\n onTimeout?: (error: Error) => Error;\n};\n\nfunction waitForInternal<T>(\n expectation: () => T,\n {\n timeout = getConfig().asyncUtilTimeout,\n interval = DEFAULT_INTERVAL,\n stackTraceError,\n onTimeout,\n }: WaitForOptions\n): Promise<T> {\n if (typeof expectation !== 'function') {\n throw new TypeError('Received `expectation` arg must be a function');\n }\n\n // eslint-disable-next-line no-async-promise-executor\n return new Promise(async (resolve, reject) => {\n let lastError: unknown, intervalId: ReturnType<typeof setTimeout>;\n let finished = false;\n let promiseStatus = 'idle';\n\n let overallTimeoutTimer: NodeJS.Timeout | null = null;\n\n const usingFakeTimers = jestFakeTimersAreEnabled();\n\n if (usingFakeTimers) {\n checkExpectation();\n // this is a dangerous rule to disable because it could lead to an\n // infinite loop. However, eslint isn't smart enough to know that we're\n // setting finished inside `onDone` which will be called when we're done\n // waiting or when we've timed out.\n // eslint-disable-next-line no-unmodified-loop-condition\n let fakeTimeRemaining = timeout;\n while (!finished) {\n if (!jestFakeTimersAreEnabled()) {\n const error = new Error(\n `Changed from using fake timers to real timers while using waitFor. This is not allowed and will result in very strange behavior. Please ensure you're awaiting all async things your test is doing before changing to real timers. For more info, please go to https://github.com/testing-library/dom-testing-library/issues/830`\n );\n if (stackTraceError) {\n copyStackTrace(error, stackTraceError);\n }\n reject(error);\n return;\n }\n\n // when fake timers are used we want to simulate the interval time passing\n if (fakeTimeRemaining <= 0) {\n handleTimeout();\n return;\n } else {\n fakeTimeRemaining -= interval;\n }\n\n // we *could* (maybe should?) use `advanceTimersToNextTimer` but it's\n // possible that could make this loop go on forever if someone is using\n // third party code that's setting up recursive timers so rapidly that\n // the user's timer's don't get a chance to resolve. So we'll advance\n // by an interval instead. (We have a test for this case).\n jest.advanceTimersByTime(interval);\n\n // It's really important that checkExpectation is run *before* we flush\n // in-flight promises. To be honest, I'm not sure why, and I can't quite\n // think of a way to reproduce the problem in a test, but I spent\n // an entire day banging my head against a wall on this.\n checkExpectation();\n\n // In this rare case, we *need* to wait for in-flight promises\n // to resolve before continuing. We don't need to take advantage\n // of parallelization so we're fine.\n // https://stackoverflow.com/a/59243586/971592\n // eslint-disable-next-line no-await-in-loop\n await new Promise((resolve) => setImmediate(resolve));\n }\n } else {\n overallTimeoutTimer = setTimeout(handleTimeout, timeout);\n intervalId = setInterval(checkRealTimersCallback, interval);\n checkExpectation();\n }\n\n function onDone(\n done: { type: 'result'; result: T } | { type: 'error'; error: unknown }\n ) {\n finished = true;\n if (overallTimeoutTimer) {\n clearTimeout(overallTimeoutTimer);\n }\n\n if (!usingFakeTimers) {\n clearInterval(intervalId);\n }\n\n if (done.type === 'error') {\n reject(done.error);\n } else {\n resolve(done.result);\n }\n }\n\n function checkRealTimersCallback() {\n if (jestFakeTimersAreEnabled()) {\n const error = new Error(\n `Changed from using real timers to fake timers while using waitFor. This is not allowed and will result in very strange behavior. Please ensure you're awaiting all async things your test is doing before changing to fake timers. For more info, please go to https://github.com/testing-library/dom-testing-library/issues/830`\n );\n if (stackTraceError) {\n copyStackTrace(error, stackTraceError);\n }\n return reject(error);\n } else {\n return checkExpectation();\n }\n }\n\n function checkExpectation() {\n if (promiseStatus === 'pending') return;\n try {\n const result = expectation();\n\n // @ts-ignore result can be a promise\n // eslint-disable-next-line promise/prefer-await-to-then\n if (typeof result?.then === 'function') {\n const promiseResult: Promise<T> = result as any;\n promiseStatus = 'pending';\n // eslint-disable-next-line promise/catch-or-return, promise/prefer-await-to-then\n promiseResult.then(\n (resolvedValue) => {\n promiseStatus = 'resolved';\n onDone({ type: 'result', result: resolvedValue });\n return;\n },\n (rejectedValue) => {\n promiseStatus = 'rejected';\n lastError = rejectedValue;\n return;\n }\n );\n } else {\n onDone({ type: 'result', result: result });\n }\n // If `callback` throws, wait for the next mutation, interval, or timeout.\n } catch (error) {\n // Save the most recent callback error to reject the promise with it in the event of a timeout\n lastError = error;\n }\n }\n\n function handleTimeout() {\n let error: Error;\n if (lastError) {\n if (lastError instanceof Error) {\n error = lastError;\n } else {\n error = new Error(String(lastError));\n }\n\n if (stackTraceError) {\n copyStackTrace(error, stackTraceError);\n }\n } else {\n error = new Error('Timed out in waitFor.');\n if (stackTraceError) {\n copyStackTrace(error, stackTraceError);\n }\n }\n if (typeof onTimeout === 'function') {\n const result = onTimeout(error);\n if (result) {\n error = result;\n }\n }\n onDone({ type: 'error', error });\n }\n });\n}\n\nexport default async function waitFor<T>(\n expectation: () => T,\n options?: WaitForOptions\n): Promise<T> {\n // Being able to display a useful stack trace requires generating it before doing anything async\n const stackTraceError = new ErrorWithStack('STACK_TRACE_ERROR', waitFor);\n const optionsWithStackTrace = { stackTraceError, ...options };\n\n if (checkReactVersionAtLeast(18, 0)) {\n const previousActEnvironment = getIsReactActEnvironment();\n setReactActEnvironment(false);\n\n try {\n const result = await waitForInternal(expectation, optionsWithStackTrace);\n // Flush the microtask queue before restoring the `act` environment\n await flushMicroTasks();\n return result;\n } finally {\n setReactActEnvironment(previousActEnvironment);\n }\n }\n\n if (!checkReactVersionAtLeast(16, 9)) {\n return waitForInternal(expectation, optionsWithStackTrace);\n }\n\n let result: T;\n\n await act(async () => {\n result = await waitForInternal(expectation, optionsWithStackTrace);\n });\n\n // Either we have result or `waitFor` threw error\n return result!;\n}\n"],"mappings":";;;;;;AACA,IAAAA,IAAA,GAAAC,uBAAA,CAAAC,OAAA;AACA,IAAAC,OAAA,GAAAD,OAAA;AACA,IAAAE,gBAAA,GAAAF,OAAA;AACA,IAAAG,OAAA,GAAAH,OAAA;AACA,IAAAI,OAAA,GAAAJ,OAAA;AAMA,IAAAK,cAAA,GAAAL,OAAA;AAA4D,SAAAM,yBAAAC,WAAA,eAAAC,OAAA,kCAAAC,iBAAA,OAAAD,OAAA,QAAAE,gBAAA,OAAAF,OAAA,YAAAF,wBAAA,YAAAA,CAAAC,WAAA,WAAAA,WAAA,GAAAG,gBAAA,GAAAD,iBAAA,KAAAF,WAAA;AAAA,SAAAR,wBAAAY,GAAA,EAAAJ,WAAA,SAAAA,WAAA,IAAAI,GAAA,IAAAA,GAAA,CAAAC,UAAA,WA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ACR,IAAAa,2BAAsB,EAACF,sBAAsB,CAAC;IAChD;EACF;EAEA,IAAI,CAAC,IAAAD,uCAAwB,EAAC,EAAE,EAAE,CAAC,CAAC,EAAE;IACpC,OAAO9C,eAAe,CAACC,WAAW,EAAE4C,qBAAqB,CAAC;EAC5D;EAEA,IAAIT,MAAS;EAEb,MAAM,IAAAe,YAAG,EAAC,YAAY;IACpBf,MAAM,GAAG,MAAMpC,eAAe,CAACC,WAAW,EAAE4C,qBAAqB,CAAC;EACpE,CAAC,CAAC;;EAEF;EACA,OAAOT,MAAM;AACf"}
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@testing-library/react-native",
|
|
3
|
-
"version": "12.
|
|
3
|
+
"version": "12.1.0",
|
|
4
4
|
"description": "Simple and complete React Native testing utilities that encourage good testing practices.",
|
|
5
5
|
"main": "build/index.js",
|
|
6
6
|
"types": "build/index.d.ts",
|
|
@@ -54,13 +54,16 @@
|
|
|
54
54
|
"flow-copy-source": "^2.0.9",
|
|
55
55
|
"jest": "^29.4.0",
|
|
56
56
|
"react": "18.2.0",
|
|
57
|
-
"react-native": "0.71.
|
|
57
|
+
"react-native": "0.71.4",
|
|
58
58
|
"react-test-renderer": "18.2.0",
|
|
59
59
|
"strip-ansi": "^6.0.0",
|
|
60
|
-
"typescript": "^
|
|
60
|
+
"typescript": "^5.0.2"
|
|
61
61
|
},
|
|
62
62
|
"dependencies": {
|
|
63
|
-
"
|
|
63
|
+
"@react-navigation/native": "^6.1.6",
|
|
64
|
+
"pretty-format": "^29.0.0",
|
|
65
|
+
"react-native-safe-area-context": "^4.5.1",
|
|
66
|
+
"react-native-screens": "^3.20.0"
|
|
64
67
|
},
|
|
65
68
|
"peerDependencies": {
|
|
66
69
|
"jest": ">=28.0.0",
|
package/typings/index.flow.js
CHANGED